id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3399861 | import sys
import os
from sqlalchemy import func
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
from pynab.db import Release, db_session
def main():
with db_session() as db:
for date in db.query(func.DATE(Release.added), func.count(Release.id))\
.group_b... |
3399866 | import bisect
import itertools
import random
from array import array
import pytest
from pygm import SortedList, SortedSet
def test_len():
assert len(SortedSet([1, 2, 3])) == 3
assert len(SortedSet([3, 1, 4, 3])) == 3
assert len(SortedSet([1] * 10)) == 1
def test_init():
assert list(SortedSet()) == ... |
3399875 | import httplib2
import json
class QueryClient:
version = 'auto'
def __init__(self, scheme="http", host="192.168.99.100", port=8080):
self.scheme = scheme
self.host = host
self.port = port
def run_query(self, query):
h = httplib2.Http()
url = self.scheme + "://" + s... |
3399923 | from armulator.armv6.opcodes.abstract_opcodes.mul import Mul
from armulator.armv6.opcodes.opcode import Opcode
from armulator.armv6.configurations import arch_version
class MulT1(Mul, Opcode):
def __init__(self, instruction, setflags, m, d, n):
Opcode.__init__(self, instruction)
Mul.__init__(self,... |
3399930 | import unittest
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from rec.coding.sample_generator import NaiveSampleGenerator, PseudoSampleGenerator
class TestSampleGenerator(unittest.TestCase):
def test_naive_sampling(self):
t = tfp.distributions.Normal(loc=tf.constant(np... |
3399942 | import yaml
from openstack import connection
username = "xxxxxx"
password = "<PASSWORD>"
projectId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" # tenant ID
userDomainId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" # user account ID
auth_url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" # endpoint url
conn = connection.Connection(
auth_url=... |
3399952 | import networkx as nx
import EoN
import matplotlib.pyplot as plt
G = nx.grid_2d_graph(100,100) #each node is (u,v) where 0<=u,v<=99
#we'll initially infect those near the middle
initial_infections = [(u,v) for (u,v) in G if 45<u<55 and 45<v<55]
sim = EoN.fast_SIS(G, 1.0, 1.0, initial_infecteds = initial_infections,
... |
3399986 | import re
from app.package_registry import *
from app.package_version import *
from app.dependency import *
POD_URI = 'https://cocoapods.org/pods/{0}'
PODSPEC_URL_REGEX = re.compile(r'<a\s+href="([^"]+?)"\s*>\s*See Podspec\s*<\/a>', re.S)
class IosPackageRegistry(PackageRegistry):
def _fetch_version(self, nam... |
4800030 | from django.conf.urls import url
from guests.views import GuestListView, test_email, save_the_date_preview, save_the_date_random, export_guests, \
invitation, invitation_email_preview, invitation_email_test, rsvp_confirm, dashboard
urlpatterns = [
url(r'^guests/$', GuestListView.as_view(), name='guest-list'),... |
4800063 | from player_detection import *
import skvideo.io
TOPCUT = 320
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
class VideoHandler:
def __init__(self, pano, video, ball_detector, feet_detec... |
4800072 | from __future__ import unicode_literals
import json
import os
import django
from django.test import TestCase
from mock import patch
from job.test import utils as job_test_utils
from storage.configuration.json.workspace_config_v6 import WorkspaceConfigurationV6
from storage.test import utils as storage_test_utils
fro... |
4800077 | from django.conf.urls import url
from . import views
urlpatterns = [
# OAuth authentication
url(r'^login/$', views.login, name='fitbit-login'),
url(r'^complete/$', views.complete, name='fitbit-complete'),
url(r'^error/$', views.error, name='fitbit-error'),
url(r'^logout/$', views.logout, name='fi... |
4800130 | import click
from nbless.nbraze import nbraze
@click.command()
@click.argument("in_file", required=True, type=click.Path(exists=True))
@click.option("-e", "--extension", "extension", default="py")
def nbraze_cli(in_file: str, extension: str) -> None:
"""Create markdown and code files from a Jupyter notebook.
... |
4800141 | import json
import random
import pytest
from indy_common.authorize.auth_constraints import AuthConstraintForbidden
from indy_common.constants import RS_CONTEXT_TYPE_VALUE, JSON_LD_CONTEXT, RS_SCHEMA_TYPE_VALUE, \
RS_MAPPING_TYPE_VALUE, RS_ENCODING_TYPE_VALUE, RS_CRED_DEF_TYPE_VALUE, RICH_SCHEMA, RICH_SCHEMA_ENCOD... |
4800142 | import os
import random
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import LabelEncoder
from torch import nn, optim
from torch.utils.data import Data... |
4800166 | n = 5
for x in range(1, n + 1):
for y in range(1, n + 1):
if (x == y or x + y == n + 1):
print( "x ", end="")
else:
print( "o ", end="")
print( )
|
4800234 | from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Any
from pdm import Project
from pdm.models.candidates import Candidate
from pdm.models.environment import Environment
from pdm.utils import cached_property
from pip._... |
4800256 | from setuptools import setup
with open('README.rst', 'r') as f:
long_description = f.read()
setup(
name='django-pkgconf',
version='0.4.0',
description='Yet another application settings helper.',
long_description=long_description,
url='https://github.com/byashimov/django-pkgconf',
author='<... |
4800283 | from shapely import wkb
from util import json_encode
class QueryError (RuntimeError):
pass
def features_geojson(features, json_callback):
'''
'''
geojson = dict(type='FeatureCollection', features=features)
body, mime = json_encode(geojson), 'application/json'
if json_callback:
bod... |
4800305 | import pytest
from gitlabform.gitlab import AccessLevel
from tests.acceptance import (
run_gitlabform,
)
class TestMembers:
def test__add_user(self, gitlab, group_and_project, three_members, outsider_user):
members_before = gitlab.get_project_members(group_and_project)
assert len(members_befo... |
4800306 | import json
import urllib.parse
import ckeditor.fields
from django.conf import settings
def set_saved_fields_cookie(form, form_url, response):
"""
Set a cookie to indicate that rich text fields have been saved.
The ckeditor autosave plugin will attempt to automatically save
form fields that have bee... |
4800318 | from argparse import ArgumentParser
import os
import json
from src.core.util import read_json, write_pickle, read_pickle
from src.core.scenario_db import ScenarioDB, add_scenario_arguments
from src.core.schema import Schema
from src.model.preprocess import Preprocessor
from dataset_statistics import *
from src.core.lex... |
4800323 | from explorer import ExplorerPlotter
from plots import LinePlot
from data_log import read_csv_data
data = read_csv_data('rechargeable.csv', skip=2)
plot = LinePlot(data,'discharging')
plotter = ExplorerPlotter()
plot.plot(plotter)
|
4800327 | import FWCore.ParameterSet.Config as cms
# ------------------------------------------------------------------------------
# configure a filter to run only on the events selected by TkAlMinBias AlcaReco
import copy
from HLTrigger.HLTfilters.hltHighLevel_cfi import *
ALCARECOTkAlMinBiasFilterForSiPixelAli = copy.deepcop... |
4800377 | from backtester.features.feature import Feature
class PositionInstrumentFeature(Feature):
'''
Computing for Instrument. By default defers to computeForLookbackData
'''
@classmethod
def computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager):
instrumentsDi... |
4800380 | import sys
sys.path.append(".")
from ai.action.movement.movements.poweron import *
from ai.action.movement.movements.basic import *
def move_foot(mars):
rand_speed_one = get_rand_speed(0.4, 0.6)
mars.setLegAngle(1, 2, -40, rand_speed_one)
mars.setLegAngle(1, 3, 70, rand_speed_one)
get_rand_del... |
4800389 | from __future__ import unicode_literals
import unittest
from mopidy_ttsgpio import Extension
class ExtensionTest(unittest.TestCase):
def test_get_default_config(self):
ext = Extension()
config = ext.get_default_config()
# ext = frontend.TtsGpio(config, mock.sentinel.core)
self.a... |
4800412 | from functools import lru_cache
valid = {str(i) for i in range(1, 26 + 1)}
mod = 10 ** 9 + 7
@lru_cache(maxsize=512)
def mapDecoding(message):
"""
>>> mapDecoding("123")
3
"""
if len(message) == 0:
return 1
if len(message) == 1:
if message[0] not in valid:
return 0... |
4800422 | import subprocess
# az is short for "Available Zone"
# init az set
az_config = {
"mysql-node-1": "az1",
"mysql-node-2": "az2",
"mysql-node-3": "az3",
"etcd-node-0": "az1",
"etcd-node-1": "az1",
"etcd-node-2": "az2",
"etcd-node-3": "az3",
"etcd-node-4": "az3",
}
def ip_of(node):
s =... |
4800424 | expected_output = {
'vrfs': {
'default': {
'neighbors': {
'192.168.199.137': {
'priority': '1',
'state': 'FULL/DR',
'dead_time': '0:00:31',
'address': '172.31.80.37',
'interface': ... |
4800429 | import FWCore.ParameterSet.Config as cms
import SimTracker.SiPhase2Digitizer.phase2TrackerDigitizer_cfi
phase2TrackerDigitizerTPlike = SimTracker.SiPhase2Digitizer.phase2TrackerDigitizer_cfi.phase2TrackerDigitizer.clone()
phase2TrackerDigitizerTPlike.isOTreadoutAnalog = cms.bool(True)
|
4800441 | from django.utils import timezone as djangotime
from django.utils.translation import ugettext_lazy as _
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication, HTTP_HEADER_ENCODING
from accounts.models import APIKey
def get_authorization_header(request):
"""
Return... |
4800442 | from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from oneibl.one import ONE
import alf.io as ioalf
from brainbox.processing import bincount2D
class Bunch(dict):
"""A subclass of dictionary with an additional dot syntax."""
def __init__(self, *args, **kwargs):
super(Bunch, ... |
4800469 | try:
from socketio import AsyncClient
from socketio.exceptions import ConnectionError
except (ImportError, ModuleNotFoundError):
raise ImportError(
"To use telemetry you must install the `telemetry` option. (run `pip install -U dogehouse[telemetry]`)")
from json import dumps
socket = AsyncClient()... |
4800472 | from secrets import token_bytes
from cwt import COSE, COSEKey, Recipient, Signer
class TestCOSESample:
"""
Tests for samples on COSE Usage Examples.
"""
def test_cose_usage_examples_cose_mac0(self):
mac_key = COSEKey.from_symmetric_key(alg="HS256", kid="01")
ctx = COSE.new(alg_auto_... |
4800513 | from flask import (Response as ResponseBase,
redirect
)
from flask.json import dumps
from ..datastructures import NCObject
import typing as t
def JsonResponse(*wargs, **kwargs) -> ResponseBase:
"""
Returns the Jsonified object.
:for example::
from navycut.htt... |
4800581 | from .dolphin_api import DolphinAPI
from copy import deepcopy
class BaseEnv():
def __init__(self, frame_limit = 100000, pid = 0, options = {}):
self.api = DolphinAPI(**options)
self.frame_limit = frame_limit
self.pid = pid # player id
self.obs = None
self.prev_obs = None
... |
4800618 | import keras.backend as K
import numpy as np
import matplotlib.pylab as plt
import cPickle as pickle
import sys
import os
def find_top9_mean_act(data, Dec, target_layer, feat_map, batch_size=32):
"""
Find images with highest mean activation
args: data (numpy array) the image data
shape : (n_s... |
4800653 | import torch
from inplace_abn import active_group, set_active_group
from grasp_det_seg.utils.bbx import shift_boxes
from grasp_det_seg.utils.misc import Empty
from grasp_det_seg.utils.parallel import PackedSequence
from grasp_det_seg.utils.roi_sampling import roi_sampling
from .detection import DetectionAlgo
from .rpn... |
4800663 | from main.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'tests',
'TEST_NAME': 'tests_test',
'USER': 'postgres'
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
... |
4800679 | from builtins import object
import numpy as np
import sporco.cnvrep as cr
from sporco.admm import ccmod
from sporco.linalg import rrs
from sporco.fft import fftconv
class TestSet01(object):
def setup_method(self, method):
np.random.seed(12345)
N = 32
M = 4
Nd = 5
self.D... |
4800709 | import random
from plenum.common.exceptions import UnauthorizedClientRequest
from plenum.common.txn_util import get_seq_no
from plenum.common.util import randomString
from plenum.test.testing_utils import FakeSomething
def add_to_idr(idr, identifier, role):
random_s = randomString()
idr.set(identifier,
... |
4800724 | import time
import re
import traceback
import logging
import os
import subprocess
import threading
from typing import Optional
from pathlib import Path
def get_numeric_month_by_string(string: str, fallback_month: Optional[str] = '01') -> str:
"""
Get a numeric month representation given a month string represe... |
4800736 | from unittest import TestCase
from contentful_management.webhook_webhooks_call_proxy import WebhookResourceProxy
from .test_helper import CLIENT, PLAYGROUND_SPACE
class WebhookResourceProxyTest(TestCase):
def test_resource_proxy_must_be_implemented(self):
with self.assertRaises(Exception):
Web... |
4800752 | import torch
from . import matrix
from . import typedef as T
LOG2 = 0.6931471805599453
SQRT2PI = 2.5066282746310002
def tmul(a: T.Scalar, x: T.FloatTensor) -> T.FloatTensor:
"""
Elementwise multiplication of tensor x by scalar a.
Args:
x: A tensor.
a: scalar.
Returns:
tensor... |
4800757 | import sys
from personalised_tests import PersonalisedTestRunner as TestRunner
if __name__ == '__main__':
acc = 1.0
dataset_increment = 0
max_no_folds = 32
if len(sys.argv) > 1:
test_to_run = int(sys.argv[1])
else:
test_to_run = 0
tag = 'p5'
# For plots 0 and 1 ------... |
4800764 | import pulumi
from pulumi import ResourceOptions
from pulumi_azure.core import ResourceGroup
from pulumi_azure.containerservice import KubernetesCluster
from pulumi_azuread import Application, ServicePrincipal, ServicePrincipalPassword
# read and set config values
config = pulumi.Config()
PASSWORD = config.require_se... |
4800775 | class WrongParameterException(Exception):
"""
Exception which indicates an error caused by wrong parameters
Attributes:
message -- explanation of the exception
possible_solution -- Possible solution for solving the issue
module -- the module which raised that exception
"""
d... |
4800779 | class NotificationInterface(object):
def __init__(self, name):
self.name = name
def notify(self, title, message, alertClass):
raise NameError('Not Implemented')
|
4800799 | from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404, redirect, render
from utils.views import (
BulkDeleteView,
DeleteView,
DetailsView,
ModelListView,
PermissionRequiredMixin,
)
from .filters import JobResultFilterSet
from .forms import JobRes... |
4800821 | input = """
c num blocks = 1
c num vars = 50
c minblockids[0] = 1
c maxblockids[0] = 50
p cnf 50 150
-18 -39 4 0
-35 -12 -16 0
27 32 -13 0
42 35 -2 0
39 27 -50 0
13 -21 49 0
7 -44 12 0
37 36 26 0
13 -21 -40 0
-4 -21 41 0
-26 6 8 0
-48 -32 10 0
-11 40 9 0
-49 -10 -4 0
-14 -22 12 0
7 -48 -30 0
-21 31 22 0
-11 39 33 0
26 ... |
4800827 | from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup
import torch
import torch.nn.functional as F
import torch.nn as nn
PRE_TRAINED_MODEL_NAME = 'Rostlab/prot_bert_bfd_localization'
class ProteinClassifier(nn.Module):
def __init__(self, n_classes):
super(ProteinClassif... |
4800856 | import xarray as xr
import pandas as pd
import numpy as np
def to_deltas(dt):
"""
Convert from delta-ts to time steps
:param dt: range of delta ts
:return: range of time steps
"""
dts = [dt[0]]
for i in range(1, len(dt)):
dts.append(dts[i-1]+dt[i])
return np.array(dts)
def cr... |
4801044 | from typing import Iterable
from synapse_tools.config_plugins.base import HAProxyConfigPlugin
MAX_TARPIT_TIMEOUT = '60s'
TARPIT_HEADER = 'X-Ctx-Tarpit'
class FaultInjection(HAProxyConfigPlugin):
def global_options(self) -> Iterable[str]:
return []
def defaults_options(self) -> Iterable[str]:
... |
4801055 | import pkgutil
import subprocess
import sys
import examples
for junk, name, junk2 in pkgutil.iter_modules(examples.__path__, 'examples.'):
if name != 'examples.__main__':
if subprocess.call([sys.executable, '-m', name]) != 0:
break
|
4801064 | leaf_type_properties = {
'name': {
'description': 'Name of the leaf type.',
'type': 'string',
},
'description': {
'description': 'Description of the leaf type.',
'type': 'string',
'default': '',
},
'attribute_types': {
'description': 'Attribute type de... |
4801084 | import unittest
from pyapprox.monomial import *
from pyapprox.indexing import compute_hyperbolic_indices, \
argsort_indices_leixographically
class TestMonomial(unittest.TestCase):
def test_monomial_mean_uniform_variables(self):
num_vars = 2
indices = np.array([[0, 0], [1, 0], [0, 1], [1, 1], ... |
4801093 | import pathlib
import subprocess
import sys
from typing import Optional
from comeback import utils
def check_plugin(print: Optional[str] = None) -> utils.RUN_STATUS:
"""Test if we can use this plugin"""
if print is None:
return False, 'cwd parameter is not set.'
return True, None
def run_plugin... |
4801105 | import sys, linecache
syn_loc_file=sys.argv[1]
embeddings_file=sys.argv[2]
explode=False
if len(sys.argv) >= 4 and sys.argv[3]=="explode":
explode=True
def transform(line, explode):
if explode:
line=line.split("\t")
if len(line) == 1:
return line[0]
line[1]=" ".join(list(lin... |
4801117 | import re
from typing import Optional
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import HomeAssistantType
# https://github.com/Koenkk/zigbee-herdsman-converters/blob/master/devices.js#L390
# https://slsys.io/action/devicelists.html
# All lumi models:
# ... |
4801165 | from torch.utils.data import DataLoader, Dataset, Sampler
from pathlib import Path
from collections import defaultdict
import json
import random
from multiprocessing import Pool
import h5py
import pickle
import math
from tqdm import tqdm
import torch
import numpy as np
from torch.utils.data.distributed import Distribut... |
4801178 | import re
import argparse
from pickle import dump, load
from collections import Counter
from multiprocessing import Pool
from itertools import chain, islice
import tqdm
from pyquery import PyQuery as pq
from elasticsearch_dsl import Search
from django.core.management.base import BaseCommand
from django.conf import se... |
4801229 | import os
import re
import logging
from garfield.lib import file_utils
from .ZKNode import ZKNode
try:
from kazoo.client import KazooClient
from kazoo.exceptions import NoAuthError
except ImportError:
KazooClient = None
def run(args, helpers):
if KazooClient is None:
logging.warning("Skippin... |
4801267 | import json
import logging
import time
from calendar import timegm
import click
import pause
import pyfiglet
from pywinauto import Desktop, keyboard
from pywinauto.application import Application
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename='data_population_skype.log',... |
4801270 | import FWCore.ParameterSet.Config as cms
from SimGeneral.MixingModule.mix_CSA14_50ns_PoissonOOTPU_cfi import *
mix.maxBunch = 0
mix.minBunch = 0
|
4801413 | from typing import Optional, Sequence
from http_types import Request, Response
from openapi_typed_2.openapi import OAuth2SecurityScheme, OpenAPIObject
from .matcher import truncate_path
def generate_code():
return "xyz"
def gen_authflow_response(req: Request):
if "redirect_uri" not in req.query:
r... |
4801415 | import os
import numpy as np
import random
import torch
def is_DataParallelModel(model):
"""
:param model: nn.Module or torch.nn.DataParallel(model)
:return: True/False
"""
return hasattr(model, 'module')
def set_randomness(args):
if args.true_rand is False:
random.seed(ar... |
4801471 | from __future__ import annotations
from typing import TYPE_CHECKING
import logging
import time
from redis import BusyLoadingError
if TYPE_CHECKING:
from pajbot.managers.redis import RedisType
log = logging.getLogger(__name__)
def wait_for_redis_data_loaded(redis: RedisType) -> None:
while True:
t... |
4801502 | from accountpool.exceptions.init import InitException
from accountpool.storages.redis import RedisClient
from loguru import logger
class BaseGenerator(object):
def __init__(self, website=None):
"""
init base generator
:param website: name of website
"""
self.website = websi... |
4801506 | from __future__ import division
import tensorflow as tf
def ClipIfNotNone(grad, clipvalue):
return tf.clip_by_value(grad, -clipvalue, clipvalue)
def randomize(grad, clipvalue):
shape = grad.get_shape().as_list()
new_grad = tf.random_uniform(shape=shape, minval=-clipvalue, maxval=clipvalue)
return new_... |
4801543 | import logging
import os
import timeit
import torch
from torch.utils.data import DataLoader, SequentialSampler
from tqdm import tqdm
from transformers.data.metrics.squad_metrics import compute_predictions_logits, \
squad_evaluate
from transformers.data.processors.squad import SquadResult
from squad_fine_tuning.se... |
4801569 | import pandas as pd
import plotly.graph_objects as go
from eventful import DynamicPlot
import os
def import_data(data_path: str) -> pd.DataFrame:
df = pd.read_pickle(data_path)
df.sort_values(by="timestamp", inplace=True)
# df["timestamp"] = pd.to_numeric(df["timestamp"])
return df
def get_fig(df:... |
4801571 | from binascii import hexlify
from binascii import unhexlify
from logging import getLogger
from sqlite_dissect.constants import BLOB_SIGNATURE_IDENTIFIER
from sqlite_dissect.constants import LOGGER_NAME
from sqlite_dissect.constants import TEXT_SIGNATURE_IDENTIFIER
from sqlite_dissect.exception import CarvingError
from ... |
4801581 | from oligo import Iber
connection = Iber()
connection.login("USER", "PASSWORD")
print("ICP Status")
print(connection.icpstatus())
print("Watts")
watts = connection.watthourmeter()
print(watts)
|
4801607 | import threading
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class CrequestMiddleware(MiddlewareMixin):
"""
Provides storage for the "current" request object, so that code anywhere
in your project can access it, without it having to be pas... |
4801618 | import os
os.system("nosetests --with-coverage --cover-package pyecharts --cover-package")
os.system("flake8 --exclude build --max-line-length 89 --ignore=F401")
|
4801670 | from setuptools import setup, find_packages
version = "Unknown"
for line in open("metasv/_version.py"):
if line.startswith("__version__"):
version = line.strip().split("=")[1].strip().replace('"', '')
print version
setup(
name='MetaSV',
version=version,
description='MetaSV: An accurate and int... |
4801693 | from __future__ import with_statement
import struct
import logging
import util
import oscar
x01_name="Generic"
log = logging.getLogger('oscar.snac.x01')
version = 4
tlv_types = {0x05: 'server_addr',
0x06: 'cookie',
0x0d: 'service_id',}
subcodes = {}
ignorable = [
... |
4801704 | from polyphony import testbench
from polyphony.typing import Tuple, bit, int8
def typing05_a(xs:Tuple[bit, ...], i:int8) -> bit:
return xs[i]
def typing05_b(xs:Tuple[int, ...], i:int8) -> int:
return xs[i]
@testbench
def test():
data = (0, 1, 1) # type: Tuple[bit, ...]
for i in range(len(data)):
... |
4801729 | import tempfile
class Defaults:
"""
This contains some default parameters of the application
"""
FILES_PATH = tempfile.gettempdir() + '/.vaillant_vr900_files'
COOKIE_FILE_NAME = '.vr900-vaillant.cookies'
SERIAL_NUMBER_FILE_NAME = '.vr900-vaillant.serial'
SMART_PHONE_ID = 'vr900-connecto... |
4801734 | class TestThreadObject(object):
def test_name(self, space):
space.execute("Thread")
def test_current(self, space):
w_res = space.execute("return Thread.current.class.name")
assert space.str_w(w_res) == "Thread"
def test_thread_local_storage(self, space):
w_res = space.execu... |
4801759 | from typing import List, Sequence
import cytoolz as tz
import numpy as np
from multiprocess.pool import Pool
from tqdm import tqdm
from robustnessgym.core.constants import SLICEBUILDERS
from robustnessgym.core.slice import SliceDataPanel as DataPanel
from robustnessgym.slicebuilders.subpopulation import Subpopulation... |
4801801 | from django.utils.translation import ugettext as _
from rest_framework.views import APIView
class BaseUploadCompletionView(APIView):
'''
Abstract base class for the upload process. Provide some common attributes
and methods for Upload completion view for both brower and public api consumer.
Compatibi... |
4801836 | from distutils.version import StrictVersion as Version
import mathutils
from .base import BaseExporter
from .common import (
Buffer,
Reference,
SimpleID,
get_bone_name,
)
def togl(matrix):
return [i for col in matrix.col for i in col]
class SkinExporter(BaseExporter):
gltf_key = 'skins'
... |
4801854 | import math
import sys
import operator
import networkx as nx
#import matplotlib.pyplot as plt
import numpy as np
import scipy.spatial.distance
import scipy.signal
import skimage
import skimage.io
from skimage.segmentation import slic
from skimage.util import img_as_float
from scipy.optimize import minimize
import pdb
... |
4801877 | import json
import logging
import pkgutil
import click
import mock
from cloudify_agent.tests.shell.commands import run_agent_command
def test_debug_command_line():
@click.command()
def log():
pass
from cloudify_agent.shell.main import main
main.add_command(log, 'log')
run_agent_command... |
4801888 | import itertools
from Bio.Seq import Seq
from Bio.Data import CodonTable
import numpy as np
from .biotables import (
NUCLEOTIDE_TO_REGEXPR,
COMPLEMENTS,
IUPAC_NOTATION,
get_backtranslation_table,
)
def complement(dna_sequence):
"""Return the complement of the DNA sequence.
For instance ``co... |
4801913 | import unittest
from preprocessing.extractor import Extractor, Function
class TestExtractor(unittest.TestCase):
expected = {
"add_special" : Function('add_special','',None,['self', 'name'],['', ''],['', ''],'',[],None),
"__init__" : Function('__init__','',None,['self', 'x'],['', 'int'],['', ''... |
4801955 | import argparse
import datetime
import ray
from ray import tune
import os
import numpy as np
import copy
from marltoolbox.algos.alternating_offers.alt_offers_training import AltOffersTraining
from marltoolbox.utils import miscellaneous, log
from marltoolbox.experiments.tune_class_api.alternating_offers.cond_params imp... |
4801963 | import requests
class GigablastConfig:
def __init__(self, config):
self.host = config['host']
self.port = config['port']
class GigablastAPI:
class _HTTPStatus:
@staticmethod
def compare(status, expected_status):
return status[status.find('(')+1:status.find(')')] =... |
4801984 | from logger import logger
from xml.etree import ElementTree
from common_utils.path_utils import get_all_files_of_extension, get_rootname_from_path
class Source:
def __init__(self, database: str):
self.database = database
class Size:
def __init__(self, width: int, height: int, depth: int):
self... |
4802038 | import random
import argparse
import functools
import inspect
import sys
import time
import numpy as np
import torch
import torch.nn.functional as F
import nn
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('tests', nargs='*')
return parser.parse_args()
def randnint(n, a=8, b=... |
4802045 | import numpy as np
def calculate_matrix(Ptran, states, number_processes):
"""Extends a HMM, corresponding to a binary Markov Process,
(i.e. 0 or 1 open channels) to model up until K open channels
by assuming K independent binary Markov processes."""
# Fill in diagonals such that each row sums to 1
... |
4802052 | import unittest
from gensim import corpora
class TestGensim(unittest.TestCase):
def test_dictionary(self):
dic = corpora.Dictionary([['lorem', 'ipsum']])
self.assertEqual(2, len(dic.token2id))
|
4802076 | from . import BR_HISICAM_ROOT, BASE_WORKDIR, DEVICE_LIST, BrHisiCam, hiburn
import os
import argparse
import logging
def make_all(br_hisicam):
br_hisicam.make_all()
def show_params(br_hisicam):
print(br_hisicam.make_board_info())
def deploy(br_hisicam):
hiburn.boot(
device_id=br_hisicam.board,... |
4802089 | from django.conf.urls import url
from .views.auth import (
CustomLogoutView,
CustomTokenObtainPairView,
CustomTokenRefreshView,
)
urlpatterns = [
url(r"^jwt/create/?", CustomTokenObtainPairView.as_view(), name="jwt-create"),
url(r"^jwt/refresh/?", CustomTokenRefreshView.as_view(), name="jwt-refres... |
4802099 | from torch import nn
import torch.nn.functional as F
class Wrapper:
@staticmethod
def get_args(parser):
parser.add('--fm_weight', type=float, default=10.0)
@staticmethod
def get_net(args):
criterion = Criterion(args.fm_weight)
return criterion.to(args.device)
class Criterion(... |
4802116 | from os import environ
from loader import Loader
import actions
LOADER = Loader()
def lambda_handler(event, context):
try:
response = LOADER.personalize_cli.delete_campaign(
campaignArn=event['campaignArn']
)
except Exception as e:
LOADER.logger.error(f'Error deleting camp... |
4802125 | import os
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import json as json
from collections import defaultdict
from pyquaternion import Quaternion
from lyft_dataset_sdk.lyftdataset import LyftDataset
from loa.datum.datum_3d import make_datum_from_gt, make_datum_from_pred
from loa... |
4802135 | import os
import setuptools
import sys
# Load README to get long description.
with open('README.md') as f:
_LONG_DESCRIPTION = f.read()
setuptools.setup(
name='autoprompt',
version='0.0.1',
description='AutoPrompt',
long_description=_LONG_DESCRIPTION,
long_description_content_type='text/mark... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.