id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
460317 | from logging import getLogger
def build_models_dict(annotated_models):
"""
Take a list with annotated genetic inheritance patterns for each
family and returns a dictionary with family_id as key and a list of
genetic models as value.
Args:
annotated_models : A list on the form ['1:AD... |
460355 | import network
import numpy as np
import tensorflow as tf
import model3 as M
import data_reader
def grad_loss(x, model):
data, label = x
with tf.GradientTape() as tape:
out = model(data)
loss = tf.reduce_mean(tf.square(out - label))
print(tf.reduce_max(out), tf.reduce_min(out))
grads = tape.gradient(loss,... |
460368 | import torch
from torch.utils import data
from Datasets.dataset_semantic_SHAB import Dataset as full_supervise_Dataset
from Models.model import Model
import os
import argparse
import matplotlib.pyplot as plt
import torch.nn.functional as F
import numpy as np
checkpoint_logs_name = 'SHA'
parser = argparse.ArgumentParse... |
460384 | from django.test import TestCase
from constance import settings
from tests.storage import StorageTestsMixin
class TestMemory(StorageTestsMixin, TestCase):
def setUp(self):
self.old_backend = settings.BACKEND
settings.BACKEND = 'constance.backends.memory.MemoryBackend'
super().setUp()
... |
460405 | from pydantic import conint, constr
hexstr = constr(regex=r'^[0-9a-f]+$', strict=True)
hexstr_i = constr(regex=r'^[0-9a-fA-F]+$', strict=True) # case-insensitive hexstr
non_negative_intstr = constr(regex=r'^(?:0|[1-9][0-9]*)$', strict=True)
non_negative_int = conint(ge=0, strict=True)
positive_int = conint(gt=0, str... |
460406 | import logging
from matplotlib.colors import LinearSegmentedColormap
from typing import Sequence, Callable
import matplotlib.figure
from matplotlib import pyplot as plt
import numpy as np
log = logging.getLogger(__name__)
def plotMatrix(matrix, title, xticklabels: Sequence[str], yticklabels: Sequence[str], xlabel:... |
460419 | from itertools import islice, count
from tqdm import tqdm
def _k_mers(sequence, k):
it = iter(sequence)
result = tuple(islice(it, k))
if len(result) == k:
yield "".join(result)
for elem in it:
result = result[1:] + (elem,)
yield "".join(result)
def transform(sequence, method... |
460445 | import requests
import json
dataSet = []
url = 'http://universities.hipolabs.com/search?name='
def readUrl(search):
results = requests.get(url+search)
print("Status Code: ", results.status_code)
print("Headers: Content-Type: ", results.headers['Content-Type'])
# print("Headers: ", results.headers)
... |
460453 | import logging
import ply.yacc as yacc
from functools import partial
from rita.lexer import RitaLexer
from rita import macros
logger = logging.getLogger(__name__)
def stub(*args, **kwargs):
return None
def either(a, b):
yield a
yield b
def load_macro(name, config):
try:
return partial(... |
460470 | from pathlib import Path
from whispers.utils import string_is_function, string_is_quoted, strip_string
class Javascript:
def pairs(self, filepath: Path):
for line in filepath.open("r").readlines():
if line.count("=") == 1:
yield from self.parse_assignment(line)
def parse_... |
460480 | import datetime
from bitmovin import Bitmovin, Encoding, S3Input, S3Output, H264CodecConfiguration, \
AACCodecConfiguration, H264Profile, StreamInput, SelectionMode, Stream, EncodingOutput, ACLEntry, ACLPermission, \
MP4Muxing, MuxingStream, CloudRegion, SmoothManifest, MP4Representation, PlayReadyDRM, PlayRead... |
460483 | import os
import shutil
from time import time
from datetime import datetime
class Utils(object):
''' Static Helpers.'''
@staticmethod
def rm_tree(path):
'''Removes all the files.'''
if os.path.isdir(path):
if os.name == 'nt':
#Hack for Windows. Shutil can't remo... |
460493 | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('dabangcrawler.urls', namespace='dabangcrawler')),
] + static(settings.STATIC_URL,... |
460515 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging
import emission.core.get_database as edb
import emission.core... |
460540 | from HelperfunctionsNew import *
import sys
import os
if __name__ == "__main__":
blockDesc = sys.argv[1]
helper = Helper()
herlper.get
if blockDesc in ["Skit Name", "Synopsis", "Minigame"]:
helper.createBlock_Multi(blockDesc)
elif blockDesc != "All":
... |
460559 | import pytest
@pytest.fixture(scope='session')
def django_db_setup():
from django.conf import settings
settings.DATABASES['default'] = {
"ENGINE": 'django.db.backends.postgresql',
"NAME": 'escalate',
"USER": 'escalate',
"PASSWORD": '<PASSWORD>',
"HOST": 'localhost',
... |
460570 | from dexy.filter import DexyFilter
from dexy.utils import parse_yaml
import re
class YamlargsFilter(DexyFilter):
"""
Specify attributes in YAML at top of file.
"""
aliases = ['yamlargs']
def process_text(self, input_text):
regex = "\r?\n---\r?\n"
if re.search(regex, input_text):
... |
460576 | from ..value_set import ValueSet
class AcuteInpatient(ValueSet):
"""
**Clinical Focus:** This value set contains concepts related to acute inpatient visits.
**Data Element Scope:** This value set may use Quality Data Model (QDM) datatype related to Encounter, Performed.
**Inclusion Criteria:** Inclu... |
460605 | from __future__ import division
from galpy.potential import SpiralArmsPotential as spiral
import numpy as np
from numpy import pi
from numpy.testing import assert_allclose
from scipy.misc import derivative as deriv
import unittest
class TestSpiralArmsPotential(unittest.TestCase):
def test_constructor(self):
... |
460618 | import asyncio
import concurrent.futures
import logging
import multiprocessing
import time
from enum import Enum, auto
import cv2
from .aruco_marker import ArucoMarker
MAX_READ_FAILURES_PER_INIT = 3
LOOPBACK_DEV_PATH = "/dev/video21"
class CapComm(Enum):
"""For communication between ArucoDetectionProcess and A... |
460635 | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import json
filter_arg = json.loads(demisto.args().get("filter", json.dumps({"tags": ["report"]})))
raw_entries = None
if filter_arg:
raw_entries = demisto.executeCommand('getEntries', {"id": demisto.incident().get("id"), ... |
460658 | import matplotlib.pyplot as plt
import numpy as np
from . import common
def plot(soln):
soln = common.numpyify(soln)
fig, axes = plt.subplots(2, 3)
fig.set_size_inches(12, 8)
ax = axes[0, 0]
ax.errorbar(
np.arange(soln.μd.shape[0]),
soln.μd[:, 0], yerr=soln.σd[0, :], marker='.', ... |
460660 | import jumpscale.packages.vdc_dashboard.bottle.api.root
import jumpscale.packages.vdc_dashboard.bottle.api.backup
import jumpscale.packages.vdc_dashboard.bottle.api.deployments
import jumpscale.packages.vdc_dashboard.bottle.api.export
## now that we have loaded all of the submodules and registered more endpoints
## on... |
460670 | from __future__ import print_function
import os
import sys
import random
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
class ListDataset(data.Dataset):
'''Load image/labels/boxes from a list file.
The list file is like:
a.jpg xmin ymin... |
460715 | import unittest
import logging
from mock import Mock
from rollingpin.utils import swallow_exceptions
class TestUtils(unittest.TestCase):
def test_swallow_exception_on_error(self):
logger = Mock()
exception = Exception("fail")
with swallow_exceptions("tester", logger):
raise ... |
460757 | import os
ALLOWED_HOSTS = ['*']
BASE_DIR = os.path.dirname(__file__)
SECRET_KEY = "007"
INSTALLED_APPS = [
# Default Django apps
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles... |
460772 | from datetime import datetime
def today():
time = datetime.now()
return time.strftime("%Y%m%d")
def timestamp():
time = datetime.now()
return time.strftime("%Y%m%d%H%M%S%f")
|
460830 | from django.utils.translation import ugettext_lazy as _
from rest_framework.exceptions import ValidationError
from dynamicforms import serializers
from dynamicforms.action import Actions, TableAction, TablePosition
from dynamicforms.viewsets import ModelViewSet
from ..models import Validated
class ValidatedSerialize... |
460833 | import datetime
import json
import os
import re
import subprocess
from shutil import copyfile
import yaml
from buildtest.config import SiteConfiguration
from buildtest.defaults import console
from buildtest.exceptions import BuildTestError, ConfigurationError
from buildtest.schemas.defaults import custom_validator, sc... |
460843 | from django.conf import settings
import os
def get_project_root():
""" get the project root directory """
settings_mod = __import__(settings.SETTINGS_MODULE, {}, {}, [''])
return os.path.dirname(os.path.abspath(settings_mod.__file__))
|
460850 | import cirq
from cirq.contrib.quantum_volume import QuantumVolumeResult
from cirq.testing import assert_json_roundtrip_works
from cirq.contrib.json import DEFAULT_CONTRIB_RESOLVERS
from cirq.contrib.acquaintance import SwapPermutationGate
def test_quantum_volume():
qubits = cirq.LineQubit.range(5)
qvr = Quant... |
460855 | from django.contrib.auth.models import User
from django.template.loaders.app_directories import Loader
class LoaderWithSQL(Loader):
def get_template(self, *args, **kwargs):
# Force the template loader to run some SQL. Simulates a CMS.
User.objects.all().count()
return super().get_template(... |
460875 | from plotly.offline import iplot, _plot_html
from IPython.display import HTML, display
import ipywidgets as widgets
def my_iplot(figure_or_data, show_link=False, link_text='Export to plot.ly',
validate=True, image=None, filename='plot_image', image_width=800,
image_height=600) :
plot_html, plotdivid, width, h... |
460888 | import FWCore.ParameterSet.Config as cms
DTEffAnalyzer = cms.EDAnalyzer("DTEffAnalyzer",
recHits2DLabel = cms.string('dt2DSegments'),
minHitsSegment = cms.int32(5),
minCloseDist = cms.double(20.0),
recHits4DLabel = cms.string('dt4DSegments'),
rootFileName = cms.untracked.string('DTEffAnalyzer.root'... |
460943 | import os
import datetime
class Config:
myemail = os.getenv('MY_EMAIL', '')
user_home_dir = os.path.expanduser('~')
# ml code location
ml_dir = os.path.abspath('.rejected_article_tracker/src/ML')
# data_locations
main_data_dir = os.path.join(user_home_dir,'rejected_article_tracker'... |
460998 | from conans import ConanFile, CMake, tools
import os
required_conan_version = ">=1.33.0"
class TidyHtml5Conan(ConanFile):
name = "tidy-html5"
license = "W3C"
url = "https://github.com/conan-io/conan-center-index"
homepage = "http://www.html-tidy.org"
description = "The granddaddy of HTML tools, w... |
461026 | from cx_const import DefaultActionsMapping, Light
from cx_core import LightController
from cx_core.integration import EventData
class SNZB01LightController(LightController):
def get_z2m_actions_mapping(self) -> DefaultActionsMapping:
return {
"single": Light.TOGGLE, # single click
... |
461033 | from flask_restly.decorator import resource, get
from flask_restly import FlaskRestly
from flask import Flask
def test_should_register_resource():
app = Flask(__name__)
FlaskRestly(app)
@resource(name='test')
class SomeResource:
@get('/')
def get(self):
return dict()
... |
461041 | import pytest
import pandas as pd
from ..importing import attempt_import
def test_import_module():
pandas = attempt_import('pandas', "Pandas package is not installed")
assert pandas is pd
with pytest.raises(RuntimeError) as err:
attempt_import('a_module_which_should_not_exist',
... |
461080 | from __future__ import unicode_literals
from ..elements.elementbase import Attribute
from ..tags.context import ContextElementBase
from .. import namespaces
from .. import logic
class Check(ContextElementBase):
"""A pre-flight check"""
xmlns = namespaces.preflight
class Help:
synopsis = "define... |
461126 | import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import torchvision.transforms as transforms
import cv2
import torch
from torch.utils import data
from torch.nn import functional as F
from torch.autograd import Function
import random
import math
def visualize(img_arr):
plt.imshow(((img_a... |
461140 | import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim
import torch.nn.functional as F
import torch.optim.lr_scheduler as lr_scheduler
import time
import os
import glob
from itertools import combinations
import configs
import backbone
from data.datamgr import Simpl... |
461161 | import os
import shapely
from affine import Affine
import rasterio
from rasterio.warp import transform_bounds
from ..utils.geo import list_to_affine, _reduce_geom_precision
from ..utils.core import _check_gdf_load
from ..raster_image.image import get_geo_transform
from shapely.geometry import box, Polygon
import pandas... |
461166 | import sys
import os
sys.path.append("/tensorflow/models/research")
from object_detection.utils import config_util
from config_file_module.ssd_resnet_50_fpn import config_ssd_resnet_fpn
from config_file_module.ssd_mobilenet_inception import config_ssd_mobilenet_inception
from config_file_module.frcnn_resnet_50_101 imp... |
461199 | from app.server import server
from app.notifications.webapn import supports_web_apn, create_pushpackage_zip
from app.controllers import webapn
from app.helpers.render import render_json
from app.models.APNDevice import APNDevice, APNProvider
from app.session.csrf import csrf_protected
from app.models.User import User
f... |
461219 | import numpy as np
def create_obstacles(sim_time, num_timesteps):
# Obstacle 1
v = -2
p0 = np.array([5, 12])
obst = create_robot(p0, v, np.pi/2, sim_time,
num_timesteps).reshape(4, num_timesteps, 1)
obstacles = obst
# Obstacle 2
v = 2
p0 = np.array([0, 5])
ob... |
461252 | from bson import ObjectId
from django.db.models import Model
from django.db.models.base import ModelState
from mongoengine import document as me
from mongoengine.base import metaclasses as mtc
from mongoengine.errors import FieldDoesNotExist
from .forms.document_options import DocumentMetaWrapper
from .queryset import... |
461272 | import datetime
import glob
import json
import os
import pathlib
import re
from typing import Any, Dict, List, Optional
from appdirs import AppDirs # type: ignore
import requests
import requests_cache # type: ignore
from tarsafe import TarSafe # type: ignore
from ochrona.log import OchronaLogger
# Cache settings
... |
461331 | from vocabulary import Vocab
import csv
tmp_Vocab = Vocab()
tmp_Vocab.count_file("../data/test/train.txt", add_eos=False)
tmp_Vocab.build_vocab()
with open('../data/test/label.tsv', 'wt') as f:
tsv_writer = csv.writer(f, delimiter='\t')
tsv_writer.writerow(['label', 'index'])
for i in range(len(tmp_Vocab.... |
461344 | import pytest
from testutils import get_co, get_bytecode
from equip import BytecodeObject, BlockVisitor
from equip.bytecode import MethodDeclaration, TypeDeclaration, ModuleDeclaration
from equip.bytecode.utils import show_bytecode
import equip.utils.log as logutils
from equip.utils.log import logger
logutils.enableL... |
461358 | from ._version import get_versions
__version__ = get_versions()["version"]
del get_versions
__author__ = "<NAME>, <NAME>"
__author_email__ = "<EMAIL>"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2019-2020, %s." % __author__
__homepage__ = "https://github.com/PhoenixDL/rising"
# this has to be simple string, se... |
461360 | from fac.commands import Command, Arg
from fac.utils import prompt
class RemoveCommand(Command):
"""Remove mods."""
name = 'remove'
arguments = [
Arg('mods', help="mod patterns to remove ('*' for all)", nargs='+'),
Arg('-y', '--yes', action='store_true',
help="automatic yes t... |
461370 | from create_dataset import create_MIMIC_dataset, create_eICU_dataset
from dataframe_gen import preprocess
from numpy_convert import convert2numpy
from preprocess_utils import label_npy_file
import os
import argparse
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--data_input_path', ... |
461389 | import pytest
from rest_framework import status
from rgd_imagery import models
@pytest.mark.django_db(transaction=True)
def test_download_image_file(admin_api_client, astro_image):
pk = astro_image.pk
response = admin_api_client.get(f'/api/rgd_imagery/{pk}/data')
assert status.is_redirect(response.status_... |
461408 | from .models import Organization
from .models import Administrator
from .models import Recipient
from .models import Task
from .models import Address
from .models import Destination
from .models import Vehicle
from .models import Worker
from .onfleet import Onfleet
from .exceptions import OnfleetDuplicateKeyException
... |
461418 | import configparser
def read_config(config_text, schema=None):
"""Read options from ``config_text`` applying given ``schema``"""
schema = schema or {}
cfg = configparser.ConfigParser(
interpolation=configparser.ExtendedInterpolation()
)
try:
cfg.read_string(config_text)
except... |
461449 | import pytest
from mktestdocs import check_codeblock, grab_code_blocks
exibit_a = """
This is an example docstring.
Arguments:
a: a parameter
There is no example
"""
exibit_b = """
This is an example docstring.
Arguments:
a: a parameter
```python
assert 1 == 1
```
"""
exibit_c = """
This is an e... |
461466 | from bs4 import BeautifulSoup
from sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS
import re
import warnings
from nltk import stem
link_re = re.compile(r'\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*')
letter_re = re.compile(r"[^a-zA-Z]")
def normalize_and_remove_stop_words(raw_text, stem=False, **kwa... |
461483 | import sys
sys.path.append("../")
import json
import arbitrage
import time
from arbitrage.observers import observer
class TestObserver(observer.Observer):
def opportunity(
self,
profit,
volume,
buyprice,
kask,
sellprice,
kbid,
perc,
weighted... |
461488 | import lark
class NType:
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(id(self))
def __eq__(self, other):
return self is other
class NGenericType(NType):
def __init__(self, name):
super(NGenericType, self).__init__(name)
def __repr_... |
461512 | import pandas as pd
import numpy as np
from Event import Event
from Team import Team
from Constant import Constant
class Game:
"""A class for keeping info about the games"""
def __init__(self, path_to_json, event_index=0):
# self.events = None
self.home_team = None
self.guest_team = N... |
461513 | import numpy as np
from SafePDP import SafePDP
from SafePDP import PDP
from JinEnv import JinEnv
from casadi import *
import scipy.io as sio
import matplotlib.pyplot as plt
from colour import Color
import time
import random
from matplotlib import cm
from ControlTools import ControlTools
# --------------------------- l... |
461543 | import torch
import torchtestcase
import unittest
import copy
from survae.nn.layers.autoregressive import MaskedLinear
from survae.nn.nets.autoregressive import MADE, AgnosticMADE
class MADETest(torchtestcase.TorchTestCase):
def test_shape(self):
batch_size = 16
features = 10
hidden_featu... |
461563 | import uuid
from office365.sharepoint.fields.field import Field
from office365.sharepoint.fields.field_creation_information import FieldCreationInformation
from office365.sharepoint.fields.field_type import FieldType
from office365.sharepoint.views.view_field_collection import ViewFieldCollection
from tests import cre... |
461615 | def is_a_url(path):
return (path is not None and isinstance(path, str) and
(path.startswith('http://') or
path.startswith('https://'))
)
def tabular(descriptor):
return 'schema' in descriptor
def streaming(descriptor):
return descriptor.get(PROP_STREAMING)
def stre... |
461626 | import json
from .oauth import OAuth2Test
from social_core.backends.paypal import PayPalOAuth2
class PayPalOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.paypal.PayPalOAuth2'
user_data_url = (
'https://api.paypal.com/v1/identity/oauth2/userinfo?schema=paypalv1.1'
)
expected_user... |
461660 | from office365.sharepoint.base_entity import BaseEntity
class AppPrincipalIdentityProvider(BaseEntity):
pass
|
461697 | from stix_shifter_utils.stix_transmission.utils.RestApiClient import RestApiClient
import json
import hashlib
class APIClient():
def __init__(self, connection, configuration):
# Uncomment when implementing data source API client.
auth_values = configuration.get('auth')
auth = (auth_values['... |
461710 | import json
import os
import numpy as np
import torch
from PIL import Image
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from tqdm import tqdm
from utils.utils import cvtColor, preprocess_input, resize_image
from yolo import YOLO
#-------------------------------------------------------... |
461752 | r"""
NI IO Trace can be used to troubleshoot & debug the setup. It should be installed
when the NI-DAQmx driver is installed.
PyDAQmx parses the NIDAQmx.h header to build ctypes wrappers for all function,
constants, etc. It also wraps the functions which return errors codes to raise
exceptions (and warnings) based on ... |
461762 | import random
import threading
import psutil
def display_cpu():
global running
running = True
currentProcess = psutil.Process()
# start loop
while running:
print(currentProcess.cpu_percent(interval=1))
def start():
global t
# create thread and start it
t = threading.Thread(... |
461794 | import asyncio
from asyncio import Queue
from aioweb3 import AsyncWeb3
async def producer(queue: Queue, jobs: int):
print(f"Enqueue {jobs} jobs")
for index in range(jobs):
await queue.put(index)
async def consumer(queue: Queue, index: int):
def log(*args, **kwargs):
print(f"Worker {inde... |
461805 | import datetime
import os
import requests
import re
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
class CongresspersonDetails:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA_PATH = os.path.join(BASE_DIR, 'data')
DATE = datetime.date.today().strftime('%... |
461807 | from django.urls import path
from django_cradmin.apps.cradmin_register_account.views import register_account
urlpatterns = [
path('',
register_account.RegisterAccountView.as_view(),
name="cradmin-register-account"),
]
|
461818 | import info
class subinfo(info.infoclass):
def setTargets(self):
self.svnTargets['master'] = 'https://github.com/win-iconv/win-iconv.git'
for ver in ['0.0.7', '0.0.8']:
self.targets[ver] = 'https://github.com/win-iconv/win-iconv/archive/v%s.tar.gz' % ver
self.archiveNames[v... |
461868 | import copy
import warnings
from math import sqrt, exp, log, cosh, sinh
import numpy as np
import pytest
from scipy import linalg
from numpy.testing import assert_array_almost_equal, assert_array_equal
from sklearn.utils import check_random_state
from sklearn.covariance import EmpiricalCovariance, LedoitWolf
from nil... |
461891 | def _run(script):
global __file__
import os, sys
sys.frozen = 'macosx_plugin'
base = os.environ['RESOURCEPATH']
__file__ = path = os.path.join(base, script)
if sys.version_info[0] == 2:
with open(path, 'rU') as fp:
source = fp.read() + "\n"
else:
with open(path, 'r', encoding='utf-8') as fp:
source = f... |
461896 | import sys
import os
path = "DataBackups"
auth = ["User"]
fitapp = ["UserFitbit", "TimeSeriesDataType", "TimeSeriesData"]
tracktivityPetsWebsite = ["Inventory",
"Level",
"Scenery",
"CollectedScenery",
"Pet",
... |
461904 | from __future__ import unicode_literals
from .. import Provider as CompanyProvider
class Provider(CompanyProvider):
formats = (
'{{last_name}} {{company_suffix}}',
'{{last_name}} {{last_name}} {{company_suffix}}',
'{{last_name}} {{last_name}} {{company_suffix}}',
'{{last_name}}',
... |
461927 | import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Run2_2018_cff import Run2_2018
process = cms.Process("HFTEST",Run2_2018)
process.load("FWCore.MessageService.MessageLogger_cfi")
process.load("SimGeneral.HepPDTESSource.pdt_cfi")
process.load('Configuration.StandardSequences.Generator_cff')
#--- ... |
461928 | from Core.HookWindow import PixelMatchesColor
class ScanStages:
def __init__(self, name):
self.stage = 0
self.name = name
def ScanStages(self, Localization, color, colorFull):
if PixelMatchesColor(Localization[0] + 100, Localization[1],
(colorFull[0], colo... |
461930 | from transformers.optimization import get_cosine_schedule_with_warmup , get_linear_schedule_with_warmup
from tqdm import tqdm
import torch as tc
import pdb
import os , sys
import math
import fitlog
import pickle
from models import get_model
from test import test
from utils.train_util import get_data_from_batch
def be... |
461941 | from .common import *
ENVIRONMENT = 'development'
DEBUG = True
TEMPLATE_DEBUG = True
INSTALLED_APPS += (
'debug_toolbar',
)
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
from fnmatch import fnmatch
class glob_list(list):
def __contains__(self, key):
for elt in s... |
461965 | import json
from datetime import datetime
def extract(filename):
"""
Extract data from json.
:param time: filepath to json
:type time: str
:return: (time, name, [timestamps], [latitude], [longitude])
:rtype: tuple
"""
with open(filename, 'r') as f:
data = json.load(f)
if(data['type']=='run'):
timestamp... |
461969 | from segmentation_models_pytorch.base import (ClassificationHead,
SegmentationHead,
SegmentationModel)
from segmentation_models_pytorch.base import initialization as init
from segmentation_models_pytorch.encoders import get_enco... |
461976 | import copy
import itertools
import uuid
from collections import defaultdict
from operator import itemgetter
import boto3
from botocore.exceptions import ClientError
from botocore.stub import Stubber
def stubbed(function):
"""
A decorator that activates/deactivates the Stubber and makes sure all
expected... |
462028 | from abc import abstractmethod
class BaseModule:
"""
A module is basically a class that is called to processes a line of text
and returns the same line (A), a modified version of that line (B) or None (C)
Where:
A = there is nothing to process
B = the line got processed by the module
C = t... |
462030 | import unittest
import torch
import os
import sys
ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")
sys.path.insert(0, ROOT)
from torch_points_kernels.cluster import grow_proximity, region_grow
class TestGrow(unittest.TestCase):
def setUp(self):
self.pos = torch.tensor(
... |
462061 | import os
import time
import math
import basis
import numpy as np
import modeling.geometric_model as gm
import modeling.collision_model as cm
import robot_sim.robots.xarm7_shuidi_mobile.xarm7_shuidi_mobile as xav
if __name__ == '__main__':
import copy
import motion.probabilistic.rrt_connect as rrtc
import... |
462088 | from .data import DataSet, DataCollate
from .embedding import Model as Embedding
from .model import Model
|
462132 | from typing import Tuple, List, Mapping, Optional, Union
import base64
from io import BytesIO, BufferedReader
from .command_builder import BitcoinCommandBuilder, BitcoinInsType
from ...common import Chain
from .client_command import ClientCommandInterpreter
from .client_base import Client, TransportClient
from .client... |
462134 | import ugfx
period = 1 * 1000
needs_icon = True
i = 0
def tick(icon):
global i
i += 1
icon.show()
ugfx.set_default_font("c*")
icon.area(0, 0, icon.width(), icon.height(), 0xFFFF)
icon.text(0, 0, str(i), 0)
return "Test: %d"% i
|
462135 | from app import add
i = 0
while True:
add.delay(4, 5)
add.delay(10, 20)
add.delay(100, 20)
i += 1
if i == 10000:
break
|
462157 | from unittest import TestCase
from cmlkit.utility.indices import *
class TestFourwaySplit(TestCase):
def setUp(self):
self.n = 40
self.k_train = 7
self.k_test = 5
self.k_valid = 15
self.a, self.b, self.c, self.d = fourway_split(
self.n, self.k_train, self.k_tes... |
462184 | from pathlib import Path
import pytest
import spacy
import tomli
from src.spacy_html_tokenizer import __version__, create_html_tokenizer
def test_version():
version = "0.1.3"
pyproject = tomli.loads(Path("pyproject.toml").read_text())
assert pyproject["tool"]["poetry"]["version"] == version
assert __... |
462196 | import numpy as np
class NNet():
"""
Class that represents a fully connected ReLU network from a .nnet file
Args:
filename (str): A .nnet file to load
Attributes:
numLayers (int): Number of weight matrices or bias vectors in neural network
layerSizes (list of ints): Si... |
462208 | from typing import NamedTuple, List
from pokeai.ai.battle_status import BattleStatus
from pokeai.ai.common import PossibleAction
class RLPolicyObservation(NamedTuple):
battle_status: BattleStatus
request: dict
possible_actions: List[PossibleAction]
|
462244 | def greet(name):
print(f'Hello, {name}!')
def test_prints(capsys):
# call the function
greet('Escape School 2021')
# test that it wrote what we expect to stdout
captured = capsys.readouterr()
# .err would be the stderr output
assert captured.out == 'Hello, Escape School 2021!\n'
|
462255 | import fastai
from fastai import *
from fastai.core import *
from fastai.vision.transform import get_transforms
from fastai.vision.data import ImageImageList, ImageDataBunch, imagenet_stats
from .augs import noisify
def get_colorize_data(
sz: int,
bs: int,
crappy_path: Path,
good_path: Path,
rando... |
462260 | import numpy as np
import gzip
import pickle
import os
class MNIST:
def __init__(self, batch_size):
self.batch_size = batch_size
train, valid, test = self._load_data()
self.X_train, self.y_train = train[0], train[1]
# encoding y_train using one-hot encoding
self.y_train_o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.