id
stringlengths
3
8
content
stringlengths
100
981k
4861542
import array import user_context def test(): output = bytearray("\0\0\0\0", "ascii") user_context.user_context(None, ord('q'), output) assert output == bytearray("qqqq", "ascii") if __name__ == "__main__": test()
4861569
from .packet import Packet from minecraft.networking.types import String, TrailingByteArray class AbstractPluginMessagePacket(Packet): """NOTE: Plugin channels were significantly changed, including changing the names of channels, between Minecraft 1.12 and 1.13 - see <http://wiki.vg /index.php?title...
4861595
import datetime as dt import enum from sqlalchemy.ext.hybrid import hybrid_method from sqlalchemy.orm import backref from sqlalchemy_utils import ChoiceType from server.api.database import db from server.api.database.mixins import ( Column, Model, SurrogatePK, reference_col, relationship, ) clas...
4861621
import numpy import unittest import warnings import theano from theano import tensor from .linear import dot_shape from .linear import dot_shape_from_shape from .linear import dot def assert_compute_equal(outputs, inputs=[]): outputs = [tensor.as_tensor_variable(o) for o in outputs] f = theano.function(input...
4861654
import torch from ..function import qsigned, qunsigned from collections import OrderedDict def cosine_similarity(net, qnet, wba=[8, 16, 8], show=False): ret = [] n_param, q_param = OrderedDict(net.named_parameters()), OrderedDict( qnet.named_parameters()) for name in n_param.keys(): if nam...
4861656
from .base import MongoCollector from .coll_stats import CollStatsCollector from .custom_queries import CustomQueriesCollector from .db_stat import DbStatCollector from .fsynclock import FsyncLockCollector from .index_stats import IndexStatsCollector from .replica import ReplicaCollector from .replication_info import R...
4861666
import time import torch import torch.nn as nn import torch.nn.functional as F import torchvision from utils.logging import AverageMeter, ProgressMeter from utils.eval import accuracy # TODO: support sm_loader when len(sm_loader.dataset) < len(train_loader.dataset) def train( model, device, train_loader, sm_load...
4861673
import os import shutil from glob import glob percent = ['0.8', '0.64', '0.512', '0.4096', '0.32768', '0.262144', '0.2097152', '0.1677722' ,'0.1342177','0.1073742'] Alist = sorted(glob(os.path.join(percent[0], 'horse2zebra', 'A', '*.png'))) Blist = sorted(glob(os.path.join(percent[0], 'horse2zebra', 'B', '*.png'))) An...
4861677
description = 'Main Treff setup' group = 'basic' includes = [ 'counter', # 'filter', # 'mc2', # 'polarizer', 'sampletable', 'shutter', 'slits', 'guidehall', 'nl5', 'reactor', ]
4861714
from ray.util.lightning_accelerators.horovod_ray_accelerator import \ HorovodRayAccelerator __all__ = ["HorovodRayAccelerator"]
4861800
from threading import Thread, Lock, Event from zlib import compress, decompress import time import zmq from google import protobuf from .engine_commons import getUUID, getOpenPort, baseToPubSubPort from .message_pb2 import SocketMessage ################# ### CONSTANTS ### ################# from .constants import DELI...
4861815
from torch.utils.data import sampler from torch.utils.data import Dataset class ChunkSampler(sampler.Sampler): """Samples elements sequentially from some offset. Arguments: num_samples: # of desired datapoints start: offset where we should start selecting from """ def __init__(self, n...
4861891
import numpy as np from numpy.testing import assert_array_equal import pytest from numcodecs.delta import Delta from numcodecs.tests.common import (check_encode_decode, check_config, check_repr, check_backwards_compatibility) # mix of dtypes: integer, float # mix of shapes: 1D, 2...
4861904
from . import builtin from ..backends.make import writer as make from ..backends.ninja import writer as ninja from ..build_inputs import Edge from ..file_types import Phony class Alias(Edge): def __init__(self, context, name, deps=None): super().__init__(context.build, Phony(name), extra_deps=deps) @bui...
4861940
import importlib ENTRY_POINT = 'conda_env.installers' class InvalidInstaller(Exception): def __init__(self, name): msg = 'Unable to load installer for {}'.format(name) super(InvalidInstaller, self).__init__(msg) def get_installer(name): try: return importlib.import_module(ENTRY_POINT...
4861957
from collections import namedtuple import numpy as np import talib from jesse.indicators.ma import ma from jesse.helpers import get_candle_source, slice_candles MAB = namedtuple('MAB', ['upperband', 'middleband', 'lowerband']) def mab(candles: np.ndarray, fast_period: int = 10, slow_period: int = 50, devup: float...
4861974
from .build import Command as BuildCommand from ._base import CommandOption class Command(BuildCommand): help = 'Install and build the whole application, and prepare the database for an initial start.' options = BuildCommand.options + ( CommandOption('-u', '--update', action='store_true', dest='updat...
4862021
import soundfile as sf import sounddevice as sd from scipy.io.wavfile import write def record_voice(): """This function records your voice and saves the output as .wav file.""" fs = 44100 # Sample rate seconds = 3 # Duration of recording # sd.default.device = "Built-in Audio" # Speakers full name h...
4862025
class adv_config(object): # Adversarial Training Hyper-Parameters total_batch = 1000 # Total batches for adversarial training gen_update_time = 1000 dis_update_time = 2 dis_epoch_per_update = 1 gen_train_dir = './gen_train_adv' # Directory to save G's parameters disc_train_dir = './di...
4862037
import os import sys import torch cur_path = os.path.abspath(os.path.dirname(__file__)) root_path = os.path.split(cur_path)[0] sys.path.append(root_path) from torchvision import transforms from PIL import Image from segmentron.utils.visualize import get_color_pallete from segmentron.models.model_zoo import get_segmen...
4862043
from typing import List class Solution: def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]: if not matrix or not matrix[0]: return [] m, n = len(matrix), len(matrix[0]) p_visited = [[False] * n for x in range(m)] # Pacific a_visited = [[False...
4862052
import os from tree_sitter import Language from code_search import shared from code_search.function_parser.utils import get_tree_sitter_languages_lib languages = [ os.path.join(shared.VENDOR_DIR, 'tree-sitter-python'), os.path.join(shared.VENDOR_DIR, 'tree-sitter-javascript'), os.path.join(shared.VENDOR_...
4862072
import sys import random f = open('random.config', 'w') f.write('height 50\n') f.write('width 50\n') numRobots = 'numRobots ' + str(sys.argv[1]) + '\n' f.write(numRobots) numRobots = int(sys.argv[1]) f.write('R 500\n') f.write('baseX 0\n') f.write('baseY 0\n') f.write('initLocs\n') initLocs = [] for i in...
4862074
import torch from torch import nn from rcnn.modeling.fast_rcnn import heads from rcnn.modeling.fast_rcnn import outputs from rcnn.modeling.fast_rcnn.inference import box_post_processor from rcnn.modeling.fast_rcnn.loss import box_loss_evaluator from rcnn.modeling import registry from rcnn.core.config import cfg clas...
4862147
import pytest from amocrm.v2.model import _get_container_by_path @pytest.mark.parametrize( ("path", "data", "expect"), [ (["name"], {"name": "test"}, {"name": "test"}), (["name"], {"name": "test", "value": "no"}, {"name": "test"}), (["name", "value"], {"name": {"value": "test"}}, {"na...
4862171
from __future__ import print_function from keras import backend as K from keras.layers import Conv2D, Concatenate, Dense, Flatten, BatchNormalization, Activation, AveragePooling2D from keras.models import Model, Input, Sequential from keras.utils import plot_model def _convbnrelu(x, nb_filters, stride, kernel_size, ...
4862250
import os import gc import json import numpy as np import gzip from gensim.models import TfidfModel, LsiModel from gensim.corpora import Dictionary from nlpia.data.loaders import BIGDATA_PATH, read_csv KEEP_N = 300000 # max vocab size NO_BELOW = 5 # min DF (count) NO_ABOVE = .7 # max DF (fraction) def l...
4862264
import torch import lmdb import random import os import glob import numpy as np from PIL import Image from torch.utils.data import Dataset, DataLoader from torchvision import transforms def prase_segmentation(img): ''' Convert 3-channel rgb to 6-channel senmantic mask Six classes: moving obstacles, traff...
4862314
import torch import torch.utils.data as data_utils import torchvision import numpy as np import ipdb import os # ====================================================================================================================== def load_dynamic_mnist(args, **kwargs): # set args if args.down_sample: ...
4862338
import os from githammer import DatabaseNotInitializedError from .hammer_test import HammerTest class HammerInitTest(HammerTest): def test_plain_init_does_not_create_database(self): self.assertFalse(os.listdir(self.working_directory.name)) def test_update_fails_when_database_not_created(self): ...
4862379
from math import log, ceil print("""What do you want to calculate? type "n" for number of monthly payments, type "a" for annuity monthly payment amount, type "p" for loan principal:""") type_ = input("> ") if type_ == "n": p = int(input("Enter the loan principal:\n")) a = float(input("Enter the monthly paymen...
4862390
from typing import Dict, Optional, List, Any import logging from overrides import overrides import torch from torch.nn.modules.linear import Linear from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import Seq2SeqEncoder, TimeDistributed, TextFieldEmbedder from allennlp...
4862435
import argparse import os import numpy as np from tqdm import tqdm from utils import model, utils from utils.utils import print_arguments parser = argparse.ArgumentParser() parser.add_argument('--list_path', default='dataset/test_list.txt', type=str, help='用于测试的数据列表') parser.add_argument('--model_path', default...
4862450
import asyncio import logging import pathlib import jinja2 import aiohttp_jinja2 from aiohttp import web from app import configuration from app.routes import setup_routes from app.helpers.global_helpers import setup_global_helpers from app.handlers.security.errors import errors_middleware from app.handlers.cookies impo...
4862594
import numpy as np import pytest from persia.embedding.data import ( _ND_ARRAY_SUPPORT_TYPE, NdarrayDataBase, IDTypeFeature, IDTypeFeatureWithSingleID, PersiaBatch, ) from persia.prelude import check_pyarray_dtype_valid def test_ndarray_base_dtype_convert_to_tensor(): for dtype in _ND_ARRAY_...
4862595
import json from com.huawei.iotplatform.client.invokeapi.Authentication import Authentication from com.huawei.iotplatform.client.invokeapi.SubscriptionManagement import \ SubscriptionManagement from com.huawei.iotplatform.client.dto.AuthOutDTO import AuthOutDTO from com.huawei.iotplatform.client.dto.DeleteBatchSu...
4862607
from __future__ import absolute_import input_name = '../examples/linear_elasticity/elastic_contact_sphere.py' output_name = 'test_elastic_contact_sphere.vtk' from tests_basic import TestInput class Test(TestInput): pass
4862619
from pathlib import Path import json from tdw.librarian import ModelLibrarian, ModelRecord from tdw.asset_bundle_creator import AssetBundleCreator from typing import Union, List, Optional from argparse import ArgumentParser import csv from tqdm import tqdm class _ShapeNet: def __init__(self, src: Union...
4862683
from modelci.metrics.cadvisor.cadvisor import CAdvisor # Tests if __name__ == "__main__": # Init the CAdvisor client, you can set the API information here. cAdvisor = CAdvisor() # base_link=None, version=None, query_object=None cAdvisor_version12 = CAdvisor(version='v1.2') # default is v1.3 raw_a...
4862704
from ..ir_utils import HDLVisitor, Scope, add_to_list, res_true, ir, IrExprRewriter, IrExprVisitor, IrVisitor from . import hls_debug class VariableFinder(IrExprVisitor): def __init__(self): self.variables = set() def visit_Name(self, node): self.variables.add(node.name) class InferRegister...
4862735
import functools import multiprocessing from django.conf import settings from tenant_schemas.migration_executors.base import MigrationExecutor, run_migrations class ParallelExecutor(MigrationExecutor): codename = 'parallel' def run_tenant_migrations(self, tenants): if tenants: processes...
4862802
import os import shutil import tempfile import unittest from ...views.upload.data import TextData from ...views.upload.dataset import FastTextDataset from ...views.upload.label import CategoryLabel class TestFastTextDataset(unittest.TestCase): def setUp(self): self.test_dir = tempfile.mkdtemp() ...
4862828
from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.schedulers.background import BackgroundScheduler import logging import psycopg2 from UnoCPI import sqlfiles,settings import os import Update_Partner, Update_Project #sched = BlockingScheduler() #sched1 = BackgroundScheduler() # Initializin...
4862875
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models import torch.utils.model_zoo as model_zoo class ResNetEncoder(models.ResNet): """Constructs a resnet model with varying number of input images. Adapted from https://github.com/pytorch/vision/blob/master/torch...
4862881
import turtle tina= turtle.Turtle() tina.pencolor("#339999") tina.fillcolor("#339999") tina.begin_fill() for i in range(0, 4, 1): tina.forward(180) tina.circle ((-20),90) tina.end_fill() tina.penup() tina.goto(0,-160) tina.pendown() tina.pencolor("#ffffff") tina.write("m",False,align="left",font=("Ravie",120,"...
4862884
def max_nested_braces(expr): max_count = count = 0 for char in expr: if char == '{': count += 1 if count > max_count: max_count = count elif char == '}': if count == 0: return -1 count -= 1 if count != 0: ...
4862890
from tensorflow.keras.models import load_model import numpy as np class CartpoleRLRemoteAgent(object): def __init__(self): # The model under GCS bucket is the best one based on it highest score. # Get public info at: https://www.googleapis.com/storage/v1/b/cartpole-rl-models/o/cartpole-rl-remote....
4862893
import sys import csv from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from bs4 import BeautifulSoup from random impo...
4862945
from torch import nn from .mish import Mish from .swish import Swish def make_act(act='ReLU', **kwargs): inplace = kwargs.pop("inplace", True) if len(act) == 0: return None act = { "ReLU": nn.ReLU(inplace=inplace), "ReLU6": nn.ReLU6(inplace=inplace), "PReLU": nn.PReLU(), ...
4862946
import json import logging import math from copy import deepcopy import numpy as np from qcelemental.models import AtomicInput, AtomicResult, Molecule from qcelemental.util.serialization import json_dumps from . import history from .exceptions import OptError class ComputeWrapper: """An implementation of MolSSI...
4862955
from pynput.keyboard import Key, Controller class WindowsBuiltInScreenRecorder: def __init__(self): self.recording = False self.keyboard: Controller = Controller() def __sendRecordStopCombination(self): self.keyboard.press(Key.cmd) self.keyboard.press(Key.alt) self.keyb...
4863024
import urllib3 pool = urllib3.PoolManager() resp = pool.request("method", "url") # $ clientRequestUrlPart="url" resp = pool.request("method", url="url") # $ clientRequestUrlPart="url" resp = pool.urlopen("method", "url") # $ clientRequestUrlPart="url" resp = pool.urlopen("method", url="url") # $ clientRequestUrlPart=...
4863031
import mock import pytest from decimal import Decimal from waffle.models import Flag from website.settings import DOMAIN from api.base.middleware import SloanOverrideWaffleMiddleware from osf_tests.factories import ( AuthUserFactory, PreprintFactory, PreprintProviderFactory ) from osf.features import ( ...
4863032
import numpy as np from unittest import TestCase from diffprivlib.mechanisms import Staircase from diffprivlib.utils import global_seed class TestStaircase(TestCase): def setup_method(self, method): if method.__name__ .endswith("prob"): global_seed(314159) self.mech = Staircase ...
4863038
from uai.arch_conf.tf_conf import TFJsonConfLoader class RetrainJsonConfLoader(TFJsonConfLoader): def __init__(self, conf): super(RetrainJsonConfLoader, self).__init__(conf) def _load(self): super(RetrainJsonConfLoader, self)._load() self.input_width = eval(self.server_conf['tensorflo...
4863073
from unittest import TestCase from modules.base import errors class TestFunctions(TestCase): def test_get_error_message_from_code__static_message(self): self.assertEqual('Your account has been disabled by an administrator.', errors.get_error_message_from_code('account_disabled')) def t...
4863095
from utils import Env def test_revrange(): start_ts = 1511885908 samples_count = 200 expected_results = [] with Env().getClusterConnectionIfNeeded() as r: r.execute_command('TS.CREATE', 'tester1', 'uncompressed') for i in range(samples_count): r.execute_command('TS.ADD', '...
4863106
import pytest from secedgar.parser import F4Parser, MetaParser class TestParser: parser = MetaParser() def test_process_document_metadata(self): doc = """<TYPE>10-K <SEQUENCE>123 <FILENAME>test-filename.txt """ metadata = self.parser.process_document_metadata(doc) ...
4863107
import logging import os import urllib import pathlib from io import BytesIO from django.core.files.base import ContentFile import cv2 from os import path import numpy as np from urllib import parse import urllib.request import certifi from PIL import Image from django.core.files.storage import get_storage_class fro...
4863125
def main(): stuff = [1, 5, "hello", 5, 12, 19, 12.5, [1, 2, 3]] write_contents(stuff) items = ["", 0, 1.1] for x in items: if isinstance(x, str): print("See? It's not used here so we don't have a type assertion") elif isinstance(x, int): print("This is very import...
4863168
import re from sympy.parsing.sympy_parser import (parse_expr, standard_transformations, convert_equals_signs) def simplify(condition, keys): keys.update({ "true": True, "false": False }) patterns = {key: (r"(?<...
4863177
from __future__ import annotations import os import uuid from abc import ABC from collections.abc import Mapping from dataclasses import dataclass from typing import Any import yaml from meerkat.tools.lazy_loader import LazyLoader import dcbench.constants as constants from dcbench.config import config from .artifac...
4863201
import os import csv #for headless display in python import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt #Load modules os.system("module load cmake/3.7.2 gcc/4.9.4") os.chdir("benchmark/cuda/stencil") os.system("rm *.dat") os.system("cmake -DHPX_ROOT=~/packagaes/hpx-4.9/ -DHPXCL_WITH_CUDA=ON -D...
4863207
import os import netifaces import psutil import subprocess import sys import re import config_parser from args_parser import parse_args from os.path import expanduser from tempfile import mktemp # 7-bit C1 ANSI sequences ansi_escape = re.compile(r''' \x1B # ESC [@-_] # 7-bit C1 Fe [0-?]* # Parameter...
4863208
from hc.accounts.models import Credential from hc.test import BaseTestCase class RemoveCredentialTestCase(BaseTestCase): def setUp(self): super().setUp() self.profile.totp = "0" * 32 self.profile.save() self.url = "/accounts/two_factor/totp/remove/" def test_it_requires_sudo...
4863223
import collections from types import SimpleNamespace def dict_to_simple_namespace(orig_dict, skip={}): def _dict_to_simple_namespace(d, path=""): res = {} for k, v in d.items(): cur_path = path + "." + k if skip.get(cur_path): res[k] = v elif is...
4863233
import pytest from qcodes.instrument.parameter import ArrayParameter from .conftest import blank_instruments, named_instrument class SimpleArrayParam(ArrayParameter): def __init__(self, return_val, *args, **kwargs): self._return_val = return_val self._get_count = 0 super().__init__(*args,...
4863266
import numpy as np from ._masker import Masker from .._serializable import Serializer, Deserializer class FixedComposite(Masker): """ A masker that outputs both the masked data and the original data as a pair. """ def __init__(self, masker): """ Creates a Composite masker from an underlying maske...
4863275
import datetime import time import functools from direct.distributed.DistributedObjectGlobalUD import DistributedObjectGlobalUD from direct.directnotify.DirectNotifyGlobal import directNotify class StatusDatabaseUD(DistributedObjectGlobalUD): notify = directNotify.newCategory('StatusDatabaseUD') def __init__(...
4863279
import time import torch import torchdata import torchfunc from .datasets import ExampleDataset, ExampleIterable from .utils import artificial_slowdown, enumerate_step, index_is_sample def test_basic_iterable(): dataset = ExampleIterable(0, 100).map(lambda value: value + 12) for index, item in enumerate(da...
4863313
from operator import itemgetter import matplotlib.pyplot as plt from sklearn.utils import validation def plot2d(model, x, y, figure, title=""): """ Projects the input data to two dimensions and plots it. The projection is done using the relevances of the given glvq model. Parameters ---------- ...
4863318
from typing import Any, Dict, List, Tuple, Union from peewee import Case import auth from api.socket.constants import GAME_NS from api.socket.groups import remove_group_if_empty from api.socket.shape.data_models import * from app import app, sio from models import ( AssetRect, Aura, Circle, CircularTo...
4863363
import upywraptest print(upywraptest.Int(0)) print(upywraptest.Int(True)) print(upywraptest.Int(False)) print(upywraptest.Int(2147483647)) print(upywraptest.Int(-2147483647)) print(upywraptest.Unsigned(0)) print(upywraptest.Unsigned(True)) print(upywraptest.Unsigned(False)) print(upywraptest.Unsigned(4294967295)) prin...
4863380
import PIL, os import sys from PIL import ImageDraw from PIL import ImageFont from papirus import Papirus BLACK = 0 WHITE = 1 font1 = ImageFont.truetype(os.path.expanduser('~/LightningATM/resources/fonts/FreeMono.ttf'), 18) font = ImageFont.truetype(os.path.expanduser('~/LightningATM/resources/fonts/Sawasdee-Bold.t...
4863399
from text_vectorian import SentencePieceVectorian import unittest from logging import getLogger import tensorflow as tf logger = getLogger(__name__) logger.setLevel('INFO') class SentencePieceVectorianTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.vectorian = SentencePieceVectorian() ...
4863406
a = range(255) n = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, ...
4863418
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math # Revolve imports from .util import ColorMixin from .. import constants from ....build.sdf import BodyPart from ....build.sdf import VelocityMotor from ....build.sdf import ComponentJoint as Joint ...
4863447
import numpy as np import preprocessing_functions as pf import config import warnings warnings.simplefilter(action='ignore') # ================================================ # TRAINING STEP - IMPORTANT TO PERPETUATE THE MODEL # Load data data = pf.load_data(config.PATH_TO_DATASET) # divide data set X_train, X_te...
4863484
from pytest import raises, yield_fixture as fixture from docopt_dispatch import Dispatch, DispatchError class OptionMarker(Exception): pass class ArgumentMarker(Exception): pass doc = 'usage: prog [--option] [<argument>]' @fixture def dispatch(): dispatch = Dispatch() @dispatch.on('--option') ...
4863503
from flask import Flask, render_template, request from tenseflow.database import db_session from tenseflow.models import Answer from tenseflow import change_tense app = Flask(__name__) @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove() @app.route('/', methods=['GET', 'POST']) ...
4863530
import os import sys import logging import inspect import fossor from fossor.engine import Fossor logging.basicConfig(stream=sys.stdout, level=logging.INFO) log = logging.getLogger(__name__) def test_no_popen_usage(): f = Fossor() for plugin in f.list_plugins(): for line in inspect.getsourcelines(p...
4863538
from django.conf import settings from django.test import TestCase from django.contrib.auth.models import User, SiteProfileNotAvailable class ProfileTestCase(TestCase): fixtures = ['authtestdata.json'] def setUp(self): """Backs up the AUTH_PROFILE_MODULE""" self.old_AUTH_PROFILE_MODULE = getattr...
4863562
import logging from dataclasses import dataclass from enum import IntEnum, Enum # from .catalog_structure import Catalogs, PublicDataServer # from .fitting_structure import BayesianDefault, MLEDefault # from .plotting_structure import GenericPlotting, ModelPlotting # from .plugin_structure import Plugins, TimeSeries ...
4863565
from tap_bigquery.sync_bigquery import _build_query as build_query def test_column_construction(): keys = { "table": "test.test.table", "columns": ["col0", "col1", "col2"], "datetime_key": "col0" } query = build_query(keys) expected = ( "SELECT col0,col1,col2 FROM test....
4863589
from __future__ import absolute_import, division, print_function from io import open import json from coreference_resolution import find_coreference_f1s def filter_with_coreference(partial_example, background, gold_answers, QA_history, history_len=2, match_metric='em', add_background=False, skip_entity=True): """...
4863595
from dataclasses import dataclass @dataclass(frozen=True) class AIResponse: """Represents an AI response returned from `get_ai_response` method. Attribues --------- message : str The main message. response : str An alias for message. response_time : str The re...
4863628
from torch.optim.lr_scheduler import _LRScheduler import numpy as np class OneCycleLR(_LRScheduler): """Sets the learning rate and momentum according to https://arxiv.org/abs/1803.09820 Args: optimizer (Optimizer): Wrapped optimizer. lrs (tuple): (start, middle, end) moms (tupl...
4863629
from unittest import TestCase import numpy as np import requests from PIL import Image from deepclustering.augment import TransformInterface from deepclustering.augment.sychronized_augment import SequentialWrapper URL = f"https://cdn1.medicalnewstoday.com/content/images/articles/322/322868/golden-retriever-puppy.jpg...
4863633
import collections.abc import functools import os import wx class KeyExistError(KeyError): def __init__(self, arg): self.arg = arg class BasicInfo(object): def __init__(self, name, val): self.name = name self._val = val def __str__(self): return f'Ke...
4863663
from __future__ import absolute_import, division, print_function from tests.core import mock from trakt import Trakt from httmock import HTTMock def test_delete(): with HTTMock(mock.list_delete, mock.unknown): with Trakt.configuration.auth('mock', 'mock'): success = Trakt['users/sean/lists/s...
4863675
from setuptools import setup, Extension import numpy as np SRC_DIR = "stl_tools" PACKAGES = [SRC_DIR] ext_1 = Extension(SRC_DIR + ".cwrapped", [SRC_DIR + "/cwrapped.c"], libraries=[], include_dirs=[np.get_include()]) EXTENSIONS = [ext_1] setup(name='stl_tools', ...
4863678
def main(): import meshpy.triangle as triangle import numpy as np points = [(1, 1), (-1, 1), (-1, -1), (1, -1)] for pt in np.random.randn(100, 2): points.append(pt * 0.1) def round_trip_connect(start, end): result = [] for i in range(start, end): result.append(...
4863698
from django.db import models from clist.templatetags.extras import slug from pyclist.models import BaseModel from true_coders.models import Coder class Chat(BaseModel): class ChatType(models.TextChoices): ROOM = 'ROOM', 'Room' PRIVATE = 'PRIV', 'Private' chat_type = models.CharField( ...
4863719
from __future__ import unicode_literals from ddt import data, ddt from django.test import TransactionTestCase from django.urls import reverse from mock_django import mock_signal_receiver from rest_framework import status, test from six.moves import mock from waldur_core.quotas.tests import factories as quota_factorie...
4863734
import argparse import collections import operator import sys import yaml from okonomiyaki.versions import EnpkgVersion from simplesat.constraints import InstallRequirement from simplesat.constraints.package_parser import constraints_to_pretty_strings from simplesat.constraints.kinds import ( Any, EnpkgUpstreamM...
4863742
import json import pytest from galaxy.unittest.mock import async_return_value @pytest.mark.asyncio async def test_chunked_messages(plugin, read): request = { "jsonrpc": "2.0", "method": "install_game", "params": { "game_id": "3" } } message = json.dumps(reque...
4863759
import inspect from typing import Any, Optional import aiohttp from aiohttp import ContentTypeError from pydantic import validate_arguments class GraphqlError(Exception): pass class ServerError(Exception): pass class ValidateMeta(type): """Metaclass that automatically wrap method with pydantic.valida...
4863791
from pandagg import Search from pandagg.mappings import Keyword, Text, Nested, Object, Integer from pandagg.tree.mappings import Mappings from pandagg.interactive._field_agg_factory import field_classes_per_name from pandagg.interactive.mappings import IMappings from tests.testing_samples.mapping_example import MAPPI...
4863814
import numpy as np a_2d = np.arange(6).reshape(2, 3) print(a_2d) # [[0 1 2] # [3 4 5]] a_2d_rot = np.rot90(a_2d) print(a_2d_rot) # [[2 5] # [1 4] # [0 3]] print(np.shares_memory(a_2d, a_2d_rot)) # True a_2d_rot[0, 0] = 100 print(a_2d_rot) # [[100 5] # [ 1 4] # [ 0 3]] print(a_2d) # [[ 0 1 100] # [...
4863841
import cv2 import numpy as np from lib.config import cfg from .chars_identify import chars_identify from .chars_segment import CharsSegment class CharsRecognize(object): def __init__(self): self.charsSegment = CharsSegment() def charsRecognize(self, plate, model_dir): chars = [] resu...