id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3213086 | import argparse
from smd.data.data_generator import DataGenerator
from smd.data.dataset_loader import DatasetLoader
from smd.models.model_loader import load_model, compile_model
from smd.data.data_augmentation import random_loudness_spec, random_filter_spec, block_mixing_spec, pitch_time_deformation_spec
from smd.data ... |
3213091 | import cv2
import numpy as np
left_ear_cascade = cv2.CascadeClassifier('./cascade_files/haarcascade_mcs_leftear.xml')
right_ear_cascade = cv2.CascadeClassifier('./cascade_files/haarcascade_mcs_rightear.xml')
if left_ear_cascade.empty():
raise IOError('Unable to load the left ear cascade classifier xml file')... |
3213112 | import json
from config import *
from auth import *
from flask import Flask, render_template, request
from script import *
#! Flask app init
app = Flask(__name__)
#! Index page
@app.route("/", methods=["GET"])
def index():
return render_template('index.html', TRADE_SYMBOL=TRADE_SYMBOL)
#! Webhook connection rout... |
3213119 | import warnings
warnings.warn("This package is experimental and could change or "
"be removed in the future. "
"`ml.features.normalization` can be used instead.")
from .c_scaler_sklearn import CScalerSkLearn
from .c_scaler_norm import CScalerNorm
from .c_scaler_minmax import CScalerMinMax
f... |
3213129 | import autodisc as ad
import ipywidgets
import collections
import zipfile
import numpy as np
import warnings
import os
import plotly
from PIL import Image
from autodisc.gui.jupyter.misc import create_colormap, transform_image_from_colormap, transform_image_PIL_to_bytes
''' --------------------------------------------... |
3213134 | import random
from typing import List, Optional
from interfaces.SentenceOperation import SentenceOperation
from tasks.TaskTypes import TaskType
class SpeechDisfluencyPerturbation(SentenceOperation):
tasks: List[TaskType] = [
TaskType.TEXT_CLASSIFICATION,
TaskType.TEXT_TO_TEXT_GENERATION,
]
... |
3213136 | import json
import numpy as np
import os
import base64
from models.img-model.score import score
from PIL import Image
DATASET_PATH = "models/img-model/dataset/data/"
#load data into numpy array
img_path = os.path.join(DATASET_PATH, "0.png")
with open(img_path, 'rb') as img_file:
img_b64 = base64.b64encode(img_fil... |
3213141 | import mxnet as mx
import net_symbols as syms
def create_block(data, name, num_filter, kernel, pad=0, stride=1, dilate=1, workspace=512,
use_global_stats=True, lr_type="alex"):
res = syms.conv(data=data, name="res" + name, num_filter=num_filter, pad=pad, kernel=kernel, stride=stride,
... |
3213189 | import threading
from peewee import *
from playhouse.kv import JSONKeyStore
from playhouse.kv import KeyStore
from playhouse.kv import PickledKeyStore
from playhouse.tests.base import PeeweeTestCase
from playhouse.tests.base import skip_if
class TestKeyStore(PeeweeTestCase):
def setUp(self):
super(TestKe... |
3213195 | from ctc_score.scorer import Scorer
class DialogScorer(Scorer):
def __init__(self, align, aggr_type='sum', device='cuda'):
Scorer.__init__(self, align=align, aggr_type=aggr_type, device=device)
def score(self, fact, dialog_history, hypo, aspect, remove_stopwords=True):
# if 'topical_chat' in ... |
3213222 | import torch
def log_likelihood(importance_weights: torch.Tensor, weights: torch.Tensor = None) -> torch.Tensor:
"""
Given the importance weights of a particle filter, return an estimate of the log likelihood.
Args:
importance_weights: The importance weights of the particle filter.
weight... |
3213237 | from copy import deepcopy
from typing import Any, Dict, List, Tuple
import logging
import dill as pickle
from keras import backend as K
from keras.layers import Dense, Dropout, Layer, TimeDistributed, Embedding
from overrides import overrides
import numpy
import tensorflow
from ..common.checks import ConfigurationErr... |
3213254 | class dotHierarchicDefinition_t(object):
# no doc
aCustomType=None
aHierarchyIdentifier=None
aName=None
aSubHierarchyIds=None
Drawable=None
HierarchyType=None
ModelObject=None
nSubHierarchyIds=None
ObjectParent=None
OperationType=None
|
3213265 | import numpy as np
from sirius import inner, l2norm, CoefficientArray, Logger, diag
import h5py
from copy import deepcopy
from scipy.constants import physical_constants
from mpi4py import MPI
from .free_energy import FreeEnergy, s
logger = Logger()
def _constraint34(u, tau, T, pe, vkw):
"""
Keywoard Argumen... |
3213274 | import pyglet
import pyperclip
import keyword
import tokenize
import io
import os
from pyno.utils import x_y_pan_scale, font
from pyno.draw import quad_aligned
highlight = set(list(__builtins__.keys()) +
list(keyword.__dict__.keys()) +
keyword.kwlist +
['call', 'clean... |
3213316 | import numpy as np
import pytest
from numpy import testing as npt
from metriculous.evaluators._classification_utils import (
ClassificationData,
ProbabilityMatrix,
)
class TestProbabilityMatrix:
def test_that_it_can_be_initialized_from_nested_list(self) -> None:
_ = ProbabilityMatrix(
... |
3213351 | import numpy as np
import datetime
from matplotlib import pyplot as plt
from betellib import tweet, build_string, get_mags_from_AAVSO
def make_plot(days_ago, dates, mag):
print('Making plot...')
time_span = np.max(dates) - np.min(dates)
min_plot = 0
max_plot = 1.4
x_days = 2000
# Make bin... |
3213367 | import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from art.data_generators import *
from art.utils import *
from art.classifiers import *
from art.attacks import *
import numpy as np
import resnet as resnet
import argparse
import models
from tqdm import tqdm
parser = argparse.Argument... |
3213412 | import py4syn
import versioneer
from setuptools import setup, find_packages
readme = open('README.rst').read()
setup(
name='Py4Syn',
author='LNLS',
author_email='<EMAIL>',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
packages=find_packages(),
scripts=[],
url=''... |
3213468 | from __future__ import division
from .base_legacy import np, TimeBased, ma, DataError
from ..io.main_legacy import Saveable
import h5py as h5
from .binned_legacy import TimeBindat, TimeBinner, rad_hz
from .time import num2date
class Velocity(TimeBased, Saveable):
def __repr__(self,):
mmstr = ''
i... |
3213473 | from collections import namedtuple
import tensorflow as tf
import numpy as np
from mvc.action_output import ActionOutput
from mvc.models.networks.base_network import BaseNetwork
from mvc.models.networks.ddpg import initializer, build_target_update
from mvc.models.networks.ddpg import build_optim
from mvc.parametric_f... |
3213475 | from os.path import dirname, join, realpath
from aiohttp.web import Application
from sqli import views
DIR_PATH = dirname(realpath(__file__))
def setup_routes(app: Application):
app.router.add_route('GET', r'/', views.index)
app.router.add_route('POST', r'/', views.index)
app.router.add_route('GET', r'... |
3213547 | from dataclasses import field
from typing import List
from pydantic.dataclasses import dataclass
from ..vae import VAEConfig
@dataclass
class VAE_LinNF_Config(VAEConfig):
"""VAE with linear Normalizing Flow config class.
Parameters:
input_dim (int): The input_data dimension
latent_dim (int)... |
3213629 | import platform
import re
import sys
from distutils.version import LooseVersion
from nose.tools import eq_
from flake8_strict import _process_code
def _test_processing(test_data_path):
with open(test_data_path, 'rt') as f:
code = f.read()
code = code.strip()
expected_errors = set()
for li... |
3213645 | from p3ui import MenuBar, Menu, MenuItem
class MenuBar(MenuBar):
def __init__(self):
super().__init__()
self.add(Menu(
'File',
on_open=lambda: print('file menu opened'),
on_close=lambda: print('file menu closed'),
children=[MenuItem(
... |
3213731 | r"""
Prototype for object model backend for the libNeuroML project
"""
import numpy as np
import neuroml
class ArrayMorphology(neuroml.Morphology):
"""Core of the array-based object model backend.
Provides the core arrays - vertices,connectivity etc.
node_types.
The connectivity array is a list of ... |
3213732 | from typing import Optional
import pytest
from chains import tasks
from chains.models import Message
from users.models import User
pytestmark = [
pytest.mark.django_db(transaction=True),
pytest.mark.freeze_time('2032-12-01 15:30'),
]
@pytest.fixture
def owl(mocker):
return mocker.patch('app.tasks.mail.... |
3213788 | from django.conf.urls import include
from django.urls import path
from django.contrib import admin
from organizations.backends.modeled import ModelInvitation
from test_accounts.models import Account
admin.autodiscover()
app_name = "test_accounts"
urlpatterns = [
path(
"register/",
include(
... |
3213827 | import os
import hashlib
path = '/root/imagenet/resized'
count = 1
for file in os.listdir(path):
# print(count,path,file)
#if (int(file[-12:-5]) > 99990):
# print(file, str(int(file[-12:-5])))
print(os.path.join(path,file),os.path.join(path,str(int(file[-12:-5]))+".jpeg"))
os.rename(os.path.jo... |
3213856 | import torch
import torch.nn as nn
import torch.nn.functional as F
CHANNELS = [20, 50, 500]
#CHANNELS = [40, 100, 500]
#CHANNELS = [10, 20, 100]
#CHANNELS = [6, 16, 120, 84]
#CHANNELS = [12, 32, 120, 84]
#CHANNELS = [32, 32, 120, 84]
class NetCCFFF(nn.Module):
def __init__(self, input_channels):
super(Ne... |
3213857 | from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from .models import Car
from .test import TestCase
class RateViewTest(TestCase):
"""
tests for the RateView
"""
def setUp(self):
self.test_user = self.make_user(username="test_user")
self.fore... |
3213858 | import asyncio
from pathlib import Path
from protostar.cli import ArgumentParserFacade, ArgumentValueFromConfigProvider
from protostar.cli.cli_app import CLIApp
from protostar.protostar_cli import ConfigurationProfileCLISchema, ProtostarCLI
from protostar.protostar_exception import UNEXPECTED_PROTOSTAR_ERROR_MSG
def... |
3213889 | import sys
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
from MySQLdb import *
from MySQLdb.cursors import DictCursor
def get_article(id):
try:
db = connect('localhost','demo','demo',db='demo', cursorclass=DictCursor)
c = db.cursor()
c.execute('SELECT * FROM demo WHERE ... |
3213929 | from tensorflow.keras.preprocessing.text import Tokenizer
# Characters available in our model
MAIN_CHAR_VECTOR = (
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-'.!?,\""
)
# Characters available in the OCR used
ASTER_CHAR_VECTOR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!... |
3213951 | from django.apps import AppConfig
class MapAppConfig(AppConfig):
name = 'mapApp'
verbose_name = "Map App"
def ready(self):
import mapApp.signals
|
3213966 | import asyncio
import time
class AIOTicker:
def __init__(self, at_least_every_ms: int, at_most_every_ms: int):
self._at_most_every = at_most_every_ms / 1000
self._at_least_every = at_least_every_ms / 1000
self._last_tick = 0
self._wait_task: asyncio.Task = None
self._triggered = False
self.... |
3214006 | from src.GNN.CONSTANTS import *
from src.GNN.helper import LayerNormGRUCell, fc_block
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl.function as fn
from torch.nn import init
# This model contains models which were not used in the final implementation
class GraphEncoder(nn.Module):
d... |
3214023 | import pytest
from indy import payment, error
from tests.payment.constants import *
@pytest.mark.asyncio
async def test_build_verify_payment_request_works_for_unknown_payment_method(wallet_handle, did_trustee):
with pytest.raises(error.PaymentUnknownMethodError):
await payment.build_verify_payment_req(wa... |
3214138 | import unittest
import time
import threading
import uuid
import redis
from nose.tools import raises
from nose.tools import eq_
from retools import global_connection
class TestLock(unittest.TestCase):
def _makeOne(self):
from retools.lock import Lock
return Lock
def _lockException(self):
... |
3214155 | import unittest
from pac import dispatcher
from pac.view_controllers import MainViewController
from pac.view_models import MainViewModel
class TestViewControllerHandler(unittest.TestCase):
def test_get_matched_view_model(self):
view_controller = MainViewController()
self.assertTrue(isinstance(view... |
3214194 | from pyemto.examples.emto_input_generator import *
import numpy as np
folder = os.getcwd() # Get current working directory.
emtopath = folder+"/Cr_B2_antiferro" # Folder where the calculations will be performed.
latpath = emtopath
prims = np.array([[1.0,0.0,0.0],
[0.0,1.0,0.0],
... |
3214195 | import re
import jax.numpy as jnp
import numpy as np
import pytest
from pgmax import fgroup, vgroup
def test_single_factor():
with pytest.raises(ValueError, match="Cannot create a FactorGroup with no Factor."):
fgroup.ORFactorGroup(variables_for_factors=[])
A = vgroup.NDVarArray(num_states=2, shape... |
3214204 | from transformers import GPT2Tokenizer, GPT2LMHeadModel
import random
import os
import argparse
def parse_arguments():
"""
Parser.
"""
parser = argparse.ArgumentParser()
parser.add_argument("--model_path",
type=str,
default="belgpt2",
... |
3214243 | from typing import Any, Dict, List, Union
from unittest.mock import patch
from sqlmodel import create_engine
from tests.conftest import get_testing_print_function
def check_calls(calls: List[List[Union[str, Dict[str, Any]]]]):
assert calls[0] == ["Before interacting with the database"]
assert calls[1] == [
... |
3214246 | from sys import stdin, stderr, stdout
from typing import IO
def puts(s: str, fd: IO = stdout, newline: str = "\n") -> None:
"""puts a string into the file descriptor"""
line = "{s}{newline}".format(s=s, newline=newline)
return print(line, end=newline, file=fd)
def piped_in(fd: IO = stdin) -> str:
wi... |
3214266 | import os
import logger
from utils import dict_from_file
def state_helper(def_state: dict, path: dict, log) -> tuple:
no_ini = not os.path.isfile(path['settings'])
no_state = not os.path.isfile(path['state'])
if no_state and no_ini:
return def_state, True, True
ini_version, merge, state_save... |
3214287 | import numpy
from numba import autojit
@autojit(nopython=True)
def poisson1d_GS_SingleItr(nx, dx, p, b):
'''
Gauss-Seidel method for 1D Poisson eq. with Dirichlet BCs at both
ends. Only a single iteration is executed. **blitz** is used.
Parameters:
----------
nx: int, number of grid point... |
3214301 | import os
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from .modules import (
TextEncoder,
DurationPredictor,
RangeParameterPredictor,
GaussianUpsampling,
SamplingWindow,
)
from wavegrad import WaveGrad
from utils.tools import get_mask_from_lengths
... |
3214326 | import tvm
from functools import reduce
from tvm import auto_scheduler
from tvm.auto_scheduler.cost_model import RandomModel, XGBModel
from tvm.auto_scheduler.search_policy import SketchPolicy
def establish_task_ansor(
schedule_gen, schedule_app,
measure_opt, task_name):
target_dag = schedule_app.targ... |
3214422 | import unittest
import struct
from uefi_firmware import efi_compressor
class CompressionTest(unittest.TestCase):
def _test_compress(self, compress_algorithm):
default_buffer = b"AAAAAAAA" * 90
compressed_buffer = compress_algorithm(
default_buffer, len(default_buffer))
self.... |
3214438 | MPI_INF_3DHP_KEYPOINTS = [
'spine_3',
'spine_4_3dhp',
'spine_2',
'spine_extra', # close to spine2
'pelvis_extra',
'neck_extra', # throat
'head_extra',
'headtop',
'left_clavicle_3dhp',
'left_shoulder',
'left_elbow',
'left_wrist',
'left_hand_3dhp',
'right_clavicle... |
3214444 | import warnings
import h5py
import numpy as np
class NaNWarning(UserWarning):
pass
def number_nan(array):
if (np.isscalar(array) and np.isreal(array)) or array.dtype.kind in ['i', 'f']:
return np.sum(np.isnan(array))
else:
return 0
def check_for_nans(handle):
"""
Check for NaN... |
3214447 | import pydwarf
@pydwarf.urist(
name = 'pineapple.deerappear',
title = 'Change Creature Apperance',
version = '1.0.1',
author = '<NAME>',
description = 'Changes the appearance of each deer from a brown D to yellow d.',
arguments = {
'creature': 'Change the creature whose appearance will ... |
3214468 | import os, random, datetime, functools, math, sys, subprocess
try:
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
except ImportError as message:
print(message)
print("Please make sure you have python3, tkinter and ttk installed")
input("Press enter to leave")
exit()
class Preferences:
def ... |
3214518 | from talon import Module, actions
mod = Module()
mod.tag("git")
@mod.action_class
class Action:
def git_numstat(since: str or None):
"""Show git statistics"""
args = "--author='<NAME>'"
if since:
args = f"{args} --since '{since}'"
awk = "awk 'NF==3 {plus+=$1; minus+=$2}... |
3214530 | from functools import lru_cache
import math
class Solution:
def minScoreTriangulation(self, A: List[int]) -> int:
@lru_cache(None)
def dfs(start, end):
if end - start < 2:
return 0
minScore = math.inf
for i in range(start + 1, end):
... |
3214535 | from sqlalchemy import Column, create_engine, orm, types
from sqlalchemy.ext.declarative import declarative_base
from django.http import Http404
from django.test import SimpleTestCase
from rest_framework.test import APIRequestFactory
from rest_witchcraft import serializers, viewsets
factory = APIRequestFactory()
... |
3214563 | import pytest
def test_audit_antibody_mismatched_in_review(testapp,
base_antibody_characterization,
inconsistent_biosample_type):
characterization_review_list = base_antibody_characterization.get('characterization_reviews')
... |
3214576 | from math import *
import Spheral
import mpi
#-------------------------------------------------------------------------------
# A class for tracking the history of a given set of nodes.
#-------------------------------------------------------------------------------
class NodeHistory:
def __init__(self,
... |
3214583 | from gui import Animation
from d_star_lite import DStarLite
from grid import OccupancyGridMap, SLAM
OBSTACLE = 255
UNOCCUPIED = 0
if __name__ == '__main__':
"""
set initial values for the map occupancy grid
|----------> y, column
| (x=0,y=2)
|
V (x=2, y=0)
x, row
"""
x_d... |
3214609 | from selenium import webdriver
from pages.quotes_page import QuotesPage
chrome = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver")
chrome.get("http://quotes.toscrape.com/search.aspx")
page = QuotesPage(chrome)
author = input("Enter the author you'd like quotes from: ")
page.select_author(author)
|
3214650 | import sys
if __name__ == "__main__":
for line in sys.stdin:
rel,x,y = line.strip().split("\t")
i,j = x.split(",")
x = "%s_%s" % (i,j)
print("%s(%s,Y)" % (rel,x))
|
3214658 | import torch
import argparse
import torchvision
import torch.nn as nn
from torch.autograd import Function
from model.base_model import Base_Model
class CIBHash(Base_Model):
def __init__(self, hparams):
super().__init__(hparams=hparams)
def define_parameters(self):
self.vgg = torc... |
3214664 | import numpy as np
import pandas as pd
import pytest
from recoder.data import RecommendationDataset
from recoder.metrics import Recall, NDCG
from recoder.model import Recoder
from recoder.nn import DynamicAutoencoder, MatrixFactorization
from recoder.utils import dataframe_to_csr_matrix
import os
@pytest.mark.param... |
3214673 | import os
import sys
fn_model = sys.argv[1] # the model file
def load_vocab(fn):
d = {}
f = open(fn)
f.readline()
f.readline()
for line in f:
if line.startswith("===="):
break
ll = line.decode('utf8').split()
word = ll[1]
d[word] = int(ll[0])
f.close... |
3214685 | import pytest
import mock
def test_pibrella_red_light_on(GPIO, atexit):
import pibrella
pibrella.light.red.on()
pibrella.light.red.off()
assert GPIO.output.has_calls((
mock.call(pibrella.PB_PIN_LIGHT_RED, True),
mock.call(pibrella.PB_PIN_LIGHT_RED, False)
)) |
3214732 | from manga_py.provider import Provider
from .helpers.std import Std
class MangaPandaCom(Provider, Std):
_cdn = 'https://img.mghubcdn.com/file/imghub'
_api_url = 'https://api.mghubcdn.com/graphql'
def get_chapter_index(self) -> str:
return self.chapter_for_json()
def get_content(self):
... |
3214745 | from typing import Any, Tuple
import arcade
class BackButton(arcade.Sprite):
"""Replaces arcade.TextButton to deal with viewport"""
def __init__(
self,
view: arcade.View,
clicked: str,
normal: str,
viewport: Tuple[float, float],
*args: Any,
**kwargs: A... |
3214756 | import pyclesperanto_prototype as cle
import numpy as np
def test_draw_box():
reference = cle.push(np.asarray([
[0, 0, 0, 0, 0],
[0, 2, 2, 2, 0],
[0, 2, 2, 2, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]))
result = cle.create((5, 5))
cle.set(result, 0)
cle.draw_b... |
3214801 | import os
import json
from pkg_resources import resource_filename
from docutils import nodes
from docutils.utils import new_document
from sphinx.transforms import SphinxTransform
from sphinx.util.docutils import LoggingReporter
from sphinx.util.fileutil import copy_asset
from . import __version__
emoji_styles = {
... |
3214810 | import numpy as np
import pandas as pd
# global variables
from synthpop import NUM_COLS_DTYPES, CAT_COLS_DTYPES
NAN_KEY = 'nan'
NUMTOCAT_KEY = 'numtocat'
class Processor:
def __init__(self, spop):
self.spop = spop
self.processing_dict = {NUMTOCAT_KEY: {},
NAN_KEY:... |
3214852 | from typing import Iterable, Tuple, Optional
import torch
import numpy as np
from tqdm import tqdm
import sys
sys.path.append('..')
from ltss.utils import read_records_csv, reshape_vector, flatten_vector
from ltss.vectorise import vectorise_record
class DataHandler(object):
"""
Contains logic for loading d... |
3214888 | def constant(func):
""" Decorator used to emulate constant values """
def fset(self, value):
raise TypeError("Cannot modify the value of a constant.")
def fget(self):
return func()
return property(fget, fset)
|
3214894 | import logging
verbosity_levels = {0: logging.ERROR,
1: logging.WARNING,
2: logging.INFO,
3: logging.DEBUG,
"ERROR": logging.ERROR,
"WARNING": logging.WARNING,
"INFO": logging.INFO,
... |
3214938 | def get_2away_pairs(local_index_to_kmer, k):
"""local_index_to_kmer is a dictionary where the value is a kmer portion, and the key is the index of the original kmer in which the kmer portion is found. get_2away_pairs returns a list of pairs where each pair of indices corresponds to a pair of kmers different in exactl... |
3214967 | from pathlib import Path
import autofit as af
from autofit.non_linear.paths.sub_directory_paths import (
SubDirectoryPaths, SubDirectoryPathsDirectory,
SubDirectoryPathsDatabase
)
def test_directory():
paths = af.DirectoryPaths()
subdirectory_path = SubDirectoryPaths(
parent=paths,
an... |
3214996 | import getpass
import os
import shutil
import sys
from buildtest.cli.clean import clean
from buildtest.config import SiteConfiguration
from buildtest.defaults import BUILDTEST_ROOT, TUTORIALS_SETTINGS_FILE
from buildtest.tools.docs import build_compiler_examples, build_spack_examples
from buildtest.utils.file import c... |
3215033 | import torch, pdb, os, json
from shared import _cat_
import numpy as np
from model import OptionInfer, Scorer
from collections import defaultdict
def get_model(path, cuda=True):
opt = OptionInfer(cuda)
if path.endswith('.yaml') or path.endswith('.yml'):
from model import JointScorer
model = Jo... |
3215063 | from relaax.common.python.config.base_config import BaseConfig
class DevConfig(BaseConfig):
def __init__(self):
super(DevConfig, self).__init__()
options = DevConfig().load()
|
3215069 | import tacoma as tc
ec = tc.flockwork_P_varying_rates([],10,[0.4,0.8], 600,[ (0, 1./3600.), (300,2./3600.) ], 600,seed=25456)
print ec.edges_out[:5]
print ec.edges_in[:5]
|
3215097 | import os
from pathlib import Path
import requests
import errno
import shutil
import hashlib
import zipfile
import logging
from .tqdm import tqdm
logger = logging.getLogger(__name__)
__all__ = ['unzip', 'download', 'mkdir', 'check_sha1', 'raise_num_file']
def unzip(zip_file_path, root=os.path.expanduser('./')):
... |
3215130 | from edit_distance.models.cnn.model import CNN
from closest_string.triplet.train import execute_train, general_arg_parser
from util.data_handling.data_loader import BOOL_CHOICE
parser = general_arg_parser()
parser.add_argument('--readout_layers', type=int, default=1, help='Number of readout layers')
parser.add_argumen... |
3215144 | import eventlet
import socketio
sio = socketio.Server()
app = socketio.WSGIApp(sio)
PORT = 5000
thread = None
def background():
while True:
sio.sleep(.1)
print("BACKGROUND!")
pass
@sio.on('connect')
def connect(sid, environ):
global thread
print('connect ')
if thread == None:
... |
3215191 | import pytest
from petisco import Persistence
from petisco.extra.sqlalchemy import SqliteConnection, SqliteDatabase
from tests.modules.extra.sqlalchemy.mother.model_filename_mother import (
ModelFilenameMother,
)
@pytest.mark.integration
def test_should_create_persistence_with_sqlite_database():
filename = M... |
3215198 | from x import (
y,
)
assert(
SyntaxWarning,
ThrownHere,
Anyway,
)
assert (
foo
)
assert (
foo and
bar
)
if(
foo and
bar
):
pass
elif(
foo and
bar
):
pass
for x in(
[1,2,3]
):
print(x)
(x for x in (
[1, 2, 3]
))
(
'foo'
) is (
'foo'
)
if (
... |
3215199 | import os, sys
import SiEPIC
try:
import siepic_tools
except:
pass
# import xml before lumapi (SiEPIC.lumerical), otherwise XML doesn't work:
from xml.etree import cElementTree
import math
from SiEPIC.utils import arc, arc_xy, arc_wg, arc_to_waveguide, points_per_circle
import pya
from SiEPIC.utils import get_te... |
3215218 | import numpy as np
from pymoo.operators.repair.bounds_repair import BoundsRepair
def inverse_penality(x, p, xl, xu, alpha=None):
assert len(p) == len(x)
normv = np.linalg.norm(p - x)
# violated boundaries
idl = x < xl
idr = xu < x
# if nothing is out of bounds just return the value
if ... |
3215220 | import torch
import torch.nn as nn
import torch.nn.functional as F
class CS_Tripletnet(nn.Module):
def __init__(self, embeddingnet):
super(CS_Tripletnet, self).__init__()
self.embeddingnet = embeddingnet
def forward(self, x, y, z, c):
""" x: Anchor image,
y: Distant (negati... |
3215227 | class A(object):
def methodA(self):
return 's'
class B(object):
def getA(self):
return self.funcA()
def funcA(self):
return A()
|
3215246 | from unittest import mock
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.backends.base import SessionBase
from django.http import HttpRequest, HttpResponse
from utm_tracker.middleware import LeadSourceMiddleware, UtmSessionMiddleware
fr... |
3215270 | from .BoxBlur import BoxBlur, BoxBlur_random
from .DefocusBlur import DefocusBlur, DefocusBlur_random
from .GaussianBlur import GaussianBlur, GaussianBlur_random
from .LinearMotionBlur import LinearMotionBlur, LinearMotionBlur_random
from .PsfBlur import PsfBlur, PsfBlur_random
from .RandomizedBlur import Randomiz... |
3215326 | import dgl
import numpy as np
from pathlib import Path
import torch
from deepstochlog.term import Term, List
from deepstochlog.context import ContextualizedTerm, Context
from deepstochlog.dataset import ContextualizedTermDataset
root_path = Path(__file__).parent
dataset = dgl.data.CiteseerGraphDataset()
g = dataset... |
3215352 | import unittest
from utils.transliteration import transliterate
class TestTransliterate(unittest.TestCase):
def test_english_string(self):
original = 'The quick brown fox jumps over the lazy dog'
result = transliterate(original)
self.assertEqual(original, result)
def test_english_st... |
3215361 | from typing import Dict, Optional
from nonebot.typing import T_State
from nonebot.matcher import Matcher
from nonebot.adapters import Bot, Event
from nonebot.message import (IgnoredException, run_preprocessor,
run_postprocessor)
_running_matcher: Dict[str, int] = {}
@run_preprocessor
as... |
3215370 | import pytest
import pandas as pd
from pandas import Series, TimedeltaIndex
class TestTimedeltaIndexRendering:
@pytest.mark.parametrize("method", ["__repr__", "__str__"])
def test_representation(self, method):
idx1 = TimedeltaIndex([], freq="D")
idx2 = TimedeltaIndex(["1 days"], freq="D")
... |
3215374 | import json
from typing import Union
from flask import Blueprint, request
from parse import parse
from anubis.models import AssignmentTest, Submission, SubmissionTestResult, db
from anubis.utils.http import success_response
from anubis.utils.data import MYSQL_TEXT_MAX_LENGTH
from anubis.utils.http.decorators import j... |
3215395 | import pickle
import dask.bag as db
import pytest
from kartothek.io.dask.bag import store_bag_as_dataset
from kartothek.io.testing.write import * # noqa
def _store_dataframes(df_list, *args, **kwargs):
bag = store_bag_as_dataset(db.from_sequence(df_list), *args, **kwargs)
s = pickle.dumps(bag, pickle.HIGHE... |
3215405 | from grb.dataset import Dataset
if __name__ == '__main__':
# Load data
dataset_name = 'grb-cora'
dataset = Dataset(name=dataset_name,
data_dir="../data/",
mode='full',
feat_norm='arctan')
adj = dataset.adj
features = dataset.feature... |
3215430 | import asyncio
from typing import Dict
from pyzeebe import (
Job,
ZeebeWorker,
create_camunda_cloud_channel,
create_insecure_channel,
create_secure_channel,
)
from pyzeebe.errors import BusinessError
# Use decorators to add functionality before and after tasks. These will not fail the task
async ... |
3215470 | import json
from functools import partial
try:
from django.contrib.postgres.fields import JSONField as NativeJSONField
except ImportError: # pragma: no cover
# If using Django 1.8, don't worry about trying to be correct.
# We won't be using the native field.
NativeJSONField = object
from django.conf ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.