id
stringlengths
3
8
content
stringlengths
100
981k
9971143
from __future__ import absolute_import import operator from cytoolz.functoolz import curry, num_required_args, has_keywords def should_curry(f): num = num_required_args(f) return num is None or num > 1 or num == 1 and has_keywords(f) is not False locals().update( dict((name, curry(f) if should_curry(f...
9971149
from doppelkopf.events import Event, EventTypes from doppelkopf.db import db def test_save_event(app): start_game = Event(event_type=EventTypes.GAME_SINGLEPLAYER_WIN) db.session.add(start_game) db.session.commit() events = Event.query.all() assert events[0].event_type == EventTypes.GAME_SINGLEPL...
9971150
from jinja2 import Template from yaml import load from jnpr.junos import Device from jnpr.junos.utils.config import Config # template to configure junos f=open('configure_junos/remove_interface_description.j2') my_template = Template(f.read()) f.close() # get devices list. each item has an ip, name, username, passwor...
9971205
import voluptuous as vol import logging import yaml import sys import os _LOGGER = logging.getLogger(__name__) CONFIG_DIRECTORY = '.ledfx' CONFIG_FILE_NAME = 'config.yaml' DEFAULT_CONFIG = """ # Webserver setup host: 127.0.0.1 port: 8888 # Device setup # devices: # test_device_1: # type: e131 # name: Test...
9971236
import numpy as np from Network.PatchHandler3D import PatchHandler3D from Network.TrainerController import TrainerController def load_indexes(index_file): """ Load patch index file (csv). This is the file that is used to load the patches based on x,y,z index """ indexes = np.genfromtxt(index_file, ...
9971255
import time import pytest import numpy as np import pandas as pd from hyperactive import Hyperactive def objective_function_0(opt): score = -opt["x1"] * opt["x1"] return score search_space_0 = { "x1": list(np.arange(-5, 6, 1)), } search_space_1 = { "x1": list(np.arange(0, 6, 1)), } search_space_2 =...
9971293
import os.path as osp import torch import torch.nn.functional as F from torch.nn import Sequential, Linear, BatchNorm1d, ReLU from torch_geometric.datasets import TUDataset from torch_geometric.loader import DataLoader from torch_geometric.nn import GINConv, global_add_pool path = osp.join(osp.dirname(osp.realpath(__...
9971335
from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import with_metaclass import types from . import inputstream from . import tokenizer from . import treebuilders from .treebuilders._base import Marker from . import utils from . import constants from .constants import spaceChara...
9971380
import requests import opentracing class TracerHelper2(object): def __init__(self, tracer): self.tracer = tracer def inject_trace_headers(self, span, headers=None): text_carrier = {} self.tracer._tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, text_carrier) if hea...
9971424
import os import brotli from django.core.files.base import ContentFile from django.core.files.storage import get_storage_class from django.test import TestCase from django.test.utils import override_settings from django.utils.functional import LazyObject from compressor import storage from compressor.conf import sett...
9971427
from functools import partial from graphql.validation import KnownFragmentNamesRule from .harness import assert_validation_errors assert_errors = partial(assert_validation_errors, KnownFragmentNamesRule) assert_valid = partial(assert_errors, errors=[]) def describe_validate_known_fragment_names(): def known_f...
9971439
from __future__ import print_function from builtins import object from builtins import str from lib.common import helpers class Module(object): def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-MS16032', 'Author': ['@FuzzySec', '@leoloobeek'], ...
9971446
from mmdet.core.bbox import build_bbox_coder from .anchor_free_bbox_coder import AnchorFreeBBoxCoder from .centerpoint_bbox_coders import CenterPointBBoxCoder from .delta_xyzwhlr_bbox_coder import DeltaXYZWLHRBBoxCoder from .partial_bin_based_bbox_coder import PartialBinBasedBBoxCoder from .class_agnostic_bbox_coder im...
9971478
import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits import mplot3d def sliceplot_pred_mean(var1,var2,GP_model,x_star_): D = 6 var_bounds = GP_model.bounds def create_grid(*args): for i in range(0,D-1): grid1 = args[i] grid2 = args[i+1] ...
9971484
from __future__ import annotations import struct import enum import io import os from PIL import Image, ImageFont, ImageDraw from .util import printf, readStruct, writeStruct, BAD_DIR_CHARS from .LangEnum import LangEnum, LangCodes from texconv.sfatexture import SfaTexture, TexFmt, ImageFormat from texconv.texture impo...
9971594
from typing import Dict, Any from pathlib import Path import json from spectacles.types import JsonDict def load_resource(filename) -> JsonDict: """Helper method to load a JSON file from tests/resources and parse it.""" path = Path(__file__).parent / "resources" / filename with path.open() as file: ...
9971685
from . import SentenceEvaluator, SimilarityFunction import logging import os import csv from sklearn.metrics.pairwise import paired_cosine_distances, paired_euclidean_distances, paired_manhattan_distances from typing import List from ..readers import InputExample logger = logging.getLogger(__name__) class TripletEv...
9971694
from colorlog import ColoredFormatter import colorlog import logging import logging.config import os import os.path as osp _color_formatter = ColoredFormatter( "%(log_color)s[%(filename)s:%(lineno)3s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", reset=True, log_colors={ 'DEBUG': 'cyan', ...
9971706
from nose.tools import raises from basehash import base56 bh56 = base56() bh6 = base56(6) bh10 = base56(10) def test_base56_encode_with_1234567890_4FXvzC(): assert bh56.encode(1234567890) == '4FXvzC' def test_base56_decode_with_4FXvzC_1234567890(): assert bh56.decode('4FXvzC') == 1234567890 def test_ba...
9971720
import os import glob import copy import six import inspect import importlib import contextlib import weakref from collections import OrderedDict from yggdrasil.doctools import docs2args _registry = {} _registry_complete = False class ComponentError(BaseException): r"""Error raised when there is a problem impor...
9971724
from torch2trt_dynamic.torch2trt_dynamic import * from torch2trt_dynamic.plugins import * @tensorrt_converter('torch.Tensor.repeat') def convert_repeat(ctx): input = ctx.method_args[0] shape = ctx.method_args[1] if isinstance(shape, int): shape = ctx.method_args[1:] input_trt = trt...
9971734
try: import mock except ModuleNotFoundError: from unittest import mock import pytest import pyshark @pytest.yield_fixture(params=[["wlan0"], ["wlan0mon", "wlan1mon"]]) def interfaces(request): with mock.patch("pyshark.tshark.tshark.get_tshark_interfaces", return_value=request.param): yield reques...
9971736
from datetime import timedelta from typing import Optional from google.protobuf.duration_pb2 import Duration from feast.protos.feast.core.Aggregation_pb2 import Aggregation as AggregationProto class Aggregation: """ NOTE: Feast-handled aggregations are not yet supported. This class provides a way to registe...
9971752
import random from tfne.encodings.codeepneat import CoDeepNEATBlueprint from tfne.helper_functions import round_with_step class CoDeepNEATInitialization: def _create_initial_blueprint(self, initial_node_species) -> (int, CoDeepNEATBlueprint): """""" # Create the dict that keeps track of the way a...
9971765
from manimlib.imports import * class MoveAlongPath1(Scene): def construct(self): circle = Circle(radius=4) square = Square() square.move_to(2 * RIGHT) self.add(square) self.add(circle) self.play(MoveAlongPath(square, circle), run_time=5.0) self.play(MoveAlon...
9971775
from termpixels import App from termpixels.util import wrap_text class TestApp(App): def __init__(self, text=""): super().__init__() self.text = text def on_frame(self): self.screen.clear() self.screen.print(wrap_text(self.text, self.screen.w), 0, 0) self.screen.update(...
9971783
from random import shuffle import tensorflow as tf import numpy as np import os from layers.graph_layer import chebyshev_polynomial_layer from layers.anisotropic_graph_layer import ga_graph_layer from layers.cubic_anisotropic_graph_layer import ga_cubic_graph_layer from helper.helper import get_matrix_of_...
9971809
src = Split(''' main.c version.c ''') component = aos_component('framework', src) CONFIG_SYSINFO_APP_VERSION = 'app-1.0.0-'+aos_global_config.current_time print( 'app_version:', CONFIG_SYSINFO_APP_VERSION) macro_tmp = Split(''' AOS_FRAMEWORK_COMMON ''') macro_tmp.append( 'SYSINFO_APP_VERSION=...
9971825
from kubernetes import client def template(context): return client.V1Service( api_version="v1", kind="Service", metadata=client.V1ObjectMeta(name=context["name"]), spec=client.V1ServiceSpec( type="NodePort", ports=[ {"port": context["external...
9971828
import unittest from orm.render import ORMInternalRenderException from orm.renderhaproxy import RenderHAProxy import orm.renderhaproxy as renderhaproxy class RenderHAProxyTest(unittest.TestCase): def assertIsStringList(self, lst, emptyOk=True): self.assertIsInstance(lst, list) for elem in lst: ...
9971843
import re import nltk import pandas as pd import numpy as np from bs4 import BeautifulSoup from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer from multiprocessing import Pool class KaggleWord2VecUtility(object): @staticmethod def review_to_wordlist(review, remove_stopwords=Fal...
9971847
from unittesting import DeferrableTestCase class TestExplicitDoCleanups(DeferrableTestCase): def test_manually_calling_do_cleanups_works(self): messages = [] def work(message): messages.append(message) self.addCleanup(work, 1) yield from self.doCleanups() se...
9971853
import torch.nn as nn from torch.nn import functional as F import math import torch.utils.model_zoo as model_zoo import torch import numpy as np from torch.utils.model_zoo import load_url from torch.autograd import Variable import sys, os from ..nn import AttentionGraphCondKernel from encoding.nn import BatchNorm2d mo...
9971866
class Dialog(object): """ The dialog class is used to declare the information passed to the user and retrieved from the user during an interaction. """ components = () """ Components to display in the given order in the dialog """ title = None """ Title of the dialog """ reason = ...
9971874
import numpy as np from django.conf import settings from images.models import Point from labels.models import Label, LocalLabel from .models import Score def acc(gt, est): """ Calculate the accuracy of (agreement between) two interger valued list. """ if len(gt) < 1: return 1 else: ...
9971883
from django.core.management.base import CommandError, BaseCommand from devilry.apps.core.models import Subject, Period from devilry.devilry_account.models import PermissionGroup class Command(BaseCommand): help = 'Clear period admins (removes the syncsystem permission group ' \ 'for the period).' ...
9971891
import random def get_random_crop_params(orig_size, target_size): """Gets bounding box parameters for a random crop Parameters ---------- orig_size : int or tuple Size of image in the form of (width, height) target_size : int or tuple Size of random crop in the form of (width, height) Returns ...
9971892
THOST_FTDC_EXP_Normal = '0' THOST_FTDC_EXP_GenOrderByTrade = '1' THOST_FTDC_ICT_EID = '0' THOST_FTDC_ICT_IDCard = '1' THOST_FTDC_ICT_OfficerIDCard = '2' THOST_FTDC_ICT_PoliceIDCard = '3' THOST_FTDC_ICT_SoldierIDCard = '4' THOST_FTDC_ICT_HouseholdRegister = '5' THOST_FTDC_ICT_Passport = '6' THOST_FTDC_ICT_TaiwanCompatri...
9971893
from datetime import datetime, timedelta, timezone from signal_ocean.historical_tonnage_list import ( Vessel, Area, LocationTaxonomy, MarketDeployment, PushType, CommercialStatus, VesselSubclass, ) def create_vessel( imo=123, name="name", vessel_class="Aframax", ice_class=...
9971942
import logging import six import requests from django.conf import settings from django.core.cache import caches logger = logging.getLogger(__name__) cache = caches['regs_gov_cache'] def fetch(url, **kwargs): kwargs['headers'] = kwargs.get( 'headers', {'X-Api-Key': settings.REGS_GOV_API_KEY}) kwarg...
9971957
from functools import reduce import operator def get_from_dict(data, keys): try: return reduce(operator.getitem, keys, data) except: return None def get_from_path(data, path, sep='.'): return get_from_dict(data, path.split(sep)) def compare_two_lists(list1: list, list2: list) -> bool: ...
9971972
import sys, os file_path = os.path.abspath(__file__) project_path = os.path.dirname(os.path.dirname(file_path)) sys.path.append(project_path) fcgf_path = os.path.join(project_path, 'ext', 'FCGF') sys.path.append(fcgf_path) from dataset.threedmatch_train import Dataset3DMatchTrain from perception3d.adaptor import Dat...
9971978
from django.conf.urls import patterns, include, url from django.contrib.auth.decorators import login_required from apps.web import views partials_patterns = patterns( '', url(r'^_competitions_managed$', login_required(views.MyCompetitionsManagedPartial.as_view()), name='my_competitions_managed...
9971980
import mock from commands import preparebluegreen, swapbluegreen, purgebluegreen from commands import createinstance from commands import updateautoscaling from tests.helpers import get_test_application @mock.patch('commands.preparebluegreen.ghost_has_blue_green_enabled') def test_command_prepare_bg_available(ghost...
9971988
import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange, repeat from einops.layers.torch import Rearrange from ..registry import register_model __all__ = ["cvt"] def group_dict_by_key(cond, d): return_val = [dict(), dict()] for key in d.keys(): match = ...
9971992
import torch import torch.nn as nn from transformers import BertModel from config import * import numpy as np class BertClassifier(nn.Module): def __init__(self, freeze_bert=False): super(BertClassifier, self).__init__() D_in, H, D_out = 768, HIDDEN_DIM, 2 # Instantiate BERT model ...
9972064
import pandas as pd from matplotlib import pylab as plt import matplotlib.dates as mdates def figure_plotting_space(): """ defines the plotting space """ fig = plt.figure(figsize=(10,10)) bar_height = 0.04 mini_gap = 0.03 gap = 0.05 graph_height = 0.24 axH = fig.add_axes([0.1,ga...
9972069
import os from os.path import join as path_join from configurations import Configuration, values from django.contrib import messages from django.core.exceptions import ImproperlyConfigured BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def is_in_docker() -> bool: return os.getenv('IN_DOCK...
9972103
import torch import torch.nn.functional as F from .tensorlist import tensor_operation @tensor_operation def conv2d(input: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor = None, stride=1, padding=0, dilation=1, groups=1, mode=None): ...
9972106
import traceback from abc import ABC, abstractmethod from concurrent.futures.thread import ThreadPoolExecutor from datetime import datetime from threading import Event, Thread, get_ident from time import sleep from unittest.case import TestCase from uuid import uuid4 from eventsourcing.persistence import StoredEvent ...
9972153
import argparse import json import numpy as np from tqdm import tqdm if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('wordvec') vecfile = parser.parse_args().wordvec wordvecdict = {} print('read word vectors...') with open(vecfile) as f: f.readline() ...
9972180
import os import lightly.loss as loss import lightly.models as models import pytorch_lightning as pl import torch import torchvision from PIL import ImageFile from data.data_ukb import get_imaging_pretraining_data torch.multiprocessing.set_sharing_strategy("file_system") os.environ["CUDA_VISIBLE_DEVICES"] = "4" Imag...
9972187
import scipy.optimize as opt import numpy as np from cbsyst.helpers import ch, noms, cast_array, maxL, calc_pH_scales, Bunch, cp # from cbsyst.boron_fns import cBO4 def _zero_wrapper(ps, fn, bounds=(10 ** -14, 10 ** -1)): """ Wrapper to handle zero finders. """ try: return opt.brentq(fn, *bou...
9972212
from datetime import timedelta from typing import Any, List, Optional, Union from django.conf import settings from django.test.signals import setting_changed from ninja_extra.lazy import LazyStrImport from ninja_schema import Schema from pydantic import AnyUrl, Field, root_validator class NinjaJWTUserDefin...
9972255
import argparse import os import cv2 import rasterio import shapely import skimage import numpy as np from skimage import measure from skimage.morphology import watershed import pandas as pd from tqdm import tqdm import rasterio.features import shapely.wkt import shapely.ops import shapely.geometry parser = argparse...
9972313
import json import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from modules.word_embedding import WordEmbedding from modules.aggregator_predict import AggPredictor from modules.selection_predict import SelPredictor from modules.sqlnet_condition_pred...
9972334
import requests # Replace with your job download_url download_url = '' def connect_to_endpoint(url): response = requests.request("GET", url) print(response.status_code) if response.status_code != 200: raise Exception(response.status_code, response.text) return response.text def main(): ...
9972335
import json from textwrap import dedent class TestRemoveHostInterface: def test_invalid_host(self, host): result = host.run('stack remove host interface test') assert result.rc == 255 assert result.stderr == 'error - cannot resolve host "test"\n' def test_no_args(self, host): result = host.run('stack remov...
9972353
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class Nvgre(Base): __slots__ = () _SDM_NAME = 'nvgre' _SDM_ATT_MAP = { 'ChecksumPresent': 'nvgre.header.checksumPresent-1', 'Reserved1': 'nvgre.header.reserved1-2', 'KeyPresent': 'nvgre.header.keyPresen...
9972377
import sys import compileall import importlib.util import os import pathlib import py_compile import shutil import struct import tempfile import time import unittest import io from test import support, script_helper class CompileallTests(unittest.TestCase): def setUp(self): self.directory = tempfile.mkdt...
9972378
from .GameRecord import GameRecord __all__ = ["GameAnalytics"] class GameAnalytics: """ This is intended as a base class for more detailed analytics, depending on what kinds of interesting information a rating system can provide. """ skipped: bool game: GameRecord def __init__(self, ski...
9972395
import numpy import sodecl import pickle import matplotlib.pyplot as plt if __name__ == '__main__': openclplatform = 0 opencldevice = 0 openclkernel = 'oculomotor.cl' solver = 2 dt = 1e-6 tspan = 0.1 ksteps = 400 localgroupsize = 0 orbits = 2 nequat = 6 nparams = 6 nno...
9972399
from flask import Blueprint eventFramesOverlay = Blueprint("eventFramesOverlay", __name__) from . import routes
9972452
import threading class MyThread(threading.Thread): def run(self): pass threads = [MyThread() for i in range(3)] for t in threads: t.start() for t in threads: t.join() print('TEST SUCEEDED!') # Break here
9972454
import argparse import torch def main(): parser = argparse.ArgumentParser() parser.add_argument("-model_file", help="Path to your model", type=str, default='') parser.add_argument("-output_name", type=str, default='out_stripped.pth') parser.add_argument("-delete_branches", action='store_true') par...
9972491
import numpy as np from TrainingController import TrainingController class NaNBreaker(TrainingController): def __init__(self): pass def after_training_iteration(self, trainer): '''If training error improves by less than min_improvement, then stop''' if np.isnan(trainer.get_training_lo...
9972533
from functools import partial from typing import List, Tuple import haiku as hk import jax import jax.numpy as jnp import numpy as np from jax.experimental import optix from rljax.algorithm.base_class import OffPolicyActorCritic from rljax.network import ContinuousQFunction, StateDependentGaussianPolicy from rljax.ut...
9972543
import logging from indra.ontology.standardize \ import standardize_agent_name from .gilda import ground_agent logger = logging.getLogger(__name__) # If the adeft disambiguator is installed, load adeft models to # disambiguate acronyms and shortforms try: from adeft import available_shortforms as available_a...
9972555
import torch import torch.nn as nn import torch.nn.functional as F from torchelie.utils import kaiming, experimental class MaskedConv2d(nn.Conv2d): """ A masked 2D convolution for PixelCNN Args: in_chan (int): number of input channels out_chan (int): number of output channels ks ...
9972561
import torch # Convert annotation mask to one hot encoding def LabelConvert(label,NumClasses=2): label = torch.from_numpy(label).cuda() # create one-hot encoding batchsize, h, w= label.size() target = torch.zeros(batchsize,NumClasses, h, w).cuda() for c in range(NumClasses): for b in range(ba...
9972595
from dataclasses import dataclass import dataclass_factory @dataclass class Book: title: str price: int author: str = "Unknown author" data = { "title": "Fahrenheit 451" } factory = dataclass_factory.Factory() try: book: Book = factory.load(data, Book) except dataclass_factory.PARSER_EXCEPTIO...
9972646
import asyncio import pytest from asgiref.sync import async_to_sync from channels import DEFAULT_CHANNEL_LAYER from channels.db import database_sync_to_async from channels.layers import channel_layers from channels.testing import WebsocketCommunicator from django.contrib.auth import user_logged_in, get_user_model from...
9972678
from __future__ import annotations from typing import Callable, Any, TYPE_CHECKING, Optional from threading import Thread import os import time import psutil # type: ignore import logging if TYPE_CHECKING: from .layout import Layout logger = logging.getLogger(__name__) class SysBackendEndpoint: def __init__...
9972683
WORD = 4 DOUBLE_WORD = 8 # the number of registers that we need to save around malloc calls N_REGISTERS_SAVED_BY_MALLOC = 9 # the offset from the FP where the list of the registers mentioned above starts MY_COPY_OF_REGS = WORD # The Address in the PC points two words befind the current instruction PC_OFFSET = 8 FORCE_...
9972689
import sys match sys.platform: case "windows": print("Running on Windows") case "darwin" : print("Running on macOS") case "linux": print("Running on Linux") case _: raise NotImplementedError(f"{sys.platform} not supported!")
9972698
from setuptools import setup setup( name='youku', version='0.1.1', description='Youku open api python client and video uploader', long_description='Youku open api python client,' ' support video upload and other api, do not support video download.', url='https://github.com/hanguokai/youku', ...
9972702
from __future__ import absolute_import, unicode_literals import os from sys import stderr from typing import List import hh_paths from common_tests import CommonTestDriver from test_case import TestCase class ExtractStandaloneDriver(CommonTestDriver): UPDATE_TESTS = False error_file_ext = ".err" auto_...
9972754
import os import copy import inspect from typing import List from dataclasses import dataclass from pygears.conf import PluginBase, reg from pygears.core.graph import has_async_producer from traceback import walk_stack from .intf import Intf from .port import InPort, OutPort, HDLConsumer, HDLProducer from .hier_node i...
9972759
import sys import os import re import math unix50_dir = sys.argv[1] intermediaries_dir = sys.argv[2] maximum_input_size = int(sys.argv[3]) print("Preparing unix50 scripts...") def convert_size(size_bytes): if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") ...
9972769
import pytest import vcr from app.factories.virustotal import VirusTotalVerdict, VirusTotalVerdictFactory @vcr.use_cassette( "tests/fixtures/vcr_cassettes/vt.yaml", filter_headers=["x-apikey"], ) @pytest.mark.asyncio async def test_virustotal(): # eicar file verdict = await VirusTotalVerdictFactory.f...
9972777
import pytest import pyogg from config import Config def test_error_in_filename() -> None: # Load a non-existant file filename = "does-not-exist.flac" with pytest.raises(pyogg.PyOggError): flac_stream = pyogg.FlacFileStream(filename) def test_total_length(pyogg_config: Config) -> None: ...
9972783
import logging from time import ( sleep, time, ) from RestrictedPython import RestrictionCapableEval from pytest_play.providers import BaseProvider logger = logging.getLogger(__name__) class TimeoutException(Exception): """ Timeout exception """ class PythonProvider(BaseProvider): """ Python comma...
9972786
def write_file(): try: with open("output.txt", "w") as out: out.write("Hi! I'm a line of text in this file!\n") out.write("Me, too!\n") except OSError as e: print(f"Cannot open file: {e}") return def read_file(): try: with open("output.txt", "r") as ...
9972829
from CoreFoundation import * from PyObjCTools.TestSupport import * try: long except NameError: long = int class TestCFBinaryHeap (TestCase): def testTypes(self): self.assertIsCFType(CFBinaryHeapRef) def testCreation(self): heap = CFBinaryHeapCreate( None, 0) ...
9972847
import csv import sys import os.path import json # 清洗数据,去除重复记录。 def washdata(): """清洗数据,去除重复记录。 """ CUR_PATH = sys.path[0] if CUR_PATH == '': CUR_PATH = os.getcwd() DATAPATH = os.path.join(os.path.dirname(CUR_PATH), 'datafile') # 此脚本文件上一级路径中的datafile文件夹 DATA_TABLEHEADER = ['user_url_to...
9972864
from tqdm import tqdm import numpy as np from imutils import face_utils import dlib from collections import OrderedDict import cv2 from calib_utils import track_bidirectional detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") FACIAL_LANDMARKS_68_IDXS =...
9972865
from typing import Dict, List, Text import pytest import rasa.nlu.utils.pattern_utils as pattern_utils from rasa.shared.nlu.training_data.training_data import TrainingData from rasa.shared.nlu.training_data.message import Message @pytest.mark.parametrize( "lookup_tables, regex_features, expected_patterns", ...
9972904
from xoto3.dynamodb.stringset import stringset_contains def test_stringset_contains(): q_w_filter = dict(FilterExpression="does some stuff") tag_set = {"a", "b"} new_query = stringset_contains("tags", tag_set)(q_w_filter) assert new_query == dict( FilterExpression="does some stuff ( contains...
9972978
import time from aggregate_stats import AggregateStats class DataPoint: def __init__(self, algorithm_name, key_size, requested_bit_error_rate, code_version): self.execution_time = time.strftime('%Y-%m-%d %H:%M:%S %Z') self.algorithm_name = algorithm_name self.key_size = key_size s...
9972981
import unittest import pandas as pd import numpy as np import periodictable as pt from earthchem.geochem import to_weight, to_molecular, common_elements, \ REE class TestWeightMolarReversal(unittest.TestCase): """Tests the reversability of weight-molar unit transformations.""" d...
9972997
from os import path import pytest from autoconf import conf from autolens.interferometer.model.visualizer import VisualizerInterferometer directory = path.dirname(path.realpath(__file__)) @pytest.fixture(name="plot_path") def make_visualizer_plotter_setup(): return path.join("{}".format(directory), "...
9973019
import tensorflow as tf from tensorflow.keras import layers import os import numpy as np os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' # metrics setting g_loss_metrics = tf.metrics.Mean(name='g_loss') d_loss_metrics = tf.metrics.Mean(name='d_loss') total_loss_metrics = tf.metrics.Mean(name='total_loss') # hyper-param...
9973042
import unittest import random, sys, time, re sys.path.extend(['.','..','py']) DO_GLM = True PARSE_ITERATIONS = 1 import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i, h2o_glm, h2o_util, h2o_rf, h2o_jobs as h2j import h2o_common, h2o_gbm class releaseTest(h2o_common.ReleaseCommon, unittest.TestCase): def te...
9973043
from django import forms from django.conf import settings from django.utils.timezone import now from django.utils.translation import ugettext as _ from daiquiri.core.utils import get_detail_fields from .models import Participant, Contribution class ParticipantForm(forms.ModelForm): class Meta: model = ...
9973048
import argparse import os import sys from paraview.simple import * from paraview import coprocessing def ExtendDefaultPipeline(renderview, coprocessor, datadescription, script_args): parser = argparse.ArgumentParser(description='BDM-PV-Params') parser.add_argument('--raytracing', action='store_true') parse...
9973052
from scrapy import Spider from scrapy.http import Request from firmware.items import FirmwareImage from firmware.loader import FirmwareLoader import json class BuffaloSpider(Spider): name = "buffalo" allowed_domains = ["buffalotech.com", "cdn.cloudfiles.mosso.com"] start_urls = ["http://www.buffalotech.c...
9973054
import json import sys import os def get_api_key(): try: with open("local.settings.json", "r") as settings: return json.loads(settings.read())["key1"] except FileNotFoundError: raise FileNotFoundError( "You may not have created a `local.settings.json` file. See LAB_SETU...
9973059
import sys import unittest import pytest from pycid.core.cpd import DecisionDomain from pycid.core.macid_base import MechanismGraph from pycid.core.relevance_graph import CondensedRelevanceGraph, RelevanceGraph from pycid.examples.simple_cids import get_3node_cid, get_5node_cid, get_minimal_cid from pycid.examples.st...
9973123
from dummy import Hyper, Param, Var, Runtime, Input, Output, Inline #### Parameters to the model (changes in this block should not require #### any changes in the actual model) maxInt = Hyper() inputNum = Hyper() inputStackSize = Hyper() prefixLength = Hyper() lambdaLength = Hyper() suffixLength = Hyper() #### Inputs...
9973147
import numpy as np import matplotlib.pyplot as plt import scipy.io as spio from mayavi import mlab import pdb deg_to_rad = np.pi/180. rad_to_deg = 180./np.pi class OTA(object): """ Over The Air Simulator config = 0 : spherical distribution of probes """ def __init__(self,**kwargs): typ = kwar...