id
stringlengths
3
8
content
stringlengths
100
981k
1605354
from __future__ import absolute_import #!/usr/bin/env python import sys import unittest sys.path.append('xypath') import xypath import messytables try: import hamcrest except ImportError: hamcrest = None import re import tcore class Test_Import_Missing(tcore.TMissing): def test_table_has_properties_at_all(...
1605368
import numpy as np import scipy.sparse as sp from pySDC.implementations.problem_classes.boussinesq_helpers.build2DFDMatrix import get2DMatrix, getBCHorizontal, \ get2DUpwindMatrix def getBoussinesq2DUpwindMatrix(N, dx, u_adv, order): Dx = get2DUpwindMatrix(N, dx, order) # Note: In the equations it is u_...
1605381
import re from fontTools.agl import AGL2UV import defcon from . import registry from .wrappers import * # Unicode Value uniNamePattern = re.compile( "uni" "([0-9A-Fa-f]{4})" "$" ) def testUnicodeValue(glyph): """ A Unicode value should appear only once per font. """ font = wrapFont(glyph....
1605395
import os from typing import List from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from service.github_service import get_contributors from service.stats_service import compute_stat, get_stats, get_stats_summary from service.twitch_service import TwitchService from view_model.stats_viewmo...
1605424
from datetime import datetime from peewee import SqliteDatabase, CharField, DateTimeField, Model db = SqliteDatabase("clipboard.db") class Paste(Model): text = CharField() date = DateTimeField() class Meta: database = db db.create_tables([Paste]) def save_new_paste(text): paste = Paste(t...
1605449
from pandas import DataFrame import pandas as pd # 첫번째 데이터프레임 data = { '종가': [113000, 111500], '거래량': [555850, 282163] } index = ['2019-06-21', '2019-06-20'] df1 = DataFrame(data=data, index=index) # 두번째 데이터프레임 data = { '시가': [112500, 110000], '고가': [115000, 112000], '저가': [111500, 109000]...
1605450
class ConfigError(Exception): """ This is an exception thrown whenever there's something wrong with the Raven configuration, from the perspective of RavenPy. """ pass
1605475
from setuptools import setup setup(name='fmq', version='0.1', description='Fast MP Queue, Feed Me Queue', url='https://github.com/weitang114/FMQ', author='<NAME>', author_email='<EMAIL>', license='MIT', packages=['fmq'], zip_safe=False)
1605539
from __future__ import print_function try: from SimpleHTTPServer import SimpleHTTPRequestHandler except ImportError: from http.server import SimpleHTTPRequestHandler try: import SocketServer as socketserver except ImportError: import socketserver import logging import cgi PORT = 8080 class ServerH...
1605542
import json from collections import defaultdict import numpy as np import tensorflow as tf from matplotlib import pyplot as plt, patches from dataset_utils.kitti_datum import KITTIDataset from dataset_utils.mot_datum import MOTDataset from trainer.dataset_info import kitti_classes_reverse from vis_utils.vis_datum imp...
1605577
import pytest from pandagg.document import DocumentSource from pandagg.node.mappings import Text, Keyword from pandagg.utils import equal_queries, equal_search, is_subset, get_action_modifier def test_equal(): q1 = {"bool": {"must": [{"term": {"field_A": 1}}, {"term": {"field_B": 2}}]}} q2 = {"bool": {"must"...
1605634
from django.test import TestCase from django.contrib.auth import get_user_model from django.test import Client from suite.views import ClubEmails from django.urls import reverse from suite.models import Club class View_ClubEmails_TestCase(TestCase): def setUp(self): self.client = Client() #create...
1605642
from collections import namedtuple ''' A datatype defining either an array of qubits or classical bits. These are defined in-program using the following syntax: (def blocka 1 2) # A two-qubit block using qubits one and two (def blockb 1 3) # Qubits 1-3 (def blockc 1 2 classical) # Classical two-bit block f...
1605681
from dataclasses import dataclass from typing import Any, List @dataclass class TaskUnit: request: Any def run(self, extractor): yield extractor.run(self) @dataclass class MultiTaskUnit(TaskUnit): request: Any def run(self, extractor): return extractor.run_multiple(self) @dataclass...
1605686
from .config import * def test_getClashTournaments(): try: data = loop.run_until_complete(panth.getClashTournaments()) except Exception as e: print(e) assert type(data) == list if len(data) > 0: assert "id" in data[0] assert "themeId" in data[0] assert "sche...
1605698
from tensorflow.python.ops import nn_ops, gen_nn_ops import tensorflow as tf class MNIST_NN: def __init__(self, name): self.name = name def __call__(self, X, reuse=False): with tf.variable_scope(self.name) as scope: if reuse: scope.reuse_variables() ...
1605766
from django.core.management.base import BaseCommand, CommandError import snippets.contact.fixtures as contact_fixtures ''' Loads service_page fixtures into your joplin environment. Run with: pipenv run python joplin/manage.py load_test_contacts ''' class Command(BaseCommand): help = "Loads test data f...
1605767
n = int(input()) assert (n >= 0 and n <= 10 ^ 7), "n should be in range 0 ≤ n ≤ 10^7 " def fib(n): a = 0 b = 1 for i in range(n): a, b = b, a + b return a print fib(n)
1605782
import pickle from collections import deque, defaultdict from numbers import Number from time import perf_counter from typing import Dict, Text, List import numpy as np from prl.utils.misc import colors DEQUE_MAX_LEN = 10 ** 6 def limited_deque(): """Auxiliary function for Logger class. Returns: Deque wit...
1605810
import pytest import torch from torch_geometric.nn import GraphConv, GroupAddRev, SAGEConv from torch_geometric.nn.dense.linear import Linear @pytest.mark.parametrize('num_groups', [2, 4, 8, 16]) def test_revgnn_forward_inverse(num_groups): x = torch.randn(4, 32) edge_index = torch.tensor([[0, 1, 2, 3], [0, ...
1605850
import click from virl.api import VIRLServer from subprocess import call from virl import helpers from virl.helpers import get_mgmt_lxc_ip, get_node_from_roster, get_cml_client, get_current_lab, safe_join_existing_lab, get_node_mgmt_ip from virl2_client.exceptions import NodeNotFound @click.command() @click.argument(...
1605862
from yacs.config import CfgNode as CN # ----------------------------------------------------------------------------- # Convention about Training / Test specific parameters # ----------------------------------------------------------------------------- # Whenever an argument can be either used for training or for test...
1605922
import tarfile from metaflow import S3 with S3() as s3: res = s3.get('s3://fast-ai-nlp/yelp_review_full_csv.tgz') with tarfile.open(res.path) as tar: datafile = tar.extractfile('yelp_review_full_csv/train.csv') reviews = [line.decode('utf-8') for line in datafile] print('\n'.join(reviews[:2]))...
1605930
import argparse import os import re import time import numpy as np from time import sleep from datasets import audio import tensorflow as tf from hparams import hparams, hparams_debug_string from infolog import log from tacotron.synthesizer import Synthesizer from tqdm import tqdm def generate_fast(model, text): mod...
1605959
from distutils.core import setup, Extension import os import numpy H2PACK_DIR = ".." extra_cflags = ["-I"+H2PACK_DIR+"/include"] extra_cflags += ["-g", "-std=gnu99", "-O3"] extra_cflags += ["-DUSE_MKL", "-qopenmp", "-xHost", "-mkl"] LIB = [H2PACK_DIR+"/lib/libH2Pack.a"] extra_lflags = LIB + ["-g", "-O3", "-qopenmp"...
1605996
from typing import ( Union, ) from .abc import ( BackendAPI, PreImageAPI, ) class Keccak256: def __init__(self, backend: BackendAPI) -> None: self._backend = backend self.hasher = self._hasher_first_run self.preimage = self._preimage_first_run def _hasher_first_run(self, ...
1605999
import argparse import logging from enum import Enum from stix2patterns_translator.parser import generate_query from stix2patterns_translator import data_models from stix2patterns_translator import search_platforms logger = logging.getLogger(__name__) class SearchPlatforms(Enum): ELASTIC = 'elastic' SPLUNK = ...
1606008
import pytest from kiez.evaluate import hits @pytest.mark.parametrize( "nn_ind, gold, k, expected", [ ( [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]], {0: 2, 1: 4, 2: 3, 3: 4}, [1, 2, 3], {1: 0.5, 2: 0.75, 3: 1.0}, ), ( [[1, 2,...
1606033
import math import torch import torch.nn as nn from src.model.nets.base_net import BaseNet class EDSRNet(BaseNet): """The implementation of Enhanced Deep Residual Networks (ref: https://arxiv.org/pdf/1707.02921.pdf). Args: in_channels (int): The input channels. out_channels (int): The output...
1606067
from django.views.generic import CreateView from .forms import SampleModelForm from .models import SampleModel class SampleModelCreate(CreateView): model = SampleModel form_class = SampleModelForm
1606075
import argparse import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import scipy as sp import scipy.stats import pyemma from pyemma.util.contexts import settings import MDAnalysis as mda # My own functions from pensa import * def workflow_torsions_jsd(args, feat_a, feat_b, data_a, data_b, to...
1606076
class Error(Exception): """Base class for exceptions in this module""" pass class InvalidTransactionError(Error): pass class InvalidConnectorError(Error): pass class InvalidCertificateError(Error): pass
1606146
import math from pyblox.math.facing import Facing from pyblox.math.vector2 import Vector2 class Vector3: def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z def get_x(self): return self.x def get_y(self): return self.y def get_z(self): ...
1606154
from scene import * import math class MyScene (Scene): def __init__(self): Scene.__init__(self) self.distance_old = 0.0 self.distance_new = 0.0 self.reset = True self.zoom = 0 def draw (self): background(0, 0, 0) locations = [[0,0],[0,0]] ...
1606222
from unittest import TestCase, skip from pykeg.core import testutils from . import client import requests import requests_mock vcr = testutils.get_vcr("contrib/twitter") FAKE_API_KEY = "<KEY>" FAKE_API_SECRET = "<KEY>" FAKE_REQUEST_TOKEN = "<KEY>" FAKE_REQUEST_TOKEN_SECRET = "<KEY>" FAKE_AUTH_URL = "https://api.twi...
1606229
import numpy as np from scipy.linalg import solveh_banded def als_baseline(intensities, asymmetry_param=0.05, smoothness_param=1e6, max_iters=10, conv_thresh=1e-5, verbose=False): '''Computes the asymmetric least squares baseline. * http://www.science.uva.nl/~hboelens/publications/draftpub/Eilers...
1606240
import unittest from src import inetaccess class ScanDataTest(unittest.TestCase): def test_no_response(self): expected_results = { "result_score": "0.0", "scan_data": [ { "fqdn": "testing.notworking.com.co", "domain": "notwor...
1606248
import hashlib from django.conf import settings from blocktools import * from gcoin.transaction import serialize MAGIC = MAGIC_NUMBER[settings.NET] SKIP_LIMIT = 100 class BlockHeader: def __init__(self, blockchain): self.version = uint4(blockchain) self.previousHash = hash32(blockchain) ...
1606258
from .linked_data_proof import LinkedDataProof from .linked_data_signature import LinkedDataSignature from .jws_linked_data_signature import JwsLinkedDataSignature from .ed25519_signature_2018 import Ed25519Signature2018 from .bbs_bls_signature_2020 import BbsBlsSignature2020 from .bbs_bls_signature_proof_2020 import B...
1606287
import abc from carbonserver.api import schemas class Runs(abc.ABC): @abc.abstractmethod def add_run(self, run: schemas.RunCreate): raise NotImplementedError
1606341
import torch import torch.nn as nn import torch.nn.functional as F class FocalLoss_Ori(nn.Module): """ This is a implementation of Focal Loss with smooth label cross entropy supported which is proposed in 'Focal Loss for Dense Object Detection. (https://arxiv.org/abs/1708.02002)' Focal_Loss= -1*al...
1606395
from rxbp.mixins.flowablemixin import FlowableMixin from rxbp.observables.tolistobservable import ToListObservable from rxbp.subscriber import Subscriber from rxbp.subscription import Subscription class ToListFlowable(FlowableMixin): def __init__(self, source: FlowableMixin): super().__init__() s...
1606420
from sys import stdin from collections import deque INFINITE = 999999999 def read_scenario(): npapers, nauthors = tuple(map(int, stdin.readline().split())) papers = [stdin.readline() for _ in range(npapers)] authors = [stdin.readline().rstrip() for _ in range(nauthors)] return papers, authors d...
1606455
import requests, re, os, time from bs4 import BeautifulSoup import http.cookiejar def search(keyword, headers, cookies=".cookies\\ssd.txt"): if not os.path.exists(cookies): return False re_subname = re.match(r'(.+?)\.(mkv|mp4|ts|avi)', keyword) #去除副檔名 key1 = key2 = re_subname.group(1) if re_subname else keyword ...
1606501
from .base import Brain from .brain_nn import BrainNN from .rlpower_splines import BrainRLPowerSplines from .bo_cpg import BrainCPGBO
1606527
from __future__ import unicode_literals from django.conf.urls import * from .views import datatable_manager app_name = 'django_datatables' urlpatterns = [ url(r'^data/$', datatable_manager, name="datatable_manager") ]
1606569
import os import yaml import click import shutil import subprocess import venv as ve lab_project = ['experiments', 'data', 'logs', 'notebooks', 'config'] # Project def check_minio_config(minio_tag): """Check that minio configuration exists""" home_dir = os.path.expanduser('~') lab_dir = os.path.join(home...
1606606
import pytest import sqlalchemy as sa from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy_utils import get_hybrid_properties @pytest.fixture def Category(Base): class Category(Base): __tablename__ = 'category' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa....
1606615
from o3seespy.base_model import OpenSeesObject class UniaxialMaterialBase(OpenSeesObject): op_base_type = "uniaxialMaterial" op_type = None def set_parameter(self, osi, pstr, value, ele, eles): from o3seespy import set_parameter if ele is not None: set_parameter(osi, value=val...
1606669
from tensorflow import keras from tensorflow.keras import backend as K from ..function_approximator import FunctionApproximator __all__ = ( 'ConnectFourFunctionApproximator', ) class ConnectFourFunctionApproximator(FunctionApproximator): """ A :term:`function approximator` specifically designed for th...
1606697
from django.apps import AppConfig from orchestra.core import services class MailboxesConfig(AppConfig): name = 'orchestra.contrib.mailboxes' verbose_name = 'Mailboxes' def ready(self): from .models import Mailbox, Address services.register(Mailbox, icon='email.png') services....
1606734
from app.core.result import Result def get_success_result() -> Result: result = Result() result.set_success() return result def get_error_result() -> Result: result = Result() result.error('some error') return result def get_failed_result() -> Result: return Result()
1606786
import cv2, pyrebase, socket,struct import numpy as np from tracker import CentroidTracker import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(33,GPIO.IN) GPIO.setup(34,GPIO.IN) GPIO.setup(36,GPIO.OUT) GPIO.setup(37,GPIO.OUT) RollOut = GPIO.PWM(36,300) PitchOut = GPIO.PW...
1606804
import numpy as np import pytest import math from sklearn.base import clone from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestRegressor import doubleml as dml from ._utils import draw_smpls from ._utils_irm_manual import fit_irm, boot_irm, tune_nuisance_irm @pytest.fixtu...
1606867
import packerlicious.provisioner as provisioner class TestBreakpointProvisioner(object): def test_no_required_fields(self): b = provisioner.Breakpoint() b.to_dict()
1606868
from ...utilities.units.dataclasses import DataClassWithPscale, distancefield class ImageStats(DataClassWithPscale): """ Gives statistics about an HPF image. n: id of the HPF mean, min, max, std: the average, minimum, maximum, and standard deviation of the pixel fluxes cx, cy: the cen...
1606879
import unittest import torch from models import decoders from templates import ModelTestsMixin, FrozenLayerCheckMixin class TestDenseEncoder(ModelTestsMixin, unittest.TestCase): def setUp(self): self.test_inputs = torch.randn(16, 32) self.output_shape = torch.Size((16, 1, 32, 32)) self.n...
1606882
import django.dispatch # @@@ this is the exact same as in django.contrib.auth not sure why it's duped here user_logged_in = django.dispatch.Signal(providing_args=["request", "user"]) password_changed = django.dispatch.Signal(providing_args=["user",]) user_login_attempt = django.dispatch.Signal(providing_args=["userna...
1606886
import ctypes import enum import errno from dataclasses import dataclass from functools import partial from signal import Signals import socket from typing import List IOC_REQUEST_PARAMS = { 0x20000000: 'IOC_VOID', 0x40000000: 'IOC_OUT', 0x80000000: 'IOC_IN', 0xc0000000: 'IOC_IN | IOC_OUT', 0xe0000...
1606893
import cv2 VC = cv2.VideoCapture('test.mp4') if VC.isOpened(): rval, frame = VC.read() else: rval = False c = 1 while rval: rval, frame = VC.read() cv2.imwrite('./frames/%s.jpg' % c, frame) c += 1 cv2.waitKey(1) VC.release()
1606903
from FormulaLab.search import FormulaSearch __all__ = ['FormulaSearch', ] __version__ = '0.1.0'
1606921
import sys import time import tensorflow as tf def print_time(s, start_time): """Take a start time, print elapsed duration, and return a new time.""" print("%s, time %ds, %s." % (s, (time.time() - start_time), time.ctime())) # sys.stdout.flush() return time.time() def print_out(s, f=None, new_line...
1606922
import os import unittest from programy.utils.parsing.linenumxml import LineNumberingParser import xml.etree.ElementTree as ET # pylint: disable=wrong-import-order from programy.parser.aiml_parser import AIMLParser from programy.dialog.sentence import Sentence from programy.parser.pattern.nodes.oneormore import Patter...
1606935
import numpy as np import tensorflow as tf from tabnet.datasets.covertype import get_data, get_dataset COVTYPE_CSV_PATH = "data/test/covtype_sample.csv" SEED = 42 class TestDataset(tf.test.TestCase): def test_gets_always_the_same_data(self): df_tr, df_val, df_test = get_data(COVTYPE_CSV_PATH, seed=SEED...
1606936
from abc import ABC, abstractmethod from typing import Dict, Optional, Sequence, Union from virtool.http.rights import MODIFY, READ, REMOVE, Right from virtool.jobs.utils import JobRights class AbstractClient(ABC): @property @abstractmethod async def authenticated(self) -> bool: ... @propert...
1606966
import numpy as np import torch from torch import nn import copy from collections import defaultdict from absl import logging from musco.pytorch.compressor.decompositions.tucker2 import Tucker2DecomposedLayer from musco.pytorch.compressor.decompositions.cp3 import CP3DecomposedLayer from musco.pytorch.compressor.deco...
1607015
import numpy as np import torch import glob import os import pickle import argparse from torch.utils.data import DataLoader from torch.utils.data.dataset import (TensorDataset, ConcatDataset) from i2i.cyclegan import CycleGAN from util import (convert_to_rgb, H5Da...
1607017
import pandas as pd from os import path from .common import * from .time_utility import * # Tushare access limit, as fetch times per minute. # If fetch data from tushare gets error message like: "抱歉,您每分钟最多访问该接口x次" # Fill the x to the corresponding entry of this table # This config is for 5000 scores. The number in c...
1607021
import fcntl import os class Concurrency(): # Default constructor def __init__(self, log, resource): self.log = log self.lock_file = f"/tmp/{resource}_lock" self.lock_fh = None def open_lock_file(self): if os.path.exists(self.lock_file): self.lock_fh = open(se...
1607030
from . import id_software class RavenBsp(id_software.IdTechBsp): file_magic = b"RBSP" # includes marker lump: # https://github.com/TTimo/GtkRadiant/blob/master/tools/urt/tools/quake3/q3map2/bspfile_rbsp.c#L308 # sprintf( marker, "I LOVE MY Q3MAP2 %s on %s)", Q3MAP_VERSION, asctime( localtime( &t ) ) ...
1607039
from .model import SMTilesMapProviderSetting, FastDFSTileProviderSetting, MongoDBTileProviderSetting, \ OTSTileProviderSetting, UGCV5TileProviderSetting, GeoPackageMapProviderSetting, MngServiceInfo, ProviderSetting from iclientpy.dtojson import * _provider_setting_parsers = { 'com.supermap.services.provi...
1607041
import numpy as np from .rank import pagerank from .sentence import sent_graph from .word import word_graph class KeywordSummarizer: """ Arguments --------- sents : list of str Sentence list tokenize : callable Tokenize function: tokenize(str) = list of str min_count : int ...
1607044
from opentera.forms.TeraForm import * from modules.DatabaseModule.DBManagerTeraUserAccess import DBManagerTeraUserAccess from flask_babel import gettext class TeraServiceConfigForm: @staticmethod def get_service_config_form(): form = TeraForm("service_config") # Building lists #####...
1607063
import os import sys import time import glob import shutil import argparse import cv2 import numpy as np sys.path.insert(0, '..') import plantid def imread_ex(filename, flags=-1): try: return cv2.imdecode(np.fromfile(filename, dtype=np.uint8), flags) except Exception as e: return None ...
1607083
import subprocess import sys import os import get_mjpeg import make_movie import shutil import datetime import util config = util.get_config() tmp_dir = config.get('treasurecolumn', 'tmp_dir') ffmpeg_location = config.get('treasurecolumn', 'ffmpeg_location') def convert_mp4(input_file, output_file): if os.path.exist...
1607085
import glob import os from pprint import pformat from shutil import rmtree, copy2 from pick_model_runs_fun import test_diff_list, load_packages_verbose, run_and_compare_h_cbc from flopyparser.model import Model """This script does three things 1. reorganize the mf5 examples, so that each example has its own folder. O...
1607089
import os import sys from easydict import EasyDict CONF = EasyDict() # path CONF.PATH = EasyDict() CONF.PATH.BASE = "/home/yuanzhihao/Projects/X-Trans2Cap/" # TODO: change this CONF.PATH.CLUSTER = "/mntntfs/med_data1/yuanzhihao/X-Trans2Cap/" # TODO: change this CONF.PATH.DATA = os.path.join(CONF.PATH.BASE, 'data') ...
1607140
import numpy as np import scipy from ... import operators from ... import utilits as ut from . _ar_yule_walker import ar_yule_walker __all__ = ['arma_hannan_rissanen'] #------------------------------------------------------------------ def arma_hannan_rissanen(x, poles_order=0, zeros_order=0, unbias = True): '...
1607152
import argparse import os import abc import time import common.evalutation.eval as ev import rechun.eval.analysis as analysis import rechun.eval.hook as hooks import rechun.eval.evaldata as evdata import rechun.directories as dirs def main(dataset, to_eval, action_names): if dataset not in ('brats', 'isic'): ...
1607187
class Solution: def numWays(self, n: int, k: int) -> int: if n == 0: return 0 elif n == 1: return k elif n == 2: return k * k else: prev01, prev02 = k, k * k n -= 2 while n > 0: prev02, prev01 = (...
1607189
import pathlib from typing import Dict, Optional, Type, Union from astro.constants import FileType as FileTypeConstants from astro.files.types.base import FileType from astro.files.types.csv import CSVFileType from astro.files.types.json import JSONFileType from astro.files.types.ndjson import NDJSONFileType from astr...
1607213
import os import pandas as pd class DatasetConverter(object): def __init__(self, dataset_path, dataset_name=None): self.dataset_path = dataset_path if dataset_name is None: self.dataset_name = os.path.basename(dataset_path).upper() else: self.dataset_name = dataset...
1607223
import sys sys.path.insert(0,'..') from algobpy.parse import parse_params from pyteal import * def dao_fund_lsig(ARG_DAO_APP_ID): """ Represents DAO treasury (ALGO/ASA) """ # check no rekeying, close remainder to, asset close to for a txn def basic_checks(txn: Txn): return And( txn.rekey_...
1607251
import logging import time import psutil from icrawl_plugin import IHostCrawler from utils.features import DiskioFeature logger = logging.getLogger('crawlutils') class DiskioHostCrawler(IHostCrawler): ''' Plugin for crawling disk I/O counters from host and computing the bytes/second rate for read and wr...
1607253
from __future__ import absolute_import import functools __all__ = ["IdentityContext", "PermissionDenied"] class PermissionContext(object): """A context of decorator to check the permission.""" def __init__(self, checker, exception=None, **exception_kwargs): self._check = checker self.in_co...
1607299
import numpy as np from wtm_envs.mujoco import robot_env, utils import mujoco_py from queue import deque from mujoco_py import modder import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg import platform import os def goal_distance(goal_a, goal_b): assert goal_a.shape == goal_...
1607363
from typing import Dict, List, Any import json import e2e.Libs.Ristretto.Ristretto as Ristretto from e2e.Libs.BLS import PrivateKey from e2e.Classes.Transactions.Transactions import Data, Transactions from e2e.Classes.Consensus.VerificationPacket import VerificationPacket from e2e.Classes.Consensus.SendDifficulty i...
1607369
from lsassy.output import IOutput class Output(IOutput): """ Returns output in greppable format """ def get_output(self): credentials = set() for cred in self._credentials: line = "{}\t{}\t{}\t{}\t{}\t{}\t{}".format(cred["ssp"], cred["domain"], cred["username"], c...
1607375
import numpy as np import os import pickle as p import argparse parser = argparse.ArgumentParser() parser.add_argument('--result_dir', type=str,required=True) args = parser.parse_args() def compute_iou(pred_box, ref_bbox): N=pred_box.shape[0] pred_box_rb = pred_box[:,0:3] - pred_box[:,3:6] / 2.0 ref_bb...
1607378
from viznet import * import matplotlib.pyplot as plt def draw_caizi_nn(ax, num_node_visible, num_node_hidden): '''CaiZi R-Theta Network''' # brush conv = NodeBrush('nn.convolution', ax) input = NodeBrush('nn.input', ax) hidden = NodeBrush('nn.hidden', ax) output = NodeBrush('nn.output', ax) ...
1607418
from miscellanies.torch.metric_logger import MetricLogger, SmoothedValue import copy from core.run.event_dispatcher.register import EventRegister def _load_metric_definitions(metric_definitions, logger: MetricLogger): name_check = set() for metric_definition in metric_definitions: window_size = 20 ...
1607440
from .temporal import * import numpy as np defaults = dict( ydeg=15, udeg=2, r=20.0, dr=None, a=0.40, b=0.27, c=0.1, n=10.0, p=1.0, i=60.0, u=np.zeros(30), tau=None, temporal_kernel=Matern32Kernel, normalized=True, normalization_order=20, normalization_zm...
1607446
import numpy as np import pytest import math from sklearn.base import clone from sklearn.linear_model import Lasso, ElasticNet import doubleml as dml from ._utils import draw_smpls from ._utils_plr_manual import fit_plr, boot_plr, tune_nuisance_plr @pytest.fixture(scope='module', params=[Lasso(), ...
1607448
from sly import Lexer, Parser from os import path from defs import * global curr_file, curr_text, error_occurred, curr_namespace, reserved_names def syntax_error(line, msg=''): global error_occurred error_occurred = True print() if msg: print(f"Syntax Error in file {curr_file} line {line}:")...
1607470
from .start_encoding_trimming import StartEncodingTrimming from .scheduling import Scheduling from .tweaks import Tweaks from .start_encoding_request import StartEncodingRequest from .manifests import StartManifest, VodStartManifest, VodDashStartManifest, VodHlsStartManifest
1607488
import pycomicvine import datetime from pycomicvine.tests.utils import * pycomicvine.api_key = "476302e62d7e8f8f140182e36aebff2fe935514b" class TestLocationsList(ListResourceTestCase): def test_get_id_and_name(self): self.get_id_and_name_test( pycomicvine.Locations, pycomic...
1607498
import unittest import numpy as np import torch from pytorch_adapt.layers import MMDBatchedLoss, MMDLoss from pytorch_adapt.layers.utils import get_kernel_scales from .. import TEST_DEVICE # from https://github.com/thuml/Xlearn/blob/master/pytorch/src/loss.py def guassian_kernel(source, target, kernel_mul=2.0, ker...
1607532
import hashlib from pathlib import Path try: import importlib.resources as resources except ImportError: # python < 3.7 import importlib_resources as resources # type: ignore[no-redef] from docutils import nodes from docutils.parsers.rst import directives from sphinx.application import Sphinx from sphinx...
1607535
from typing import Dict, List, Optional from rotkehlchen.fval import FVal def assert_serialized_lists_equal( a: List, b: List, max_length_to_check: Optional[int] = None, ignore_keys: Optional[List] = None, length_list_keymap: Optional[Dict] = None, max_diff: str = "1e-...
1607536
import json from google.protobuf import json_format import tinkoff_voicekit_client.speech_utils.apis.tinkoff.cloud.longrunning.v1.longrunning_pb2 as pb_operations def get_proto_operation_request(request: dict): grpc_request = json_format.Parse(json.dumps(request), pb_operations.GetOperationRequest()) return...