id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4849477 | import json
import pytest
from model_mommy import mommy
from rest_framework import status
@pytest.fixture
def financial_spending_data(db):
ta1 = mommy.make("TreasuryAppropriationAccount", federal_account__id=1, federal_account_id=1)
mommy.make(
"FinancialAccountsByProgramActivityObjectClass",
... |
4849502 | import lib
import matplotlib.pyplot as plt
import os
import statistics
from collections import OrderedDict
format = "pdf"
os.makedirs("out", exist_ok=True)
runs = lib.get_runs(["cogs_trafo"])
runs = lib.common.group(runs, ['transformer.variant'])
runs["theirs"] = lib.get_runs(["cogs_trafo_official"])
window = 2500
... |
4849505 | import os
import glob
import shutil
from collections import OrderedDict
import json
from batchgenerators.utilities.file_and_folder_operations import *
if __name__ == "__main__":
root = '/home1/glshi/data/private/challenge'
samples = os.listdir(root)
output_dir = '/home1/glshi/data/nnUNet_preprocess/nnUNet_... |
4849534 | import uuid
from rest_framework import views, permissions
from rest_framework.response import Response
from rest_framework import status
from django_otp import devices_for_user
from django_otp.plugins.otp_totp.models import TOTPDevice
from django_otp.plugins.otp_static.models import StaticDevice, StaticToken
from otp.u... |
4849572 | import operator
import pytest
from cartesian.cgp import *
@pytest.fixture()
def pset():
terminals = [Symbol("x_0"), Symbol("x_1"), Constant("c")]
operators = [Primitive("neg", operator.neg, 1)]
pset = PrimitiveSet.create(terminals + operators)
return pset
@pytest.fixture()
def individual(request):... |
4849615 | import cv2
import numpy as np
import matplotlib.pyplot as plt
# Grayscale
def BGR2GRAY(img):
# Grayscale
gray = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0]
return gray
# Bi-Linear interpolation
def bl_interpolate(img, ax=1., ay=1.):
if len(img.shape) > 2:
H, W, C = img.shape
else:
H, W... |
4849616 | from dataclasses import dataclass
from dataclasses_json import dataclass_json
from .base_model import BaseModel
@dataclass_json
@dataclass
class OrthographicCameraInfo(BaseModel):
"""
An orthographic camera containing properties to create an orthographic projection matrix.
Properties:
xmag (number) T... |
4849639 | class BoardgameError(Exception):
pass
class LoadError(BoardgameError):
pass
class InvalidBoardState(LoadError):
pass
class InvalidMoveError(BoardgameError):
pass
class PositionError(BoardgameError):
pass
|
4849669 | from niaaml.preprocessing.feature_selection.feature_selection_algorithm import (
FeatureSelectionAlgorithm,
)
from niaaml.preprocessing.feature_selection.variance_threshold import VarianceThreshold
from niaaml.preprocessing.feature_selection.jDEFSTH import jDEFSTH
from niaaml.preprocessing.feature_selection.select_... |
4849677 | from ROLL.LSTM_wrapped_env import LSTMWrappedEnv
from rlkit.samplers.data_collector import GoalConditionedPathCollector
class LSTMWrappedEnvPathCollector(GoalConditionedPathCollector):
def __init__(
self,
goal_sampling_mode,
env: LSTMWrappedEnv,
policy,
... |
4849689 | def test_vocab(vocab):
return len(vocab)
def test_network(network):
return int(all(param.grad is not None for param in network.parameters()))
def test_batch(batch):
return int(batch[0].shape[0])
|
4849699 | import glob
import os
from eth_utils import to_tuple
from ruamel.yaml import YAML
from yaml_test_execution import execute_ssz_test_case, execute_tree_hash_test_case
YAML_BASE_DIR = os.path.abspath(os.path.join(__file__, "../../eth2.0-tests/"))
SSZ_TEST_FILES = glob.glob(
os.path.join(YAML_BASE_DIR, "ssz", "**/*.y... |
4849712 | import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.autograd import Variable
import numpy as np
from model.utils import create_pointnet_components, create_mlp_components
__all__ = ['pvt_partseg']
class STNbox(nn.Module):
def __init__(self, k=6):
super(STNbox, self).__init... |
4849726 | import asyncio
import time
import avarice
import exchangelayer as el
import genconfig as gc
import genutils as gu
import indicators
import loggerdb as ldb
import notifier as no
import simulator as sim
import strategies
import storage
import trader as trd
pgerr = 'WARNING: Avarice needs pygal and lxml to support graph... |
4849735 | import urllib.request
import urllib.parse
import threading
import sublime
from PyV8 import JSObject, JSArray, JSFunction
from SublimeJS.v8 import getContext, convert
class Http:
def request(self, options, callback=None):
def _call(host, port, auth, method, path, data='', headers={}, callback=None, *args):
data ... |
4849742 | import torch
from os import path
import numpy as np
import ujson as json
from tqdm import tqdm
from torch.utils.data import TensorDataset
from transformers import T5Tokenizer
import nltk
nltk.data.path.append('./nltk_data')
nltk.download('punkt', download_dir='./nltk_data')
def process_file_t5(filename, tokenizer, l... |
4849744 | import seamless
from seamless.core import context, cell, transformer, unilink
ctx = context(toplevel=True)
ctx.cell1 = cell("int").set(1)
ctx.cell2 = cell("int").set(2)
ctx.code = cell("ipython").set("""
%timeit -n 10 c = a + b
%timeit -n 10 c = 99
%%timeit -n 10
def func():
return a + b
c = a + b
""")
ctx.resu... |
4849757 | from mpi4py import MPI
rank = MPI.COMM_WORLD.Get_rank()
info = MPI.INFO_NULL
port = MPI.Open_port(info)
print "Server port: '%s'", port
service = 'cpi'
MPI.Publish_name(service, info, port)
print 'Service %s published', service
root = 0
print 'Waiting for connection request'
comm = MPI.COMM_WORLD.Accept(port, info... |
4849761 | from inqry.system_specs import systemspecs
def test_instantiating_systemspecs_instance():
assert systemspecs.SystemSpecs()
def test_systemspecs_internal_storage_property():
assert systemspecs.SystemSpecs().storage
def test_systemspecs_model_property_has_value():
assert systemspecs.SystemSpecs().model_... |
4849768 | import xml.etree.ElementTree as ET
from urllib import parse
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
import requests_cache
from patent_client import CACHE_CONFIG, CACHE_BASE, SETTINGS
CLIENT_SETTINGS = SETTINGS["ItcEdis"]
USERNAME = CLIENT_SETTINGS["Username"]
PASSWORD = CLIENT_S... |
4849772 | n = int(input())
nb_steps = 0
while len(str(n)) != 1:
m = 1
for c in str(n):
m *= int(c)
n = m
nb_steps += 1
print(nb_steps)
|
4849775 | from .config import INFER_HOST
from .main import runserver, serve_static
__all__ = ("INFER_HOST", "run_app", "runserver", "serve_static")
|
4849803 | from rest_framework import permissions
from dynamic_preferences.api import viewsets
from . import serializers
from . import models
class UserPreferencesViewSet(viewsets.PerInstancePreferenceViewSet):
queryset = models.UserPreferenceModel.objects.all()
serializer_class = serializers.UserPreferenceSerializer
... |
4849864 | from .parser import Gene2GeneRifParser
import biothings.hub.dataload.uploader as uploader
class GenerifUploader(uploader.MergerSourceUploader):
name = "generif"
def load_data(self, data_folder):
gene2generif = Gene2GeneRifParser(data_folder).load()
return gene2generif
@classmethod
de... |
4849890 | import os
import sys
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)))))
sys.path.append(BASE_DIR)
import numpy as np
from tools.path import CIFAR100_path
from simpleAICV.classification import backbones
from simpleAICV.classification import losses
... |
4849900 | from os.path import isfile, join
import pandas as pd
from torch.utils import data
from torchvision import transforms as T
from torchvision.datasets import ImageFolder
from PIL import Image
import torch
import os
import random
from shutil import copyfile, copy2
from helpers.AgeGender import get_gender
class CelebA(... |
4849929 | from jmeter_api.samplers.beanshell.elements import BeanShell
from jmeter_api.basics.utils import tag_wrapper
import xmltodict
import pytest
class TestBeanShell:
class TestResetInterpreter:
def test_check(self):
with pytest.raises(TypeError):
BeanShell(resetInterpreter="True")
... |
4849956 | import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # to import shared utils
import torch
import torch.optim as optim
import torch.nn as nn
import numpy as np
import argparse
import time
import os
import copy
from IPython import embed
from DataLoader import ClevrDataLoader
from m... |
4849967 | from typing import Any, Dict
from .enums import RelationsTypeEnum
__all__ = (
"Relation",
"RelationFollow",
"RelationLike",
"RelationRetweet",
"RelationHide",
"RelationUpdate",
"RelationPin",
"RelationDelete",
)
class Relation:
"""Represents a base class of all relations classes.... |
4849969 | from django.contrib import admin
from .models import ArticleComment, Notification
@admin.register(ArticleComment)
class CommentAdmin(admin.ModelAdmin):
date_hierarchy = 'create_date'
list_display = ('id', 'author', 'belong', 'create_date', 'show_content')
list_filter = ('author', 'belong',)
ordering =... |
4849975 | import asyncio
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from tartiflette.coercers.common import CoercionResult
from tartiflette.constants import UNDEFINED_VALUE
from tartiflette.types.exceptions.tartiflette import CoercionError
from tartiflette.utils.errors import graphql_error_from_nodes
... |
4850010 | import re
from .errors import *
UNKNOWN_PATTERN = '# Unknown object type: (?P<t>.+)'
UNKNOWN = re.compile(UNKNOWN_PATTERN)
INVALID_PATTERN = '# Invalid object specification: \'(?P<t>.+)\''
INVALID = re.compile(INVALID_PATTERN)
NOTFOUND_PATTERN = '# (?P<t>\w+) (?P<r>\d+) does not exist.'
NOTFOUND = re.compile(NOTFOUND_... |
4850021 | from .context import unittest, os, GeneratorPretrainingGenerator, GeneratorPretraining
top = os.getcwd()
class TestGeneratorPretraining(unittest.TestCase):
def sub_test(self, actual, expected, msg=None):
with self.subTest(actual=actual, expected=expected):
self.assertEqual(actual, expected, ms... |
4850031 | from bitmovin.resources.models import AzureInput
from ..rest_service import RestService
from .analyse_service import AnalyzeService
class Azure(RestService, AnalyzeService):
BASE_ENDPOINT_URL = 'encoding/inputs/azure'
def __init__(self, http_client):
super().__init__(http_client=http_client, relative... |
4850156 | import django_filters
from watson import search as watson_search
from ..models import OnlineGroup, OnlineUser
class UserFilter(django_filters.FilterSet):
query = django_filters.CharFilter(method="watson_filter")
def watson_filter(self, queryset, name, value):
if value and value != "":
qu... |
4850176 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^noslash$', views.empty_view),
url(r'^slash/$', views.empty_view),
url(r'^needsquoting#/$', views.empty_view),
]
|
4850233 | from dagster import repository
@repository(name="repo_one")
def repo_one_symbol():
return []
@repository
def repo_two():
return []
|
4850244 | self.description = "Sysupgrade with an epoch and ignore on same package"
lp = pmpkg("dummy", "1.0-1")
self.addpkg2db("local", lp)
sp = pmpkg("dummy", "1:1.0-2")
self.addpkg2db("sync", sp)
self.args = "-Su --ignore %s" % lp.name
self.addrule("PACMAN_RETCODE=0")
self.addrule("PKG_VERSION=dummy|1.0-1")
|
4850340 | import argparse
def parse_args():
parser = argparse.ArgumentParser(
description='PyTorch LaserTagger')
# data arguments
parser.add_argument('--data', default='dataset_50_Laser/',
help='Path to dataset')
parser.add_argument('--save', default='LaserTagger/checkpoints/',
... |
4850352 | from sklearn_explain.tests.skl_datasets import skl_datasets_test as skltest
skltest.test_class_dataset_and_model("BreastCancer" , "AdaBoostClassifier_1")
|
4850355 | import inspect
from guniflask.annotation import Annotation, AnnotationUtils
class AsyncRun(Annotation):
def __init__(self, executor: str = None):
super().__init__(executor=executor)
def async_run(executor: str = None):
def wrap_func(func):
AnnotationUtils.add_annotation(func, AsyncRun(execu... |
4850435 | import bpy
class OpenPoseToRigifySettings(bpy.types.PropertyGroup):
facial_capture: bpy.props.BoolProperty(
name="Facial Capture",
description="As We read in the JSON files do we apply facial capture to the character",
default = True
)
body_capture: bpy.props.BoolPrope... |
4850441 | import logging
import time
from urllib import parse as urlparse
from functools import partial
from gdc_client.parcel import colored, manifest
from gdc_client.download.client import GDCHTTPDownloadClient
from gdc_client.query.index import GDCIndexClient
from gdc_client.query.versions import get_latest_versions
from gd... |
4850442 | import cv2 as cv
img = cv.imread("number.png")
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 降噪
ret, thresh = cv.threshold(gray_img, 127, 255, 0)
# 寻找轮廓
contours, hierarchy = cv.findContours(gray_img, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
cnt = contours[0]
# 绘制最小外接圆
# (x, y), radius = cv.minEnclosingCircle(cnt)
# ce... |
4850480 | from PYB11Generator import *
class SVPHFieldNames:
A_SVPH = PYB11readonly(static=True, returnpolicy="copy")
B_SVPH = PYB11readonly(static=True, returnpolicy="copy")
gradB_SVPH = PYB11readonly(static=True, returnpolicy="copy")
|
4850496 | import sublime
import sublime_plugin
import os,json,re
from datetime import datetime
from time import sleep
import shutil
from . import baseutil
from . import util
from .setting import SfBasicConfig
from . import xlsxwriter
from .requests.exceptions import RequestException
from .salesforce import (
SalesforceMoreT... |
4850527 | import re
class IpHelper:
@staticmethod
def is_valid_ipv4(ip):
"""Validates IPv4 addresses.
"""
pattern = re.compile(r"^\d{1,3}\.\d{1,3}.\d{1,3}.\d{1,3}$", re.VERBOSE | re.IGNORECASE)
if pattern.match(ip) is None:
return False
for x in ip.split("."):
... |
4850540 | import unittest
from hydra import compose, initialize_config_dir
from nuplan.planning.script.run_simulation import CONFIG_NAME, main
from nuplan.planning.script.test.skeleton_test_simulation import SkeletonTestSimulation
class TestRunSequentialWorker(SkeletonTestSimulation):
"""Test running sequential workers i... |
4850550 | from .losses import ROI_mean_squared_error_loss,wind_ROI_mean_squared_error,ROI_diff_mse_joint_loss,ROI_diff_temporal_loss,wind_ROI_diff_temporal_loss
from .util import agg_window,create_windowed_arr,save_multiple_graph,get_output,gather_auc_avg_per_tol,join_mean_std,create_diff_mask
import matplotlib.pyplot as plt
fro... |
4850558 | import pickle
import re
from collections import defaultdict
from ._base import BaseTokenizer
class DisjointLetterTokenizer(BaseTokenizer):
""" Disjoint Letters based tokenization
"""
def train(self, file_path):
"""Train data using disjoint letters
Args:
file_path (str): fil... |
4850560 | import json
import random
from collections import defaultdict
from datetime import datetime, timedelta
from typing import List
from django.utils import timezone
from firebase_admin.messaging import (AndroidConfig, Message, Notification, QuotaExceededError,
send as send_notification, SenderIdMismatchError, ThirdPar... |
4850602 | from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.auth.password_validation import validate_password
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.e... |
4850620 | from datetime import datetime
import yaml
from dateutil.tz import UTC
from src.Error import Error
class Configuration:
"""
Encapsulates configuration file and provides various convenience methods.
"""
@classmethod
def from_file(cls, file_name):
try:
stream = open(file_name, ... |
4850642 | import shutil, os
example_dir = os.path.split(os.path.realpath(__file__))[0]
src_dir = example_dir + '/dist'
manifest = example_dir + '/src/manifest.json'
dist_dir_ios = example_dir + '/../iOS/assets.bundle'
dist_dir_android = example_dir + '/../Android/example/src/main/assets'
def clear_dir(dist_path):
fo... |
4850715 | import os
import time
import numpy as np
################################
def TicTocGenerator():
# Generator that returns time differences
ti = 0 # initial time
tf = time.time() # final time
while True:
ti = tf
tf = time.time()
yield tf-ti # returns the time differenc... |
4850731 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="spark_tensorflow_distributor",
version="0.0.3",
author="sarthfrey",
author_email="<EMAIL>",
description="This package helps users do distributed training with TensorFlow on their Spark clusters.",
... |
4850740 | if __name__ == "__main__":
'''
dictionary.fromkeys(sequence[, value])
'''
seq = ('name', 'age', 'sex')
dict_1 = dict.fromkeys(seq)
print('dict_1', dict_1)
dict_2 = dict.fromkeys(seq, 10)
print('dict_2', dict_2)
|
4850747 | import pytest
import json
import unittest
from unittest.mock import Mock, MagicMock, patch, call
from kafka import KafkaProducer
from DeviceManager.BackendHandler import KafkaHandler, KafkaInstanceHandler
class TestBackendHandler(unittest.TestCase):
@patch("DeviceManager.BackendHandler.KafkaNotifier")
@patch... |
4850757 | from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import types
from random import randint
from operator import __xor__
from functools import reduce
def add4(a,b):
"""scalar or vector addition in GF(4)"""
if type(b) == types.ListType:
if type(a... |
4850758 | from random import randint
from retrying import retry
from apysc._type.expression_string import ExpressionString
class TestExpressionString:
@retry(stop_max_attempt_number=15, wait_fixed=randint(10, 3000))
def test___init__(self) -> None:
exp_str: ExpressionString = ExpressionString(valu... |
4850795 | import Weapon
import WeaponGlobals
from direct.interval.IntervalGlobal import *
from pandac.PandaModules import *
from pirates.inventory import ItemGlobals
from pirates.piratesbase import PLocalizer
from pirates.effects import PolyTrail
from pirates.audio import SoundGlobals
from pirates.audio.SoundGlobals import loadS... |
4850800 | import sys
import threading
from contextlib import contextmanager
from pathlib import Path
from time import sleep
from typing import TYPE_CHECKING
import anyio
import pytest
from watchfiles import Change, awatch, watch
from watchfiles.main import _calc_async_timeout
if TYPE_CHECKING:
from conftest import MockRus... |
4850822 | import unittest
import uuid
from google.appengine.ext import testbed, ndb
from mock import patch, PropertyMock
from src.backup.datastore.Backup import Backup
from src.backup.datastore.Table import Table
from src.commons.config.configuration import Configuration
from src.commons.exceptions import ParameterValidationEx... |
4850834 | from os import path
from setuptools import setup
description = ''
try:
import pypandoc # pylint: disable=F0401
description = pypandoc.convert('README.md', 'rst')
except Exception:
pass
v = path.join('cloud4rpi', 'version.py')
with open(v) as f:
version_code = compile(f.read(), v, 'exec')
exec(v... |
4850843 | import numpy as np
__all__ = ["rle_decode", "rle_encode", "rle_to_string"]
def rle_encode(mask: np.ndarray):
"""
Convert mask to EncodedPixels in run-length encoding
from https://www.kaggle.com/stainsby/fast-tested-rle-and-input-routines
"""
pixels = mask.T.flatten()
# We need to allow for ca... |
4850846 | from flask import url_for
from sqlalchemy.ext.associationproxy import association_proxy
from sopy import db
from sopy.auth.models import User
from sopy.ext.models import IDModel
from sopy.se_data.models import SEQuestion
from sopy.tags.models import HasTags
class CanonItem(HasTags, IDModel):
title = db.Column(db.... |
4850867 | import json
from ees.model import Response
class VersionHandler:
def execute(self, cmd):
return Response(
http_status=200,
body={
"version": "0.0.1"
})
|
4850938 | from copy import deepcopy
from functools import wraps
import attr
import sys
import os
from pathlib2 import Path
from clearml_agent.helper.process import Argv, DEVNULL, check_if_command_exists
from clearml_agent.session import Session, POETRY
def prop_guard(prop, log_prop=None):
assert isinstance(prop, property... |
4850953 | import numpy as np
import sys
import argparse
import yaml
import torch
import torch.nn as nn
import icp
import torchvision.utils as vutils
import model
# Arguments
parser = argparse.ArgumentParser(
description='Train ICP.'
)
parser.add_argument('config', type=str, help='Path to cofig file.')
args = parser.parse_... |
4850961 | from abc import ABC, abstractmethod
from typing import List
from bridge.types import Model, Artifact
class ModelRegistry(ABC):
@abstractmethod
def list_models(self) -> List[Model]:
pass
@abstractmethod
def fetch_version_artifact(
self, model_name: str, version: str
) -> Artifact:
... |
4850962 | import pickle
import json
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.linear_model import Lasso
from sklearn.model_selection import GridSearchCV
from mlserve import build_schema
diabetes = datasets.load_diabetes()
X = diabetes.data[:150]
y = diabetes.target[:150]
lasso = Lasso(r... |
4850983 | import unittest
from mock import patch
from kafka.tools.protocol.requests import ArgumentError
from kafka.tools.protocol.requests.create_topics_v0 import _parse_partition, _parse_kv_args, _parse_remaining_args, CreateTopicsV0Request
class CreateTopicsV0RequestTests(unittest.TestCase):
def setUp(self):
se... |
4851023 | import json
from io import BytesIO
from dongtai_agent_python.utils import scope
class Request(object):
def __init__(self, request):
super(Request, self).__init__()
self.scheme = request.scheme
self.headers = dict(request.headers)
class DjangoRequest(Request):
def __init__(self, req... |
4851079 | from interface import Interface
from liteflow.core.models import *
class IPersistenceProvider(Interface):
def create_workflow(self, workflow: WorkflowInstance):
pass
def persist_workflow(self, workflow: WorkflowInstance):
pass
def get_workflow_instance(self, id) -> WorkflowInstance:
... |
4851083 | from django.test import TestCase
from localflavor.md import forms
from .forms import MDPlaceForm
class MDLocalFlavorTests(TestCase):
def setUp(self):
self.data = {
'idno': '1231231231231',
'company_type_1': 'SRL',
'company_type_2': 'II',
'license_plate': ... |
4851125 | import os
import sys
import time
import datetime
import argparse
import re
from pathlib import Path
from copy import deepcopy, copy
import traceback
import warnings
import numpy as np
from numba import jit
import pandas as pd
from sklearn.metrics import roc_auc_score, confusion_matrix, mean_squared_error
from .prepro... |
4851138 | import unittest
import ctypes
from ctypeslib.codegen.util import get_cursor
from ctypeslib.codegen.util import get_tu
from test.util import ClangTest
"""Test if functions are correctly generated.
"""
class TestFunction(ClangTest):
"""
ctypes.CFUNCTYPE a function type declaration in python code
Usage:
... |
4851145 | import mysql.connector
def main():
connection = mysql.connector.connect(user='readonly', password='<PASSWORD>',
host='covid-19-biconnector.hip2i.mongodb.net',
port='27015',
database='covid19'... |
4851177 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class LabourAppConfig(AppConfig):
name = 'labour'
verbose_name = _('Volunteer management')
def ready(self):
from . import event_log_entry_types # noqa
|
4851187 | import python_jsonschema_objects as pjs
import pytest
@pytest.fixture
def testclass():
builder = pjs.ObjectBuilder({"title": "Test", "type": "object"})
ns = builder.build_classes()
return ns.Test()
def test_extra_properties_can_be_deleted_with_item_syntax(testclass):
# Deletion before setting should... |
4851206 | import unittest
from programy.context import ClientContext
from programy.dynamic.maps.lemmatize import LemmatizeMap
from programytest.client import TestClient
class TestLemmatizeMaps(unittest.TestCase):
def setUp(self):
self._client_context = ClientContext(TestClient(), "testid")
def test_static_ma... |
4851207 | from django import template
from ..models import SequencingMachine
register = template.Library()
@register.simple_tag
def get_details_sequencers(project):
"""Return sequencers for the project details page"""
return SequencingMachine.objects.filter(project=project)[:5]
|
4851238 | from opensfm.actions import reconstruct_from_prior
from . import command
class Command(command.CommandBase):
name = "reconstruct_from_prior"
help = "Reconstruct from prior reconstruction"
def run_impl(self, dataset, args):
reconstruct_from_prior.run_dataset(dataset, args.input, args.output)
... |
4851262 | from django.apps import AppConfig
class RestFrameworkRolesConfig(AppConfig):
name = 'rest_framework_roles'
verbose_name = 'REST Framework Roles'
def ready(self):
from .patching import patch
patch()
|
4851265 | import asyncio
import sys
from .exceptions import LoopNotRunning
def _get_current_task(loop): # noqa
if sys.version_info[:2] < (3, 7): # to avoid deprecation warning
return asyncio.Task.current_task(loop=loop)
else:
return asyncio.current_task(loop=loop)
def _check_event_loop():
if n... |
4851288 | from os.path import abspath, dirname, join
from tornado.ioloop import IOLoop
from tornado.web import StaticFileHandler
from tornado.websocket import WebSocketHandler, WebSocketClosedError
from .nt_serial import NTSerial
import logging
logger = logging.getLogger("net2js")
__all__ = ["get_handlers", "NetworkTablesWe... |
4851325 | from functools import partial
import numpy as np
from violajones.HaarLikeFeature import HaarLikeFeature
from violajones.HaarLikeFeature import FeatureTypes
import progressbar
from multiprocessing import Pool
LOADING_BAR_LENGTH = 50
# TODO: select optimal threshold for each feature
# TODO: attentional cascading
def ... |
4851395 | from django.urls import path
from grandchallenge.notifications.views import (
FollowCreate,
FollowDelete,
FollowList,
NotificationList,
)
app_name = "notifications"
urlpatterns = [
path("", NotificationList.as_view(), name="list"),
path("subscriptions/", FollowList.as_view(), name="follow-lis... |
4851411 | import unittest
import torch
from allennlp.common.params import Params
from zsl_kg.knowledge_graph.conceptnet import ConceptNetKG
class TestConceptNetKG(unittest.TestCase):
def setUp(
self,
):
"""creates an instance of KG with sample data."""
params = Params({})
nodes = [
... |
4851508 | import asyncio
import string
import random
from typing import Generator
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy.pool import StaticPool
class MemorySql():
def __init__(self, ... |
4851541 | import logging
from flask import request
from flask_restful import Resource
from werkzeug.exceptions import NotFound
from rdr_service.api.data_gen_api import generate_samples_task
from rdr_service.app_util import task_auth_required
from rdr_service.dao.bq_code_dao import rebuild_bq_codebook_task
from rdr_service.dao.... |
4851550 | from stable_baselines3 import PPO
from stable_baselines3.common.evaluation import evaluate_policy
# A basic agent.
class SB3PPOAgent:
def __init__(self):
super().__init__()
self.sb3_ppo = self.tracker.restore("ppo")
if self.sb3_ppo is None:
self.sb3_ppo = PPO("MlpPolicy", self.... |
4851574 | from collections.abc import Iterable
import numpy as np
import openmdao.api as om
from ..transcription_base import TranscriptionBase
from ..common import TimeComp, PseudospectralTimeseriesOutputComp
from .components import StateIndependentsComp, StateInterpComp, CollocationComp
from ...utils.misc import CoerceDesvar,... |
4851594 | from starling_sim.basemodel.trace.events import *
from starling_sim.basemodel.agent.requests import UserStop, StopPoint, StationRequest
from starling_sim.utils.constants import PUBLIC_TRANSPORT_TYPE
class KPI:
"""
Generic structure of a KPI class
Its sub-classes compute and update specific indicator
... |
4851606 | import os
import numpy as np
import pickle
import header
import sys
import random
import numpy.matlib as npm
from Quaternion import Quat
import pickle
import Quaternion
import argparse
import head_orientation_lib
import saldat_head_orientation
# Q is a Nx4 numpy matrix and contains the quaternions to average in the... |
4851607 | import math
import os
import numpy as np
import torch
import torch.nn as nn
from args import conf
args = conf()
__all__ = [ 'bn_AlexNet', 'bn_alexnet']
class bn_AlexNet(nn.Module):
def __init__(self, num_classes=1000):
super(bn_AlexNet, self).__init__()
self.features = nn.Sequential(
... |
4851629 | modes = {
'aar': ['Latn'],
'amh': ['Ethi-pp', 'Ethi-red', 'Ethi'],
'ara': ['Arab'],
'aze': ['Latn', 'Cyrl'],
'ben': ['Beng', 'Beng-red'],
'cat': ['Latn'],
'ceb': ['Latn'],
'ces': ['Latn'],
'ckb': ['Arab'],
'deu': ['Latn', 'Latn-np... |
4851638 | import dataikuapi
def test_run_scenario(params, scenario_id):
print("*************************")
print("Executing scenario ", scenario_id)
client = dataikuapi.DSSClient(params["host"], params["api"])
project = client.get_project(params["project"])
scenario_result = project.get_scenario(scenario_id... |
4851653 | def pattern(n):
n1=1
for i in range(0,n):
for j in range(0,i+1):
print(n1,end=" ")
n1=n1+1
print("\r")
pattern(4)
|
4851697 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="spark_privacy_preserver", # Replace with your own username
version="0.3.1",
author="thamindu",
author_email="<EMAIL>",
description="Anonymizing Library for Apache Spark",
long_descrip... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.