id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1798446 | from __future__ import division, print_function, absolute_import
import unittest
from tempfile import NamedTemporaryFile
import os
import numpy as np
import deepdish as dd
from contextlib import contextmanager
class TestCore(unittest.TestCase):
def test_multi_range(self):
x0 = [(0, 0), (0, 1), (0, 2), (1,... |
1798482 | def longestPalindrome(s):
n = len(s)
dp = [[False for _ in range(n)] for _ in range(n)]
for i in range(n):
dp[i][i] = True
max_length = 1
first = 99999999999
start = 0
for i in range(n-1):
if s[i] == s[i+1]:
dp[i][i+1] = True
start = i
... |
1798507 | import FWCore.ParameterSet.Config as cms
##################################################################
# AlCaReco for track based calibration using single muon events
##################################################################
from HLTrigger.HLTfilters.hltHighLevel_cfi import *
ALCARECOSiPixelCalSingleMuon... |
1798520 | from __future__ import absolute_import
from metaparticle_pkg.containerize import Containerize, PackageFile
__all__ = ['Containerize', 'PackageFile']
|
1798531 | import os
import json
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django_datajsonar.models import Field, Catalog, Metadata
from series_tiempo_ar_api.apps.dump.generator.metadata import MetadataCsvGenerator
from series_tiempo_ar_api.apps.dump.generator.sources impor... |
1798539 | from src.base import SourceLocation, Target
# main
SourceLocation(
name = 'nextpnr',
vcs = 'git',
location = 'https://github.com/YosysHQ/nextpnr',
revision = 'origin/master',
)
Target(
name = 'nextpnr-bba',
sources = [ 'nextpnr' ],
build_native = True,
gitrev = [ ('nextpnr', 'bba') ],
)
Target(
name = 'next... |
1798557 | import sys
import os
import time
import toolshed as ts
files = [
dict(file="ESP6500SI.all.snps_indels.tidy.v2.vcf.gz",
fields=["EA_AC", "AA_AC"],
names=["esp_ea", "esp_aa"],
ops=["first", "first"]),
dict(file="ExAC.r0.3.sites.vep.tidy.vcf.gz",
field... |
1798626 | from dss.index.es.backend import ElasticsearchIndexBackend
DEFAULT_BACKENDS = [ElasticsearchIndexBackend]
__all__ = ['DEFAULT_BACKENDS']
|
1798627 | import pytest
def test_print(api, b2b_config):
"""Demonstrate output of Snappi objects
"""
print(b2b_config.ports)
print(b2b_config.ports[0])
print(b2b_config.flows)
print(b2b_config.devices)
print(b2b_config)
if __name__ == '__main__':
pytest.main(['-vv', '-s', __file__])
|
1798640 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sys
import time
from sklearn.pipeline import make_pipeline
from skrebate import ReliefF
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score, train_test_split, LeaveOneOut, KFold, StratifiedK... |
1798665 | import shutil
import subprocess
if shutil.which('py'):
py = 'py'
else:
py = 'python'
def test_examples():
assert subprocess.getoutput(f'{py} examples/add.py') == '9'
assert subprocess.getoutput(f'{py} examples/cycle.py') == '4'
assert subprocess.getoutput(f'{py} examples/env.py') == '55'
asser... |
1798705 | from skimage.measure import compare_ssim
from skimage.measure import compare_psnr
from vifp import vifp_mscale
import cv2
import numpy as np
def SSIM(img1, img2):
return compare_ssim(img1, img2,multichannel=True)
def VIF(img1, img2):
return vifp_mscale(img1, img2)
if __name__ == '__main__':
img1 = cv2... |
1798727 | import ocnn
import torch
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter('logs/resnet')
octree = ocnn.octree_batch(ocnn.octree_samples(['octree_1', 'octree_2']))
model = ocnn.ResNet(depth=5, channel_in=3, nout=4, resblk_num=2)
print(model)
octree = octree.cuda()
model = model.cuda()
writer.ad... |
1798753 | import aisy_sca
from app import *
aisy = aisy_sca.Aisy()
aisy.set_resources_root_folder(resources_root_folder)
aisy.set_database_root_folder(databases_root_folder)
aisy.set_datasets_root_folder(datasets_root_folder)
aisy.set_database_name("database_ascad.sqlite")
aisy.set_dataset(datasets_dict["ascad-variable.h5"])
ai... |
1798791 | import os
if os.environ.get('PULSARPY', 'no') == 'yes':
HAS_C_EXTENSIONS = False
else:
HAS_C_EXTENSIONS = True
try:
import httptools # noqa
from .clib import (
EventHandler, ProtocolConsumer, Protocol, Producer, WsgiProtocol,
AbortEvent, RedisParser, WsgiResponse,... |
1798802 | import numpy as np
from scipy.stats import norm
import xlwings as xw
# https://en.wikipedia.org/wiki/Greeks_(finance)
@xw.func
def bsm(S, K, T = 1.0, r = 0.0, q = 0.0, sigma = 0.16, CP='call'):
d1 = (np.log(S / K) + (r - q + 0.5 * sigma ** 2) * T) / (sigma * np.sqrt(T))
d2 = (np.log(S / K) + (r - q - 0.5 * sig... |
1798814 | import os
import time
import json
import torch
import dill
import random
import pathlib
import evaluation
import numpy as np
import visualization as vis
from argument_parser import args
from model.online.online_trajectron import OnlineTrajectron
from model.model_registrar import ModelRegistrar
from environment import E... |
1798841 | import random
import pandas as pd
import io
import json
from dateutil import parser
from collections import OrderedDict
import time
import csv
import difflib
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import os
import sys, traceback
from matplotlib.legend_handler import HandlerLine2D
import gr... |
1798866 | import time
import github
from loguru import logger
from typing import List
class GithubWrapper:
def __init__(self, token, throttle_secs):
self.gh = github.Github(token)
self.cache = {}
self.throttle_secs = throttle_secs
self.get_repo_cache_miss_count = 0
self.get_repo_cach... |
1798886 | from .corruptions_aug import *
from .random_style_aug import StyleAugmentor
from .transfer_style_aug import StyleTransfer
from .cartoonize_aug import CartoonAugmentor
from .aprs import APRecombination
from .vqgan_aug import VQGAN |
1798923 | import os
from pylearn2ext.chbmit import CHBMIT
from pylearn2ext.epilepsiae import EpilepsiaeTest
def compute_n_samples_chbmit():
patients = [1, 3, 5, 8, 10, 20]
model_path = '../models'
data_path = '/Users/akara/Workspace/data/chbmit'
with open(os.path.join(model_path, 'sdae_chbmit_train_test_samples... |
1798939 | from neurogym.version import VERSION as __version__
from neurogym.core import BaseEnv
from neurogym.core import TrialEnv
from neurogym.core import TrialEnv
from neurogym.core import TrialWrapper
import neurogym.utils.spaces as spaces
from neurogym.envs.registration import make
from neurogym.envs.registration import reg... |
1798957 | def longestStringChain(strings):
stringChains = {}
for string in strings:
stringChains[string] = {"nextString": "", "maxChainLen": 1}
sortedString = sorted(strings, key=len)
for string in sortedString:
findLongestStringChain(string, stringChains)
return buildLongestStringChain(stri... |
1798968 | from typing import List, Tuple, Callable
from herpetologist import recursive_check
def validate_object_methods(object, methods, variable):
if object is not None:
if all([not hasattr(object, method) for method in methods]):
s = ' or '.join([f'`{method}`' for method in methods])
rais... |
1798974 | import queue
import time
import numpy as np
import voluptuous as vol
from ledfx.color import COLORS, GRADIENTS
from ledfx.effects.audio import AudioReactiveEffect
from ledfx.effects.gradient import GradientEffect
class Strobe(AudioReactiveEffect, GradientEffect):
NAME = "Real Strobe"
CONFIG_SCHEMA = vol.Sc... |
1799007 | import numpy as np
from scipy.optimize import linear_sum_assignment
from collections import defaultdict
from utils.utils import parse_camera_param
def global2pixel(person_coords, camera_id, camera_param_dict):
# det : X Y Z
world_coord = person_coords / camera_param_dict['discretization_factor'] + camera_param... |
1799020 | from . import api
import argparse
import os.path
import sys
parsing_errors = False
def is_valid_file(parser, arg):
"""Check if the file exists and return its path. Otherwise raise error."""
if not arg: return arg
if not os.path.exists(arg):
parser.error("The file %s does not exist!" % arg)
els... |
1799021 | import tensorflow as tf
import cv2
from configuration import test_video_dir, temp_frame_dir, CATEGORY_NUM, save_model_dir
from test_on_single_image import single_image_inference
from yolo.yolo_v3 import YOLOV3
def frame_detection(frame, model):
cv2.imwrite(filename=temp_frame_dir, img=frame)
frame = single_im... |
1799060 | import logging
import json
import sys
import csv
from inspect import isclass
from stdnet.utils import StringIO
from .globals import get_model_from_hash
__all__ = ['get_serializer',
'register_serializer',
'unregister_serializer',
'all_serializers',
'Serializer... |
1799114 | import tensorflow as tf
import numpy as np
class KeypointDetector:
def __init__(self, model_path, gpu_memory_fraction=0.25, visible_device_list='0'):
"""
Arguments:
model_path: a string, path to a pb file.
gpu_memory_fraction: a float number.
visible_device_list... |
1799148 | import platform
import time
from uuid import uuid4
from django.conf import settings
from django.db import models
from django.db.models import F
from django.db.models import QuerySet
from morango.models import UUIDField
from morango.models.core import SyncSession
from .utils import LANDING_PAGE_LEARN
from .utils impor... |
1799168 | from django.contrib import admin
from django.contrib.auth.models import Group
from rest_framework.authtoken.models import Token
from . import models as m
class TokenInline(admin.TabularInline):
model = Token
class UserAdmin(admin.ModelAdmin):
exclude = ["user_permissions"]
readonly_fields = ["password"]... |
1799174 | import pyomo.environ as pyo
from pyomo.opt import SolverStatus, TerminationCondition
from pyomo.core.expr.numvalue import RegisterNumericType
import numpy as np
import tqdm
from typing import List
from ..utils.storage import AnnParameters
from .modeling_interface import ModelingInterface
class PyomoModelingInterfac... |
1799178 | import pytest
pytestmark = [pytest.mark.django_db]
@pytest.fixture(autouse=True)
def url(mocker):
return mocker.patch('app.integrations.s3.AppS3.get_presigned_url', return_value='https://downloa.d/home.video.mp4')
def test_template_context(shipment):
ctx = shipment.get_template_context()
assert ctx['n... |
1799187 | import glob
import sys
import os
from setuptools import setup, find_packages, Extension
from cy_build import CyExtension as Extension, cy_build_ext as build_ext
import pysam
test_module_suffix = os.path.dirname(os.path.abspath(__file__)).split(os.sep)[-1]
test_module_name = "PysamTestModule_{}".format(test_module_su... |
1799226 | from fpl_reader.pseudo_object import PseudoObject
from fpl_reader.cool_io import CoolIO
from fpl_reader.windows_time import get_time_from_ticks
class Playlist:
def __init__(self, tracks):
self.tracks = tracks
def __repr__(self):
return (
'Playlist([\n'
+ ',\n\n'.join(r... |
1799229 | def application(environ, start_response):
import cgi
import json
import hashlib
# Set top folder to allow import of modules
import os, sys, inspect
top_folder = \
os.path.split(os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0])))[0]
if top_... |
1799253 | import numpy as np
from ray import tune
exp_args = {
'stop': {'is_finished': True},
'resume': False,
'verbose': True,
'checkpoint_freq': 0,
'checkpoint_at_end': False,
'num_samples': 1,
'resources_per_trial': {'cpu': 2, 'gpu': 1},
'config': {
'SynDataset.dataset_choice': tune.grid_search(
[... |
1799275 | from ocfweb.middleware import errors
def test_sanitize():
assert errors.sanitize(
"'a': True, 'encrypted_password': b'<PASSWORD>',",
) == "'a': True, 'encrypted_password': b'<REDACTED>',"
def test_sanitize_wsgi_context():
assert errors.sanitize_wsgi_context({
'CONTENT_LENGTH': 123,
... |
1799279 | import codecademylib
from matplotlib import pyplot as plt
drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"]
ounces_of_milk = [6, 9, 4, 0, 9, 0]
error = [0.6, 0.9, 0.4, 0, 0.9, 0]
# Plot the bar graph here
plt.bar(range(len(drinks)), ounces_of_milk, yerr=error, capsize=5)
plt.show() |
1799312 | import torch
from torch import nn
from pytorch_pfn_extras.nn import LazyBatchNorm1d, LazyBatchNorm2d, LazyBatchNorm3d # NOQA
from tests.pytorch_pfn_extras_tests.nn_tests.modules_tests.test_lazy import \
LazyTestBase
class TestLazyBatchNorm1d(LazyTestBase):
def get_original_module(self):
return nn.... |
1799359 | import pytest
from rpi_backlight import Backlight, _EMULATOR_SYSFS_TMP_FILE_PATH
from rpi_backlight.utils import FakeBacklightSysfs
def test_constructor() -> None:
with pytest.raises(TypeError):
Backlight(board_type="foo") # type: ignore[arg-type]
assert not _EMULATOR_SYSFS_TMP_FILE_PATH.exists()
... |
1799379 | from enum import Enum
import copy
from abc import ABC, abstractmethod
import numbers
from itertools import count
import numpy as np
import scipy
class Type(Enum):
Continuous = 'c'
Discrete = 'o'
class DuplicateHyperparameterError(Exception):
pass
class MissingHyperparameterError(Exception):
pass... |
1799390 | def process_input(file_contents):
lines_stripped = [int(line.strip()) for line in file_contents]
return lines_stripped
def main():
with open("input.txt",'r') as depths_file:
file_lines = depths_file.readlines()
depths = process_input(file_lines)
count = 0
for i in range(len(dept... |
1799391 | import pandas as pd
from datetime import datetime
import math
import pathlib
import sys
import os
# Read data downloaded from the crawler
def read_data(path):
try:
data = pd.read_excel(path, engine="odf")
return data
except Exception as excep:
sys.stderr.write(
"'Não foi p... |
1799486 | from game.nodes.actor import Actor
from game.nodes.base import Base
from game.nodes.bullet import (
BulletBoxShape,
BulletCapsuleShape,
BulletDebugNode,
BulletPlaneShape,
BulletRigidBodyNode,
BulletSphereShape,
BulletWorld,
)
from game.nodes.camera import Camera
from game.nodes.collision imp... |
1799496 | import datetime
def a():
test = 'Test'
return "{name} ({date:%B %d, %Y})".format( name=test, date=datetime.datetime.now() ) |
1799500 | import os
import numpy as np
from PIL import Image
PADDING = 16
MIN_CLIP = -1.75
MAX_CLIP = 3.75
img = Image.open('/tools/projects/LSTM-PYNQ/notebooks/Fraktur_images/010001.raw.lnrm.png').convert('L')
input_data = np.array(img.getdata())
input_data = input_data * 1.0 / np.amax(input_data)
input_data = np.amax(input_... |
1799529 | import random
import config
from nonebot import on_command, CommandSession,permission
__plugin_name__ = '随机传送'
__plugin_usage__ = r"""随机传送
例:#随机传送
或者 #rtp"""
import config
@on_command('rtp', aliases='随机传送', only_to_me=False, permission=permission.GROUP)
async def RandomTp(session: CommandSession):
# 查数据库
# ... |
1799548 | class UserService:
def __init__(self, client):
self.client = client
def getUser(self, id, headers=None, query_params=None, content_type="application/json"):
"""
Get a user by UUID. Get a user by UUID
It is method for GET /user/{id}
"""
uri = self.client.base_ur... |
1799561 | import json
import os
import re
import time
import xlrd
import xlwt
from flask import g, current_app, request
from sqlalchemy import desc, func, and_, or_
from apps.auth.models.users import User
from apps.project.business.requirement import RequirementBindCaseBusiness
from apps.project.models.cases import Case
from a... |
1799596 | import asyncio
from collections import OrderedDict
import concurrent
from contextlib import contextmanager
from functools import wraps
import functools
import itertools
import json
import logging
import math
from os import access
import os
from os.path import realpath, basename, dirname
from pathlib import Path
from th... |
1799599 | def binary_search(end, arr, val):
start = 0
while(start<=end):
mid = int((start+end)/2)
if arr[mid]>val:
ans = mid
end = mid-1
else:
start = mid+1
return ans
T = int(input())
for i in range(T):
N = int(input())
A = list(map(int, input().... |
1799625 | import autodisc as ad
import ipywidgets
class ExperimentRepetitionLoaderWidget(ipywidgets.Box):
@staticmethod
def get_default_gui_config():
default_config = ad.Config()
default_config.box_layout = ad.Config()
default_config.box_layout.display = 'stretch'
default_config.box_lay... |
1799632 | import numpy as np
from .kernel import Kernel
from scipy.linalg import block_diag
class Add(Kernel):
def __init__(self, first, second):
self.parts = list()
for k in (first, second):
if isinstance(k, Add):
self.parts.extend(k.parts)
else:
se... |
1799642 | import tomotopy as tp
model = tp.GDMRModel(degrees=[1])
print(model.alpha)
print(model.alpha_epsilon)
print(model.degrees)
print(model.eta)
print(model.f)
print(model.sigma)
print(model.sigma0)
|
1799655 | from monitors.views import MonitorDashboard, AddIndicator, DomainMonitor, DeleteIndicator
from profiles.models import Profile
from django.test import TestCase, RequestFactory
from django.core.urlresolvers import reverse
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseRedirect
im... |
1799663 | import sys
if sys.version_info < (2,7):
print('At least Python 2.7 is required')
exit()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('requirements.txt') as f:
required_packages = f.readlines()
from myssh import config
setup(name='myssh',
... |
1799671 | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = pat... |
1799770 | from django.urls import path, re_path
from .views import (
StaffMemberPaymentsView, OtherStaffMemberPaymentsView, FinancesByMonthView,
FinancesByDateView, FinancesByEventView, AllExpensesViewCSV, AllRevenuesViewCSV,
FinancialDetailView, ExpenseReportingView, RevenueReportingView,
CompensationRuleUpdate... |
1799839 | import copy
import mock
try:
import unittest2 as unittest
except ImportError:
import unittest
from testrail.helper import TestRailError
from testrail.section import Section
from testrail.suite import Suite
class TestSuite(unittest.TestCase):
def setUp(self):
self.mock_suite_data = [
{... |
1799871 | import argparse
import re
"""
DEPRECATED
Simple script to fix some default Java XML serialization issues.
This is normally useless, because the Java XML generation now includes its own corrected serialization
(via the same regex).
"""
if __name__ == "__main__":
parser = argparse.ArgumentParse... |
1799886 | import dash
from dash import html
import feffery_antd_components as fac
from dash.dependencies import Input, Output
from server import app
@app.callback(
Output('table-demo-output', 'children'),
[Input('table-demo', 'currentData'),
Input('table-demo', 'recentlyChangedRow'),
Input('table-demo', 'sor... |
1799932 | import demistomock as demisto # noqa
import ExpanseEnrichAttribution
CURRENT_IP = [
{"ip": "1.1.1.1", "attr1": "value1"},
{"ip": "8.8.8.8", "attr1": "value2"},
]
ENRICH_IP = [
{"ipaddress": "1.1.1.1", "provider": "Cloudflare", "ignored": "ignored-right"},
{"ipaddress": "8.8.8.4", "provider": "Googl... |
1799982 | from octopus.arch.wasm.cfg import WasmCFG
# Eos smart contract == wasm module
class EosCFG(WasmCFG):
def __init__(self, module_bytecode):
WasmCFG.__init__(self,
module_bytecode=module_bytecode)
def visualize_instrs_per_funcs(self, show=True, save=True,
... |
3200005 | from __future__ import annotations
import tempfile
from pathlib import Path
from typing import List, Set, Dict, Generator, Tuple
import pandas as pd
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
from pybedtools import BedTool
from genomics_data_index.storage.model import NUCLEOTIDE_UNKNOWN, NUCLEOTIDE_UN... |
3200018 | import torch.nn as nn
import numpy as np
FAIRFACE_AE_N_UPSAMPLING_EXTRA = {1: 1, 2: 1, 3: 2, 4: 2, 5: 3, 6: 5, 7: 5}
class ResnetBlock(nn.Module):
"""Define a Resnet block"""
def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):
"""Initialize the Resnet block
A r... |
3200073 | from pymongo import MongoClient
import glob
import os
if __name__ == '__main__':
client = MongoClient('localhost', 27017)
db = client['nlprokz']
glove = db.glove
count = 0
for root, dirs, files in os.walk('Glove/'):
for basename in files:
filename = os.path.join(root, basename)
... |
3200084 | from logging import getLogger
import requests_cache
from kivy.clock import Clock
from naturtag.app import alert, get_app
from naturtag.controllers import Controller
from naturtag.inat_metadata import get_http_cache_size
from naturtag.thumbnails import delete_thumbnails, get_thumbnail_cache_size
logger = getLogger(__... |
3200166 | from accelergy.utils import *
class SystemState():
def __init__(self):
self.cc_classes = {}
self.pc_classes = {}
self.arch_spec = None
self.hier_arch_spec = None
self.ccs = {}
self.pcs = {}
self.action_counts = None
self.plug_ins = []
self.ERT ... |
3200178 | from charcoaltoken import CharcoalToken as CT
from unicodegrammars import UnicodeGrammars
def PassThrough(r):
return r
def GetFreeVariable(s, n=1):
r = ""
for _ in range(n):
r += next(filter(lambda c: c not in s + r, "ικλμνξπρςστυφχψωαβγδεζηθ"))
return r
def VerbosifyVariable(c):
return ... |
3200184 | import hashlib
import hmac
from secrets import token_bytes
from typing import Any, Union
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.ec import (
EllipticCurvePrivateKey,
EllipticCurvePublicKey,
)
from ... |
3200203 | import os.path
import pytest
CD = os.path.dirname(__file__)
@pytest.fixture
def __EH_prolog3_pat():
with open(os.path.join(CD, "data", "__EH_prolog3.pat"), "rb") as f:
return f.read().decode("utf-8")
@pytest.fixture
def __EH_prolog3_sig():
# sigmake ./data/__EH_prolog3.pat ./data/__EH_prolog3.sig
... |
3200236 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
VERSION = '0.1'
URL_PREFIX_VERSION = '/api'
GEO_FILE = 'logtoes/geocity/GeoLiteCity.dat'
HOST = 'localhost'
PORT = 5555
DEBUG = True
BRANCH = 'master'
TRAP_HTTP_EXCEPTIONS = True
TRAP_BAD_REQUEST_ERRORS = True
JSONIFY_PRETTYPRINT_REGULAR = True
ERROR_4... |
3200285 | import uuid
import pytest
from botx import ChatTypes
from botx.clients.methods.v3.chats.create import Create
from botx.concurrency import callable_to_coroutine
pytestmark = pytest.mark.asyncio
async def test_chat_creation(client, requests_client):
method = Create(
host="example.com",
name="<NAM... |
3200306 | from harborclient import base
class JobManager(base.Manager):
def list(self, policy_id=None):
"""List filters jobs according to the policy and repository."""
return self._list("/jobs/replication?policy_id=%s" % policy_id)
def get_log(self, job_id):
"""Get job logs."""
return s... |
3200327 | import sys
import unittest
from src import (
WalletQueryService,
)
from tests.utils import (
build_dependency_injector,
)
class TestWalletQueryService(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.injector = build_dependency_injector()
async def asyncSetUp(self) -> None:
... |
3200400 | from mock import patch
from django.test import TestCase
from ..serializer import CollaboratorSerializer
class CollaboratorSerializerTests(TestCase):
"""Test RepoSerializer methods"""
def setUp(self):
self.username = "delete_me_username"
self.repo_base = "delete_me_repo_base"
self.pa... |
3200436 | import envi.archs.msp430.emu as e_msp430e
import vivisect.impemu.emulator as v_i_emulator
class Msp430WorkspaceEmulator(v_i_emulator.WorkspaceEmulator, e_msp430e.Msp430Emulator):
taintregs = [ x for x in range(2, 16) ]
def __init__(self, vw, **kwargs):
'''
Please see the base emulator class i... |
3200441 | import logging
from tqdm import tqdm
import os
import jieba
from collections import Counter
import numpy as np
from algo.model.model_config import BertBilstmCrfConfig
from algo.model.msra_preprocessing import msra_preprocessing
from algo.models import ClassifyTag
from algo.model.model_config import FastTextConfig
def... |
3200467 | import traceback
import Defines as CONST
class GestureToHangoutControl():
def __init__(self):
pass
def update(self, in_gesture):
if in_gesture == CONST.GESTURE_TWO_FINGERS_PINCH_OPEN:
out_answer = True
out_decline = False
return (out_answer, out_d... |
3200473 | from typing import Set
from keycloak_scanner.logging.vuln_flag import VulnFlag
from keycloak_scanner.scan_base.scanner import Scanner
from keycloak_scanner.scan_base.types import FormPostXSS, WellKnown, Client, Realm
from keycloak_scanner.scan_base.wrap import WrapperTypes
class FormPostXssScanner(Scanner[FormPostXS... |
3200480 | from typing import Text
import hypothesis.strategies._internal.core as st
from hypothesis.strategies._internal.strategies import SearchStrategy
@st.defines_strategy(force_reusable_values=True)
def mac_addr_strings():
# type: () -> SearchStrategy[Text]
"""A strategy for MAC address strings.
This consists... |
3200545 | import sys
import gzip
all_event_count = 0
min_overlap_removed = 0
filtered = open("no_min_overlap80_disc.vcf", 'w')
with gzip.GzipFile(sys.argv[1], 'r') as fh:
for line in fh:
if line.startswith("#"):
filtered.write(line)
sys.stdout.write(line)
continue
data = ... |
3200548 | from setuptools import setup
setup(
name="electrum-ltc-server",
version="1.0",
scripts=['run_electrum_ltc_server.py','electrum-ltc-server'],
install_requires=['plyvel','jsonrpclib', 'irc >= 11, <=14.0'],
package_dir={
'electrumltcserver':'src'
},
py_modules=[
'electrumlt... |
3200550 | expected_output = {
'vrf':
{'vpn1':
{'no_g_routes': 5,
'no_sg_routes': 44
}
}
}
|
3200560 | from nerblackbox.modules.ner_training.data_preprocessing.tools.bert_dataset import (
BertDataset,
)
from nerblackbox.modules.ner_training.data_preprocessing.tools.csv_reader import (
CsvReader,
)
from nerblackbox.modules.ner_training.data_preprocessing.tools.input_example import (
InputExample,
)
from nerbl... |
3200581 | from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.text import Truncator
# Create your models here.
class Board(models.Model):
"""
Class for message boards.
"""
name = models.CharField(max_length=30, unique=True)
description... |
3200601 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from camera import Camera
from control_panel import ControlPanel
import time
import kivy
from kivy.config import Config
Config.set('graphics', 'width', '1920')
Config.set('graphics', 'height', '1080')
#Config.... |
3200626 | from django.conf.urls import url
from . import views
urlpatterns = (
url('^$', views.landing,
name='landing'),
url('^about$', views.about,
name='about'),
url('^faq$', views.faq,
name='faq'),
url('^contact$', views.contact,
name='contact'),
url('^terms-and-conditio... |
3200633 | import doctest
from nose.tools import assert_equal
from corehq.apps.app_manager import id_strings
def test_doctests():
results = doctest.testmod(id_strings)
assert_equal(results.failed, 0)
|
3200651 | import numpy as np
from .alg_config import RRT_EPS
import torch
class SearchTree:
def __init__(self, env, root, model=None, dim=2):
self.states = np.array([root])
self.parents = [None]
self.rewired_parents = [None]
self.expanded_by_rrt = [None]
self.freesp = [True]
... |
3200666 | import matplotlib.pyplot as plt
import math
import candelier.candelier_parameters as ch_pp
import candelier as ch
import DEM_explicit_solver_var as DEM_parameters
def Radius(a):
a_2 = [x ** 2 for x in a]
return math.sqrt(sum(a_2))
sim = ch.AnalyticSimulator(ch_pp)
coors = [None] * 3
sim.CalculatePosition(coo... |
3200693 | from boa3.builtin import public
from boa3_test.test_sc.import_test.FromImportUserModuleRecursiveImport import from_import_empty_list
@public
def empty_list() -> list:
return from_import_empty_list()
|
3200733 | import logging
import unittest
from dotsecrets.smudge import SmudgeFilter
class TestSmudgeFilter(unittest.TestCase):
def setUp(self):
logging.basicConfig()
self.secrets = {
'password': {
'secret': 's3cr3t'
},
'question': {
'secr... |
3200735 | from django.core.management.base import BaseCommand
from django.utils import timezone
from player.models import Player
from player.tenhou.models import TenhouNickname
from utils.tenhou.helper import (
download_all_games_from_nodochi,
recalculate_tenhou_statistics_for_four_players,
save_played_games,
)
de... |
3200784 | import hashlib
import base64
from glados.models import TinyURL
from elasticsearch_dsl import Search
from django.http import JsonResponse
from datetime import datetime, timedelta, timezone
from glados.usage_statistics import glados_server_statistics
from glados.models import ESTinyURLUsageRecord
from glados.es_connectio... |
3200793 | from typing import Tuple
import vapoursynth as vs
def _get_bits(clip: vs.VideoNode, expected_depth: int = 16) -> Tuple[int, vs.VideoNode]:
"""Checks bitdepth, set bitdepth if necessary, and sends original clip's bitdepth back with the clip"""
from vsutil import depth, get_depth
bits = get_depth(clip)
... |
3200802 | class MetricBase():
def __init__(self, args, **kwargs):
self._metrics = {"lang": []}
self._internalstore = {}
def parse_tokens(self, language, tokens):
if language not in self._metrics["lang"]:
self._metrics["lang"].append(language)
def get_results(self):
return... |
3200847 | from dataclasses import dataclass
from typing import Any, Optional
from ..utils import parse_json
@dataclass
class Link:
url: Optional[str] # Optional[AnyUrl]
label: str
active: bool
def __post_init__(self):
self.url = str(self.url) if self.url is not None else None
self.label = str... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.