content stringlengths 5 1.05M |
|---|
import numpy as np
import pytest
from structure_factor.hyperuniformity import Hyperuniformity
from structure_factor.point_processes import (
GinibrePointProcess,
HomogeneousPoissonPointProcess,
)
@pytest.mark.parametrize(
"sf, expected",
[
(HomogeneousPoissonPointProcess.structure_factor, Fal... |
import asyncio
import os
import re
id_matcher = re.compile("(?<=/)\d+(?=/)")
async def main():
files = os.listdir("links")
for file in files:
with open(f"links/{file}", encoding="utf-8") as link_file:
links = link_file.readlines()
for link in links:
nlink = lin... |
#!/usr/bin/env python
"""
Entry point for bin/* scripts
"""
__authors__ = "James Bergstra"
__license__ = "3-clause BSD License"
__contact__ = "github.com/hyperopt/hyperopt"
import cPickle
import logging
import os
import base
import utils
logger = logging.getLogger(__name__)
from .base import SerialExperimen... |
#notecard specific ATTN requests and processing
from command import Commands
CM = Commands
remoteCommandQueue = "commands.qi"
def isEndOfQueueErr(e):
return str.__contains__(e, "{note-noexist}")
def _extractAndEnqueueCommands(body):
for c in body.items():
command = c[0]
args = t... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup (
name = "katsdpdisp",
description = "Karoo Array Telescope Online Signal Displays",
author = "MeerKAT SDP team",
author_email = "sdpdev+katsdpdisp@ska.ac.za",
packages = find_packages(),
package_data={'': ['html/*']},
... |
import numpy
# scipy.special for the sigmoid function expit()
import scipy.special
# neural network class definition
class neuralNetwork:
# initialise the neural network
def __init__(self, inputnodes, hiddennodes, hiddenlayers, outputnodes, learningrate):
# set number of nodes in each input, hidde... |
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db, models
from app.models import User, Bucket, BucketItem
import unittest
import coverage
import os
import forgery_py as faker
from random import randint
from sqlalchemy.exc import IntegrityError
# Initializing the... |
__all__ = ('animate', )
from functools import partial
from kivy.clock import Clock
from kivy.animation import AnimationTransition
from asynckivy import sleep_forever
async def animate(target, **kwargs): # noqa:C901
'''
animate
=======
An async version of ``kivy.animation.Animation``.
Usage
... |
from logging import getLogger
def settings_handler():
"""
This function is started if the bot receives settings command (not used yet)
"""
logger = getLogger()
logger.info("settings_handler started")
|
"""
gfa_reduce.xmatch
================
Cross-matching utilities for the DESI GFA
off-line reduction pipeline.
"""
|
"""Second-Generation p-values and delta-gaps."""
def sgpvalue(*, null_lo, null_hi, est_lo, est_hi, inf_correction: float = 1e-5,
warnings: bool = True):
"""
Second-Generation p-values and delta-gaps.
#TODO: Output is still not pretty-> need to remove numpy type information
Parameters
... |
#!/usr/bin/env python3
# Requires Python 3.6 and above
from os import chdir, makedirs, path
from sys import platform
from math import pi, sin, cos, inf
import webbrowser
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from ezdxf.r12writer import r12writer
from polylabel import polylabel
# Use Wi... |
import os
import copy
import torch
import torch.nn as nn
import numpy as np
from .network_blocks import Focus, SPPBottleneck, BaseConv, CoordAtt
from .bev_transformer import DropPath, TransBlock
from .swin import BasicLayer
class LayerNormChannel(nn.Module):
"""
LayerNorm only for Channel Dimension.
Inp... |
from schematics.types import IntType, StringType, UTCDateTimeType
from sqlalchemy.sql import and_, func, select
from playlog.lib.validation import OrderType, validate
from playlog.models import album, artist
async def create(conn, artist_id, name, plays, first_play, last_play):
return await conn.scalar(album.ins... |
"""
Module that provides a class that filters profanities
"""
__author__ = "leoluk"
__version__ = '0.0.1'
import random
import re
arrBad = [
'2g1c',
'2 girls 1 cup',
'acrotomophilia',
'anal',
'anilingus',
'anus',
'arsehole',
'ass',
'asshole',
'assmunch',
'auto erotic',
... |
#!/usr/bin/python
from mod_pywebsocket import msgutil, util
def web_socket_do_extra_handshake(request):
pass # Always accept.
def web_socket_transfer_data(request):
msgutil.send_message(request, request.ws_location.split('?', 1)[1])
|
from django.shortcuts import render
from formtools.wizard.views import SessionWizardView
from .forms import StepOneForm, StepTwoForm
def index(request):
return render(request, 'multistepapp/index.html')
class FormWizardView(SessionWizardView):
template_name ='multistepapp/steps.html'
form_list = [StepOn... |
from django.db import models
from django.db.models import CharField
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length = 20)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length = 255)
b... |
from typing import Union
class MessageTransfer:
id: str
text: Union[str, None]
skip: bool
terminate_group: bool
def __init__(
self,
*,
id: str,
text: Union[str, None] = None,
skip: bool = False,
terminate_group: bool = False
) -> None:
self.id = id
self.text = text
self.skip = skip
self.ter... |
import config as cfig
import bot as udpbot
import commands as twitchcommands
import sys
import urllib.request
import random
# Load the config settings
print('==> Loading settings')
conf = cfig.config()
# Check if we have generated a default config.ini, if so exit
if conf.default == True:
print('[!] Could not find... |
# IMAGE FILE
import struct
import imghdr
def getImageSize(fname):
with open(fname, 'rb') as fhandle:
head = fhandle.read(24)
if len(head) != 24:
raise RuntimeError("Invalid Header")
if imghdr.what(fname) == 'png':
check = struct.unpack('>i', head[4:8])[... |
#!/usr/bin/python3
import argparse
parser = argparse.ArgumentParser(
description="Caesar Encryptor/Decryptor.")
parser.add_argument("-dec",dest="mode",action="store_true",help="For decryption.")
args = parser.parse_args()
if args.mode == 0:
text = input("Message to be encrypted: ")
key = int(input(... |
from __future__ import absolute_import
from sentry.relay.projectconfig_debounce_cache.base import ProjectConfigDebounceCache
from sentry.utils.redis import get_dynamic_cluster_from_options, validate_dynamic_cluster
REDIS_CACHE_TIMEOUT = 3600 # 1 hr
def _get_redis_key(project_id, organization_id):
if organizat... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
import sys
import os
cwd = os.getcwd()
path = "files"
try:
os.mkdir(path)
except OSError:
print ("Creation of the directory %s failed" % path)
else:
print ("Successfully created the directory %s " % path)
filename = 'files/yourprogram'
writefile = open(filename, "w+")
writefile.write("the current workin... |
from abc import abstractmethod
from typing import List
from open_mafia_engine.core.all import (
Actor,
EPrePhaseChange,
Faction,
Game,
handler,
Event,
)
from .auxiliary import TempPhaseAux
class ECreateFactionChat(Event):
"""Event that signals creating a faction chat."""
def __init_... |
import numpy as np
from numpy.linalg import lstsq
from scipy.optimize import lsq_linear
from . import moduleFrame
class FitSignals(moduleFrame.Strategy):
def __call__(self, signalVars, knownSpectra):
# rows are additions, columns are contributors
knownMask = ~np.isnan(knownSpectra[:, 0])
... |
"""
Created on Wed Jan 20 10:15:31 2021
@author: Lucas.singier
"""
import socket
import select
IP = "127.0.0.1"
PORT = 1234
# Creation de la socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# On set les options du socket
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEA... |
import distdl
import distdl.nn as dnn
import matplotlib.pyplot as plt
import numpy as np
import os
import time
import torch
from argparse import ArgumentParser
from distdl.utilities.torch import *
from dfno import *
from mat73 import loadmat
from matplotlib.animation import FuncAnimation
from mpi4py import MPI
from pa... |
import tradeStock as t
import robin_stocks as r
import financial as f
import trading_algorithms as a
import numpy as np
import signal
import concurrent.futures
import time
import matplotlib.pyplot as plt
import indicators as ind
from Method_kd import KD
from long_algo import Long_algo
from Method_BOLL_SMA import BO... |
#!/usr/bin/env python
import argparse
import sys
import jinja2
import markdown
from os import listdir, makedirs
from os.path import isfile, join, exists
reload(sys)
sys.setdefaultencoding('utf-8')
def main(args=None):
src_path = 'src/pages'
dist_path = 'dist'
with open('src/layouts/template.html', 'r'... |
# -*- coding: utf-8 -*-
"""
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class UpdateDeviceSwitchPortModel(object):
"""Implementation of the 'updateDeviceSwitchPort' model.
TODO: type model description here.
Attributes:
... |
from flask import Flask, request, render_template, jsonify
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
# Time zones
import pytz
# time & atexit: scheduler of temperature recording
import time
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
import datetime
impor... |
# Compare between two learning rates for the same model and dataset
EXP_GROUPS = {'mnist':
[
{'lr':1e-3, 'model':'mlp', 'dataset':'mnist'},
{'lr':1e-4, 'model':'mlp', 'dataset':'mnist'}
]
} |
#
# MIT License
#
# Copyright (c) 2018 WillQ
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
import demistomock as demisto
import pytest
import ShowCampaignSenders
INCIDENT_IDS = [{"id": '1'}, {"id": '2'}, {"id": '3'}]
DEMISTO_RESULT = [
{
'Contents': '[{"emailfrom": "example1@support.com"}, {"emailfrom": "example2@support.co"}, '
'{"emailfrom": "example1@support.com"}, {"ema... |
# -*- coding: utf-8 -*-
"""
VTK Point Cloud Rendered using PyVista Library
Create and render car shapes
Author: Jari Honkanen
"""
import numpy as np
import math
import pyvista as pv
from pyvista import examples
def get_example_point_cloud(decimateFactor = 0.05):
""" Create numpy array of points from... |
"""Serializer fields"""
import collections
from django.contrib.gis import geos, forms
from django.db.models.query import QuerySet
from rest_framework import renderers
from rest_framework.fields import Field, FileField
from spillway.compat import json
from spillway.forms import fields
class GeometryField(Field):
... |
SECRET_KEY = 'secret'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'priorities',
'USER': 'vagrant',
}
}
# This should be a local folder created for use with the install_media command
MEDIA_ROOT = '/usr/local/apps/madrona-priorities/mediaroot/'... |
#!/usr/bin/python3
# server.py - Test server for web services.
# Monitor a TCP port for messages to be displayed on the pimoroni scroll phat hd.
import socket
import scrollphathd
import configparser
import logging
import signal
import sys
import os
import datetime
sock = 0
# expand_file_name - If file_name is not a... |
#!/usr/bin/python3
import socket
import sys
if len(sys.argv) < 2:
print('usage: tcp_server port')
sys.exit(1)
GREEN = '\033[38;5;82m'
RED = '\033[38;5;'
print(GREEN)
# Banner
print("================")
print("|| TCP Server ||")
print("================")
port = int(sys.argv[1])
server = socket.socket(socket.... |
import os
import requests
import json
import pandas as pd
from datetime import datetime, timedelta
ENV = "sandbox" #Use "sandbox" when testing, and "api" if you have an account at Tradier
API_TOKEN = "" #Fill in your Tradier API Token here
###
#Script starts here
###
def main():
#Get list of symbols from file
... |
"""Modified code from https://developers.google.com/optimization/routing/tsp#or-tools """
# Copyright Matthew Mack (c) 2020 under CC-BY 4.0: https://creativecommons.org/licenses/by/4.0/
from __future__ import print_function
import math
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_sol... |
# -*- coding: utf-8 -*-
#---------------------------------------------------------------------------
# Copyright 2020 VMware, Inc. All rights reserved.
# AUTO GENERATED FILE -- DO NOT MODIFY!
#
# vAPI stub file for package com.vmware.nsx_policy.infra.domains.
#---------------------------------------------------------... |
import sys
sys.setrecursionlimit(10**6)
def DFS(u):
global found
visisted[u] = True
checkedLoop[u] = True
for x in graph[u]:
if checkedLoop[x] == True:
found = True
return
if visisted[x] == False:
DFS(x)
checkedLoop[u] = False
TC = int(input())
for _ in range(TC):
found = False
N, M = map(int,... |
#!/usr/bin/env python3
with open('input', 'r') as f:
data = [line.rstrip().split() for line in f.readlines()]
valid_lines = 0
for line in data:
if len(set(line)) == len(line):
valid_lines += 1
print('There were {} valid lines'.format(valid_lines))
|
from muzero.network.muzero import MuZero, MuZeroAtariConfig
import gym
import asyncio
if __name__ == '__main__':
environment = gym.make('Breakout-v0')
muzero_config = MuZeroAtariConfig(environment=environment)
muzero = MuZero(muzero_config)
muzero.start_training()
|
"""nla_client_lib.py provides a wrapper to calls to the REST-style API which interfaces with the
CEDA NLA system. Common calls, such as `ls`, `quota` and making requests are wrapped in a few
functions."""
__author__ = 'sjp23'
import os
import requests
import json
from nla_client.nla_client_settings import NLA... |
# file openpyxl/tests/test_dump.py
# Copyright (c) 2010-2011 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use... |
from __future__ import print_function, division, absolute_import
import itertools
import sys
# unittest only added in 3.4 self.subTest()
if sys.version_info[0] < 3 or sys.version_info[1] < 4:
import unittest2 as unittest
else:
import unittest
# unittest.mock is not available in 2.7 (though unittest2 might cont... |
import time
import logging
from healthtools.scrapers.base_scraper import Scraper
from healthtools.config import SITES, SMALL_BATCH_NHIF
log = logging.getLogger(__name__)
class NhifInpatientScraper(Scraper):
"""Scraper for the NHIF accredited inpatient facilities"""
def __init__(self):
super(NhifInpat... |
from fpdf import FPDF
import os
import re
from scipy.signal.spectral import spectrogram
class PDF(FPDF):
def __init__(self):
super().__init__()
self.WIDTH = 210
self.HEIGHT = 297
def header(self):
# Custom logo and positioning
# Create an `asset... |
from typing import Optional
import colorful as cf
from kolga.utils.models import SubprocessResult
class Logger:
"""
Class for logging of events in the DevOps pipeline
"""
def _create_message(self, message: str, icon: Optional[str] = None) -> str:
icon_string = f"{icon} " if icon else ""
... |
# This contains all helper functions for the project
import re
# -------------------------------------------------- USERS -------------------------------------------------------------
def find_special_chars(string):
regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
if regex.search(string) == None:
return ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Software License Agreement (BSD License)
#
# Copyright (c) 2013 PAL Robotics SL.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code ... |
# Generated by Django 3.1.7 on 2021-04-22 15:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Carletapp', '0015_auto_20210421_1451'),
]
operations = [
migrations.CreateModel(
name='Wallet',... |
#!/usr/bin/env python
"""
Artesanal example Pipe without Pipe class.
"""
__author__ = "Rafael García Cuéllar"
__email__ = "r.gc@hotmail.es"
__copyright__ = "Copyright (c) 2018 Rafael García Cuéllar"
__license__ = "MIT"
from concurrent.futures import ProcessPoolExecutor
import time
import random
def worker(arg):... |
import os
DEBUG = os.getenv('DEBUG', False)
PORT = os.getenv('PORT', 80)
|
"""
Test model creation with custom fields
"""
from django.test import TestCase
from django_any.models import any_model
from testapp.models import ModelWithCustomField
class CustomFieldsTest(TestCase):
def test_created_model_with_custom_field(self):
model = any_model(ModelWithCustomField)
self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.