id
stringlengths
3
8
content
stringlengths
100
981k
9937037
from .. import TransformersTorchSeqClassifier import numpy as np import pytest def test_sequencetransformerstorchclassifier(): model_name = 'distilbert-base-uncased-finetuned-sst-2-english' classifier = TransformersTorchSeqClassifier(model_name) data = np.stack( [ 'Today is a good day....
9937059
from unittest import TestCase from ...elastic import ElasticsearchProxy class ElasticTestCase(TestCase): def setUp(self): self.es_host = '127.0.0.1' def test_get_transactions(self): es = ElasticsearchProxy(self.es_host) transactions = es.get_transactions(['19336', '19976']) s...
9937071
from aioify import aioify from discord.ext import commands from typing import Optional, Union import aiofiles import aiohttp import aiosqlite import asyncio import discord import glob import json import os import remotezip import shutil import time class Utils(commands.Cog): def __init__(self, bot): self....
9937102
import numpy as np from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential, Model from keras.layers import Dropout, Flatten, Dense, GlobalAveragePooling2D from keras import applications from keras import backend as K #from keras_squeezenet import SqueezeNet import tensorflow as tf f...
9937114
from data.load_dataset import MultipleDataLoader from lib.utils.training_stats import TrainingStats from lib.utils.evaluate_depth_error import validate_rel_depth_err, recover_metric_depth from lib.models.diverse_depth_model import * from lib.core.config import cfg, merge_cfg_from_file, print_configs from lib.utils.net_...
9937146
import lmdb import os import pickle from .feature_reader import FeatureReader, FEATURE_READERS @FEATURE_READERS.register_module() class LMDBFeatureReader(FeatureReader): def __init__(self, dataset_type, feat_path=None, max_features=None): super().__init__(dataset_type, feat_path=feat_path, max_features=m...
9937158
import pooch from pathlib import Path from typing import Union from .adhoc import handle_pannuke from .base_downloader import BaseDownloader HASHES = { "fold_1":"6e19ad380300e8ce9480f9ab6a14cc91fa4b6a511609b40e3d70bdf9c881ed0b", "fold_2":"5bc540cc509f64b5f5a274d6e5a245527dbd3e6d3155d43555115c5d54709b07", ...
9937174
import unittest from ..docstring_parsing import DocStringInfo, Arg, number_of_spaces from contracts.interface import add_prefix examples = {""" Provides a RGB representation of the values by interpolating the range [min(value),max(value)] into the colorspace [min_color, max_color]. :param va...
9937194
import unittest from tfaip import PipelineMode, Sample from calamari_ocr.ocr.dataset.textprocessors import TextRegularizerProcessorParams class TextTextRegularizer(unittest.TestCase): def test_space_quotes(self): n = TextRegularizerProcessorParams( rulesets=["quotes", "spaces"], ...
9937262
from django import template from panel.handlers import is_demo as check_is_demo register = template.Library() @register.simple_tag() def is_demo() -> bool: if check_is_demo(): return True return False
9937270
import re import time from multiprocessing import Process, Queue # (45,11),(41,15),(36,20) PTS_REGEX = "\((\d*),(\d*)\)" TOTAL_PROCESSES = 8 def find_area(points_queue): points_str = points_queue.get() while points_str is not None: points = [] area = 0.0 for xy in re.finditer(PTS_REGE...
9937275
import datetime import itertools import logging import pickle from typing import List, Tuple import click import matplotlib import numpy as np import pandas as pd from matplotlib import figure from sklearn.linear_model import ElasticNet from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score fr...
9937283
from django.contrib.auth.base_user import AbstractBaseUser from django.db import models from django_countries.fields import CountryField from accounts.managers import AccountManager from projects.models import Project class Account(AbstractBaseUser): uid = models.AutoField(primary_key=True) email = models.Em...
9937312
import pytest from metagraph.tests.util import default_plugin_resolver from . import RoundTripper import pandas as pd def test_dataframe(default_plugin_resolver): rt = RoundTripper(default_plugin_resolver) df = pd.DataFrame( { "Source": [0, 1, 1, 3], "Target": [1, 2, 3, 1], ...
9937319
from torch.nn import Module, LSTM, Dropout from getalp.wsd.model_config import ModelConfig from getalp.wsd.modules.encoders.encoder_base import EncoderBase class EncoderLSTM(Module): def __init__(self, config: ModelConfig): super().__init__() self.base = EncoderBase(config) if config.en...
9937322
import typing from http import cookies as http_cookies def cookie_parser(cookie_string: str) -> typing.Dict[str, str]: """ This function parses a ``Cookie`` HTTP header into a dict of key/value pairs. It attempts to mimic browser cookie parsing behavior: browsers and web servers frequently disregard t...
9937363
from random import shuffle import tensorflow as tf import tensorflow_text as tf_text from tf_transformers.data import TFReader from tf_transformers.utils import tf_utils def split_fn(item, delimiter_pattern): text_splitted = tf_text.regex_split(item['text'][0], delimiter_pattern, keep_delim_regex_pattern=' ', n...
9937388
import pulumi import pulumi_auth0 as auth0 client = auth0.Client("client", allowed_clients=["https://allowed.example.com"], allowed_logout_urls=["https://example.com"], allowed_origins=["https://example.com"], app_type="regular_web...
9937392
from unittest import TestCase from carbon.util import parseRetentionDef class TestParseRetentionDef(TestCase): def test_valid_retentions(self): retention_map = ( ('60:10', (60, 10)), ('10:60', (10, 60)), ('10s:10h', (10, 3600)), ) for retention, expected...
9937405
from .string_expr import StringExpression from . import filepath_utils from ..rfb_logger import rfb_log from bpy.app.handlers import persistent import bpy import os import re PAD_FMT = ['%d', '%01d', '%02d', '%03d', '%04d'] __SCENE_STRING_CONVERTER__ = None # FIXME: we should get the extensions from the display driver...
9937454
from sacred import Experiment from sacred.utils import apply_backspaces_and_linefeeds from experiments.utils import get_observer from experiments.evaluation import import_weights_into_network from experiments.utils import ExperimentData from xview.datasets import get_dataset from xview.models import get_model, BayesFus...
9937467
import os import datetime import numpy as np def df_to_unique_csv(df, file_prefix): now = datetime.datetime.now() d = '%s-%s-%s' % (now.year, now.month, now.day) if not os.path.exists(d): os.makedirs(d) i = 0 while os.path.exists("%s/%s.%s.csv" % (d, file_prefix, i)): i += 1 ...
9937525
from __future__ import print_function from mongoalchemy.py3compat import * from mongoalchemy.util import classproperty, UNSET def test_class_properties(): class A(object): a = 1 b = 2 @classproperty def c(cls): return cls.a+cls.b assert A.c == 3 def test_UNSET(): ...
9937616
import tensorflow as tf import numpy as np import math import sys import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, '../utils')) sys.path.append(os.path.join(BASE_DIR, '../../utils')) import tf_util from transform_nets import input_transform...
9937640
from tests.integration.base import DBTIntegrationTest, use_profile class TestColumnTypes(DBTIntegrationTest): @property def schema(self): return 'column_types' def run_and_test(self): self.assertEqual(len(self.run_dbt(['run'])), 1) self.assertEqual(len(self.run_dbt(['test'])), 1) ...
9937661
import os from enum import Flag, auto from io import BytesIO from textwrap import wrap import piexif import requests from PIL import Image, ImageFont, ImageDraw BREAKPOINT_DIMENSION = 400 # 400px MARGIN_RATIO = 0.04 # 4% FONT_RATIO = 0.04 # 4% FRAME_COLOR = '#fff' # White frame TEXT_COLOR = '#000' # Black text ...
9937718
import json import unittest from route4me.utils import json2obj from tests.base import Route4MeAPITestSuite class Route4MeUtilsTests(Route4MeAPITestSuite): """ Route4Me Utils Tests """ def test_json2obj(self): json_data = json.dumps({'variable1': 'test_value'}) json_obj = json2obj(js...
9937719
import os from typing import Any, Optional import hydra from hydra import compose, initialize_config_dir from artefact_nca.config.config_utils import setup_config def load_config(config_path: Optional[str] = None, config_name = "default") -> Any: setup_config() if config_path is not None: config_pat...
9937739
import os import sys import datetime req_path=input("Enter your path: ") age=3 if not os.path.exists(req_path): print("Please provide valid path ") sys.exit(1) if os.path.isfile(req_path): print("Please provide directory path ") sys.exit(2) today=datetime.datetime.now() for each_file in os.listd...
9937742
import autograd.numpy as np import autograd.numpy.random as npr from ssmdm.accumulation import Accumulation, LatentAccumulation import copy import matplotlib.pyplot as plt import seaborn as sns sns.set_style("ticks") sns.set_context("talk") from ssmdm.misc import smooth, generate_clicks, generate_clicks_D from ssm.pr...
9937757
from django.contrib import admin from django.urls import include, path from rest_framework.routers import DefaultRouter from .sample_group_viewset import GroupViewSet router = DefaultRouter() router.register("auth/group", GroupViewSet) router.register("auth/groups", GroupViewSet) urlpatterns = [ path("api/", in...
9937772
import torch import math from zhusuan.mcmc.SGMCMC import SGMCMC class SGLD(SGMCMC): """ Subclass of SGMCMC which implements Stochastic Gradient Langevin Dynamics (Welling & Teh, 2011) (SGLD) update. The updating equation implemented below follows Equation (3) in the paper. * **var_list** - ...
9937787
from heapq import heappush, heappop from collections import namedtuple, defaultdict from .nearest import BruteForceNeighbors, KDNeighbors from .primitives import default_weights, get_embed_fn, get_distance_fn from .utils import INF, elapsed_time, get_pairs, default_selector, irange, \ merge_dicts, compute_path_cos...
9937797
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy # get the annotated file as well import Cython.Compiler.Options Cython.Compiler.Options.annotate = True ext_modules = [ Extension("matMul", sources=["matMul.pyx", "cMatMul.c...
9937807
import json import os import argparse import torch import numpy as np import wandb import yaml from scipy import stats from holoprot.data import DATASETS from holoprot.models.model_builder import MODEL_CLASSES from holoprot.utils.metrics import DATASET_METRICS, METRICS DEVICE = "cuda" if torch.cuda.is_available() els...
9937849
import os, sys import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import ROOT import numpy as np import pandas as pd import root_numpy as rn from util.fill_df import * BASE_PATH = os.path.realpath(__file__) BASE_PATH = os.path.dirname(BASE_PATH) rse = ['run','subrun','event'] rsev = ['ru...
9937883
from glob import glob import os def Print(dir): include_root = '../Include/' with open(include_root + dir+'.hpp', 'w') as f: print("#pragma once", file=f) print('', file=f) for x in glob(include_root + dir+"/**/*.hpp", recursive=True): x = os.path.relpath(x, include_root) x = x.replace('\\', '/') prin...
9937897
import json import matplotlib.pyplot as plt import os from functools import reduce from pyrsistent import pmap from pyrsistent.typing import PMap from typing import FrozenSet from rlo import analytics from rlo.dataset import StateValueDataset from rlo.expression_util import SymtabAndDefs from rlo import expr_sets from...
9937916
import os ope = os.path.exists opj = os.path.join import numpy as np import socket import warnings warnings.filterwarnings('ignore') sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) hostname = socket.gethostname() RESULT_DIR = '/data4/data/retrieval2020/result' DATA_DIR = '/data5/data/landmark2020' PRE...
9937917
AlMohanad_map = [ (0, 1), (12, 15), (32, 127), (160, 444), (446, 502), (504, 540), (542, 544), (548, 564), (1548, 1549), (1563, 1564), (1567, 1568), (1569, 1595), (1600, 1619), (1632, 1643), (1645, 1646), (7680, 7834), (7835, 7836), (7840, 7930), ...
9937929
if not exists("AEITOMGTMSMD.png"): exit(1) click(Pattern("AEITOMGTMSMD.png").targetOffset(-31,33)) sleep(1) exit(0)
9937954
import numpy as np class MyModel: def __init__(self, a=None, b=None, c=None, d=None, e=None, q=None, p=None): self.a = a self.b = b self.c = c self.d = d self.e = e self.q = q self.p = p self.dimension = 3 def dynamics(self, x0, t): """...
9937989
import tvm, numpy, ast, inspect, re, textwrap import warnings as wrn from mutator import IRMutator def preprocess_source(src, lam = True): # remove comments src = re.sub(r'#.*\n', "\n", src) src = re.sub(r'\'\'\'.*\'\'\'', "\n", src, flags=re.S) # remove header indentations src = textwrap.dedent(src) # re...
9937996
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability class DeviceFilterSetRemote(RemoteModel): """ Network traffic rule lists; on most routers and firewalls, this corresponds to an access control list. In JunOS packet mode configurations, it corresponds to a rule-set...
9938001
from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('templates'), extensions=['jinja2.ext.autoescape'], autoescape=True) demos = [{ "title": 'canvas LEDs', "dir" : 'leds', "theme": "dark1", "highlight_theme" : "monokai" }, { "title": 'Hello World', "dir" : 'hello...
9938006
import os import re from tests.utils.txt_to_json import create_tmp_test_textfile, rm_tmp_file class TestEmbeddings(object): """ test embedding functions """ def ingor_test_char2vec_standalone(self): """ test char2vec_standalone training """ abs_path = os.path.dirname(os...
9938034
from unittest import mock from framewirc.messages import build_message, ReceivedMessage from framewirc.parsers import ( apply_kwargs_parser, apply_message_parser, is_channel, nick, privmsg, ) class TestIsChannel: """Tests for the boolean function is_channel.""" def test_starts_with_ampers...
9938067
from __future__ import print_function import sympy as sm x, y, a = sm.symbols('x y a') f = a*x + y**2*sm.sin(y) step1 = sm.Integral(f, x, y) print(step1) step2 = sm.Integral(sm.Integral(f, x).doit(), y) print(step2) step3 = step2.doit() print(step3)
9938081
import re import sys import os import logging import time import hashlib from urlparse import urlparse from malware import utils from malware import decoder from malware.snort import SnortRule from malware.sql_tool import SQLiteTool from malware import apikey from virus_total_apis import PrivateApi as VirusTotal logge...
9938083
from django.contrib import admin from . import models class ArticleAdmin(admin.ModelAdmin): list_filter = ['bee'] search_fields = ['real_url', 'ra_title'] class ClassifiedAdmin(admin.ModelAdmin): list_filter = ['article__bee', 'types'] search_fields = ['article__real_url', 'article__ra_title'...
9938086
import asyncio import time import string import random import aiofiles import threading import gevent dir = '/var/run/workflow_results/' #dir = 'data/' async def open_file(file): async with aiofiles.open(dir + file, mode='r') as f: content = await f.read() print(len(content)) return len(content...
9938091
from typing import List class Solution: def alienOrder(self, words: List[str]) -> str: if not words: return '' all_words = set() graph_words = set() from collections import defaultdict, deque graph = defaultdict(list) in_degrees = defaultdict(int) ...
9938092
import jwt from rest_framework import authentication, exceptions from django.conf import settings from api.user.models import User from api.authentication.models import ActiveSession class ActiveSessionAuthentication(authentication.BaseAuthentication): auth_error_message = {"success": False, "msg": "User is no...
9938150
from chatbot import chatbot from flask import Flask, render_template, request,session,logging,url_for,redirect,flash from flask_recaptcha import ReCaptcha import mysql.connector import os app = Flask(__name__) recaptcha = ReCaptcha(app=app) app.secret_key=os.urandom(24) app.static_folder = 'static' app.config.update...
9938181
import pytest from sam_spot_bot_create_job import iam_helper from .my_ut_config import create_env @pytest.fixture() def init_env(): """ Generates API GW Event""" create_env() return {} def test_get_location(init_env): helper = iam_helper.IamHelper() print(helper.get_region()) def test_create_...
9938211
from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome('./chromedriver') driver.get('https://google.com') # locate the search box element search_box = driver.find_element_by_name('q') import time time.sleep(5) # type in our search query into the search box search_bo...
9938238
import sys import optparse import glob import os import string import tempfile import shutil import zipfile import textureconverter from pipelinetools import * def MakeObjQuad(origsize, trimsize, scale, depth, plane, outfilename): p0 = [ (trimsize[0] - origsize[0]/2)*scale, (-trimsize[3]+origsize[1]/2)...
9938256
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm from django.utils import timezone from .email_service import UsersSaasyEmailService from .models import User class CustomPasswordResetForm(PasswordResetForm): """ Default form was customized to create an RefreshToken object during s...
9938288
import os import taichi as ti import numpy as np import utils import math from engine.mpm_solver import MPMSolver import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-o', '--out-dir', type=str, help='Output folder') args = parser.parse_args() print(args) retur...
9938289
import os import sys import time sys.path.insert(1, os.path.join(sys.path[0], '../..')) import src from utils.utilities import (load_json) import numpy as np BOUND = 1 INSTRUMENTS = {"seen": "Violin,Cello,Viola,Flute,Clarinet,Saxophone,Trumpet,Trombone", "unseen": "Horn,Tuba,Double_Bass,Bassoon,Oboe"} skip...
9938290
import os import pytest from yarl import URL from staff.utils import DEFAULT_PG_URL @pytest.fixture(scope='session') def pg_url(): """ Provides base PostgreSQL URL for creating temporary databases. """ return URL(os.getenv('CI_STAFF_PG_URL', DEFAULT_PG_URL))
9938315
from abc import abstractmethod, ABC, ABCMeta class AbstractConfigurationStorageRepository(ABC): __metaclass__ = ABCMeta @abstractmethod def store_configuration(self, name: str, configuration_obj: object) -> None: raise NotImplementedError @abstractmethod def retrieve_configuration(self, name) ->...
9938338
import logging import os import nbformat import pytest from nbconvert.preprocessors import ExecutePreprocessor NOTEBOOKS_DIR = "notebooks" DOCS_DIR = "docs" resources = {"metadata": {"path": NOTEBOOKS_DIR}} log = logging.getLogger(__name__) class LoggingExecutePreprocessor(ExecutePreprocessor): def __init__(se...
9938376
from numpy import * from itertools import * from collections import * import time # This program is intended for calculating the inverse kinematics for a robotic arm with one azimuthal degree of freedom # And 3 effectors that do not rotate at a wrist. # First we set the lengths of each arm in our assemblage, th...
9938378
import numpy as np '''Scenes - simple smooth transitions of a variable for making better animations''' class Act: def __init__(self, start, end, dt=1, met="lin", c=2.): 'Act - a variable starting at value start, changing to value end, after time dt, interpolating with method met' self.start = start...
9938382
from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.shortcuts import render from django.urls import reverse from django.urls import reverse_lazy from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView from django.views.gener...
9938402
import json import pytest import core.event import core.config import core.output import core.module class SampleModule(core.module.Module): pass @pytest.fixture(autouse=True) def clear_events(): core.event.clear() @pytest.fixture def i3(): return core.output.i3() @pytest.fixture def module_a(mocke...
9938408
from . import interpolate # noqa: F401 from . import zero_volume_corrector # noqa: F401 from .zero_volume_corrector import ZeroVolumeCorrectorFunction # noqa: F401
9938442
import attr import abc import six from openpype.lib import PypeLogger log = PypeLogger().get_logger("SyncServer") STATUS = { 0: 'In Progress', 1: 'Queued', 2: 'Failed', 3: 'Paused', 4: 'Synced OK', -1: 'Not available' } DUMMY_PROJECT = "No project configured" @six.add_metaclass(abc.ABCMet...
9938477
from django.conf.urls import re_path, include from clist import views app_name = 'clist' urlpatterns = [ re_path(r'^$', views.main, name='main'), re_path(r'^send-event-notification/$', views.send_event_notification, name='send_event_notification'), re_path(r'^resources/$', views.resources, name='resources...
9938479
from connect import * import psycopg2.extras from datetime import datetime from datetime import timedelta import os import time import pandas as pd from pprint import pprint try: # Connect to PostgreSQL database conn, engine = connect_to_db() cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCurs...
9938499
lRESCUETIME_API_KEY = RESCUETIME_API_KEY TODOIST = {"email" : EMAIL, "password" : PASSWORD} SPOTIFY = {"email" : EMAIL, 'client_id' : CLIENT_ID, 'client_secret': CLIENT_SECRET, 'redirect_uri': WHAT_YOU_ENTER_ON_SPOTIFY} MOVES_KEYS = {'client_id':CLIENT_ID, 'client_secret':CLIENT_SECRET, 'redirect_uri': WHAT_YOU_ENTER_O...
9938505
import functools import numpy as np from scipy.stats import norm as ndist import regreg.api as rr from selection.tests.instance import gaussian_instance from knockoffs import lasso_glmnet from core import (infer_full_target, split_sampler, # split_sampler not working yet normal_s...
9938506
from flask import url_for, session, redirect from functools import wraps # login_required and logout_required decorators that ensure certain url's confront to # respective wanted behaviors! # This file contains only admin centered login checks. # Custom login_required decorator def login_required(view_function): ...
9938532
import os import sys import yaml def run(): command = 'salt-run manage.status' all_control = ControllerAdmin.fetch_all() for i in all_control: salt_obj = SaltSshBase(i.to_dict()) data = salt_obj.salt.shell_remote_execution("master-local", command) yaml_str = data.get("master-loca...
9938544
from typing import Tuple from rich import progress __all__ = ["Progress"] class Progress(progress.Progress): @classmethod def get_default_columns(cls) -> Tuple[progress.ProgressColumn, ...]: return ( progress.TextColumn("[progress.description]{task.description}"), progress.Bar...
9938568
import re from typing import Dict def replace(string: str, dictionary: Dict[str, str]) -> str: if not isinstance(string, str): raise TypeError("accept string type") pattern = re.compile("|".join(dictionary.keys())) return pattern.sub(lambda x: dictionary[x.group()], string)
9938601
import binascii import codecs import hashlib import hmac import math from six.moves import xrange from six.moves.urllib.parse import urlparse from six import text_type import mohawk from mohawk.base import EmptyValue from requests.auth import AuthBase class HawkAuth(AuthBase): """Handles authentication using Haw...
9938636
def exporta(dados, nome): dados.to_csv(f"./resultados/{nome}.csv", encoding='UTF-8') def diarios_antigos(df): df = df[df['data_inicial'] != 'Indefinido'] top = df.sort_values('data_inicial', ascending=True).filter(items=['municipio', 'regiao', 'populacao_2020','eh_capital','data_inicial']).head(10) ex...
9938658
import os from . import Project class MesonProject(Project): description = 'Meson' @classmethod def find(cls): return cls.find_containing('meson.build') def ensure_builddir(self): if self.exists('build/build.ninja'): return os.makedirs('build', exist_ok=True) ...
9938698
import os import tempfile import urllib import numpy as np from scipy.misc import imsave import cPickle import math import import_data_mnist from scipy.io import loadmat def mnist(datasets_dir='/TMP/'): URL_MAP = { "train": "http://www.cs.toronto.edu/~larocheh/public/datasets/binarized_mnist/binarized_mnist_tr...
9938726
algorithm='ppo' env_class='Gym' model_class='SingleHiddenLayer' environment = { 'name': 'CartPole-v1', 'max_steps': 1000, 'seed': 5 } model = { 'state_size': 4, 'action_size': 2, 'fc_units': 16 } agent = { 'lr': 0.005 } train = { 'n_episodes': 4000, 'max_t': 1000, 'solve_scor...
9938739
import os import cv2 data_dir = '/home/meprint/sunanlin_folder/data_copy' with open('data_copy.txt','w') as f: for folder in os.listdir(data_dir): folder_path = os.path.join(data_dir,folder) for img_name in os.listdir(folder_path): if "(1)" not in img_name: img_path =...
9938740
from astrolabe.interval import Interval from metrology.instruments.histogram import HistogramExponentiallyDecaying from metrology.instruments.meter import Meter class Timer(object): """ A timer measures both the rate that a particular piece of code is called and the distribution of its duration :: ...
9938799
debugging_test_text_001 = 'import bla' debugging_test_text_002 = 'import pdb' debugging_test_text_003 = 'import ipdb' debugging_test_text_004 = 'import pudb' debugging_test_text_005 = 'pdb = 10' debugging_test_text_006 = 'breakpoint()' debugging_test_text_007 = 'breakpoint = 0'
9938803
import pytest from bioptim import ( MultinodeConstraintList, MultinodeConstraintFcn, Node, OdeSolver, OptimalControlProgram, DynamicsList, DynamicsFcn, ObjectiveList, BoundsList, InitialGuessList, QAndQDotBounds, ) import biorbd_casadi as biorbd from .utils import TestUtils ...
9938853
from unittest.mock import patch, Mock from datetime import datetime from django.core.urlresolvers import reverse from allegation.factories import AllegationFactory from common.models import Allegation from common.tests.core import SimpleTestCase class AdminInvestigationDocumentsExportViewTestCase(SimpleTestCase): ...
9938866
import numpy as np def calib_err(confidence, correct, p='2', beta=100): # beta is target bin size idxs = np.argsort(confidence) confidence = confidence[idxs] correct = correct[idxs] bins = [[i * beta, (i + 1) * beta] for i in range(len(confidence) // beta)] bins[-1] = [bins[-1][0], len(confide...
9938871
from . import BatchSampler from paddorch.utils.data import IterableDataset import paddorch as torch import math import numpy as np class WeightedRandomSampler(BatchSampler): def __init__(self, weights,batch_size, num_samples=None, replacement=True): if num_samples is None: num_samples=len(weigh...
9938894
import unittest import orca from setup.settings import * from pandas.util.testing import * class SeriesTSRelatedTest(unittest.TestCase): def setUp(self): self.PRECISION = 5 @classmethod def setUpClass(cls): # connect to a DolphinDB server orca.connect(HOST, PORT, "admin", "123456") ...
9938909
r""" Consist of the functions for dealing labels for training. 1.Deal labels from xml to txt_yolo. 2.Classify datasets as train/val/test datasets. The format of dataset label: xml bbox is real from 1 to max. coco bbox is real from 0 to max. txt bbox is relative from 0 to 1. """ import json import random imp...
9938992
import numpy as np import numpy.testing as npt from aurora.nn.pyx.fast_pooling import max_pool_forward from aurora.nn.pyx.fast_pooling import max_pool_backward from aurora.nn.pyx.im2col import im2col from aurora.nn.pyx.im2col import col2im from tests.utils.gradient_check import gradient_check_numpy_expr # Testing Max...
9939006
import argparse import logging from typing import Tuple, Dict from nornir.core import InitNornir import setup # noqa from deployment import Deployment from utils import update_description, update_host_vars logger = logging.getLogger('lab_system.main') def convert_topology_arg(topology: str) -> Tuple[str, Dict[str...
9939062
from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function import logging import numpy as np import sys from collections import defaultdict from core.config import config as cfg from utils.localization_eval import all_localizati...
9939070
import datetime from django.core.urlresolvers import reverse from apps.canvas_auth.models import AnonymousUser from canvas.models import FollowCategory from canvas.tests.tests_helpers import CanvasTestCase, create_group, create_content, create_user, create_staff class TestUrls(CanvasTestCase): def test_non_exist...
9939076
import sys from attacks import Attacks def handle_attacks(credentials): """ awspx attacks """ include_conditional_attacks = False skip_attacks = [] only_attacks = [] max_attack_iterations = 5 max_attack_depth = None attacks = Attacks(skip_conditional_actions=include_conditional_a...
9939084
import argparse from pyrfsim import RfSimulator import numpy as np import h5py from scipy.signal import gausspulse from time import time import math import sys sys.path.append("../phantom_scripts") import bsplines description=""" Example script for demonstrating that the use of the spline- based simulation alg...
9939093
from .checks import * from ..config import * from ..pug import Pug from ..team import Team from ..utils import * @check(not_in_pug, not_a_captain, team_already_exists) async def rename(message, pugs, user_input, client): existing_pug.find_team(message.author).name = new_name await update_status(message....
9939102
import pickle import math import polyline import yaml geoCache = pickle.load(open('geoCache.p', 'rb')) directionsCache = pickle.load(open('directions.p','rb')) config = yaml.load(open("config.yml", 'r')) def getCoords(place): return geoCache[place] def getCoordString(place): return str(geoCache[pla...
9939126
from .corpus import Corpus from .ngram import Ngram from .voicebox import Voicebox from .voice import Voice