id
stringlengths
3
8
content
stringlengths
100
981k
9835201
import numpy as np from discretize.base import BaseRectangularMesh, BaseTensorMesh from discretize.operators import DiffOperators, InnerProducts from discretize.mixins import InterfaceMixins, TensorMeshIO from discretize.utils import mkvc from discretize.utils.code_utils import deprecate_property class TensorMesh( ...
9835208
import binascii import struct class MCB: """Motion Control Bus (MCB) is a high-speed serial protocol designed for getting low latency and high determinism in motion control systems where control loops work at high update rates (tens of kHz). """ EXTENDED_MESSAGE_SIZE = 8 def __init__(self): ...
9835216
import os.path import h5py import numpy as np import multiprocessing import threading import queue import warnings from . import utils class Distributor: """Base class for Distributors. A `Distributor` is an object that should receive the input data from a Device, e.g. a plotter or a file writer. Refer ...
9835280
import functools from typing import Callable, Sequence def sequence_not_empty(fn: Callable[..., bool]) -> Callable[..., bool]: """Decorator to exclude empty series""" @functools.wraps(fn) def inner(sequence: Sequence, *args, **kwargs) -> bool: if not any(True for _ in sequence): retur...
9835303
try: import mayaHooks.override.dagMenuProc import pdil.tool.animDagMenu mayaHooks.override.dagMenuProc.callback_customDagMenu.register(pdil.tool.animDagMenu.animationSwitchMenu) except Exception: import traceback print( traceback.format_exc() ) print( "See above error text, something w...
9835313
from pygmy.exception.error import PygmyExcpetion class URLAuthFailed(PygmyExcpetion): """Secret key is invalid or not present.""" def __init__(self, url): self.url = url def __str__(self): return "Invalid/missing secret key for protected url"
9835319
from typing import Dict, Any, List import dpath.util from checkov.terraform.context_parsers.base_parser import BaseContextParser class VariableContextParser(BaseContextParser): def __init__(self) -> None: definition_type = "variable" super().__init__(definition_type=definition_type) def _c...
9835333
import os from nonebot.plugin import get_loaded_plugins from src.utils.log import logger class PluginBase(): ''' 插件管理器,基础类 ''' module_name: str ''' 模块名 ''' plugin_name: str ''' 插件名 ''' plugin_command: str ''' 插件命令 ''' plugin_usage: str ''' 插件说明 ...
9835363
from sparrow_cloud.access_control.base_access_control import BaseAccessControl class ExampleAccessControl(BaseAccessControl): """访问控制资源 每个资源由用字典组成: 名称规范: 资源名称需要以permission_开头, 否则不会注册, 例如: permission_Example1 资源key必须为: resource_code 资源描述key必须为: desc 示例: ...
9835374
del_items(0x800A1B30) SetType(0x800A1B30, "char StrDate[12]") del_items(0x800A1B3C) SetType(0x800A1B3C, "char StrTime[9]") del_items(0x800A1B48) SetType(0x800A1B48, "char *Words[118]") del_items(0x800A1D20) SetType(0x800A1D20, "struct MONTH_DAYS MonDays[12]")
9835406
import os from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from typing import List, Any, Union from funcy import contextmanager from steem import Steem from steemdata.helpers import simple_cache, create_cache from steemdata.markets import Markets usernames_cache = create_c...
9835460
import torch import torch.multiprocessing as mp import utils from trainer import Trainer from utils import dist_init def main(): parser = utils.prepare_parser() parser = utils.add_dgp_parser(parser) config = vars(parser.parse_args()) utils.dgp_update_config(config) print(config) rank = 0 ...
9835470
import radiotap as r def test_ac_rate_1(): """ Frame 1: 4865 bytes on wire (38920 bits), 188 bytes captured (1504 bits) Radiotap Header v0, Length 38 Header revision: 0 Header pad: 0 Header length: 38 Present flags MAC timestamp: 270036265 Flags: 0x40 Channel frequency: 5180 [A 36] ...
9835475
import pytest import torch from neurodiffeq import diff from neurodiffeq.losses import _losses as losses N = 100 def pde_system(u, v, w, x, y): return [ diff(u, x, order=2) + diff(u, y, order=2), diff(v, x, order=2) + diff(v, y, order=2), diff(w, x, order=2) + diff(w, y, order=2), ] ...
9835549
import json import urllib import urllib2 import os.path import sys sys.path.append("./") import iprep_conf def getresult(key): parameters = { "ip" : key, "apikey": iprep_conf.vt_key} print parameters try: data = urllib.urlencode(parameters) req = urllib2.Reque...
9835562
from . import train from . import test from . import data from ..yolo import misc import numpy as np
9835575
from typing import Dict, Callable, List, Union from abc import ABC, abstractproperty from collections import Counter from .vault import Vault from .frames import frame_manager from .parameters import get_dotted Metadata = Dict[str, Union[str, List[Dict]]] class Syntax: def __init__(self, required, optional=No...
9835583
import json TAGGING_RECTIFIER_DICTIONARY = './Dictionaries/tagging_recitifier_dictionary.json' DBPEDIA_PROPERTY_RECTIFIER_DICTIONARY = './Dictionaries/dbpeida_property_rectifier_dictionary.json' KEY_WORD_RECTIFIER_DICTIONARY = './Dictionaries/key_word_rectifier_dictionary.json' def read_file(file_path): with open(...
9835617
import time from datetime import datetime, timedelta, timezone import mysql.connector from multiprocessing import Pool import random from decimal import Decimal import config ######################################################################################################################## # PROCEDURES: # Step 1:...
9835623
import sys import datetime as dt import pandas as pd import numpy as np # scikit-learn classifiers. from sklearn.linear_model import SGDClassifier from sklearn.qda import QDA from sklearn.lda import LDA from sklearn.preprocessing import StandardScaler from stormtracks.results import StormtracksResultsManager, Result...
9835677
from datetime import datetime, timezone from enum import Enum from typing import Any, Dict, Optional from ..utils import _get_as_snowflake from .base import Object, Snowflake from .user import User __all__ = ('IntegrationExpire', 'IntegrationAccount', 'IntegrationApplication') class IntegrationExpire(Enum): REM...
9835715
from PyPDF4 import PdfFileMerger import os merger = PdfFileMerger() files = ['report1.pdf', r'C:\Users\Srinjoy\Desktop\pdf merger\report2.pdf'] for file in files: bookmarkName = os.path.basename(file) merger.append(file, bookmark= bookmarkName) merger.write('result.pdf') merger.close()
9835757
from __future__ import print_function import struct from mapproxy.cache.base import tile_buffer from mapproxy.image import ImageSource class MetaTileFile(object): def __init__(self, meta_tile): self.meta_tile = meta_tile def write_tiles(self, tiles): tile_positions = [] count = len(til...
9835783
from __future__ import absolute_import, division, print_function, unicode_literals from unittest import TestCase from beast.util import String from beast.util import Terminal Terminal.CAN_CHANGE_COLOR = False class String_test(TestCase): def test_comments(self): self.assertEqual(String.remove_comment(''), '')...
9835786
import json import psycopg2 from pathlib import Path import xml.etree.ElementTree as et import os import argparse import wget import csv import subprocess from time import time # I guess I shouldn't set password here? CONNECTION = "postgres://username:password@localhost:30003/pss_database" TABLENAME = 'oltpbench_resul...
9835811
import json import os import pytest from click.testing import CliRunner from agent import di from agent.api import main DUMMY_DESTINATION_OUTPUT_PATH = '/output' TEST_DATASETS_PATH = '/home' INPUT_FILES_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'input_files') @pytest.fixture(scope="session") ...
9835847
import os from run_cmds import run_cmds __author__ = 'abhigyan' def cp_scripts_configs(user, ssh_key, ns_ids, lns_ids, remote_folder, config_file, workload_config_file, node_config_folder, remote_node_config_file): """ #!/bin/sh user=$1 ssh_key=$2 pl_ns=$3 pl_lns=$4 ...
9835865
import unittest from ctypes import * from asp.codegen.ctypes_converter import * def normalize(a): return ''.join(a.split()) class BasicConversionTests(unittest.TestCase): def test_int_field(self): class Foo(Structure): _fields_ = [("x", c_int), ("y", c_int)] self.asser...
9835874
import asyncio import inspect from contextvars import ContextVar from typing import Type, Dict, Union, Optional, NoReturn, List from pydantic import BaseModel from fastapi_event.base import BaseEvent from fastapi_event.exceptions import ( InvalidEventTypeException, InvalidParameterTypeException, EmptyCont...
9835897
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import seaborn as sns # Function to help plotting the results of our cross-validation for the random forest algorithm. def triple_ticker_grid(tuned_parameters, parameter_1, parameter_2, parameter_3): ticker_labels = [] for i in tuned_...
9835927
from backtester.trading_system_parameters import TradingSystemParameters from datetime import timedelta from backtester.dataSource.yahoo_data_source import YahooStockDataSource from backtester.dataSource.nse_data_source import NSEStockDataSource from backtester.executionSystem.simple_execution_system import SimpleExecu...
9835953
import os from shutil import copyfile, copytree from django.contrib.auth import get_user_model from django.db import connection from django.template import Context, Template from django.test import TestCase as BaseTestCase from django.test.client import RequestFactory from mezzanine.conf import settings from mezzanin...
9835969
def make_shirt(size_shirt, title_shirt): """Display information about a pet.""" print("\nTalla " + size_shirt + ".") print("Titulo " + title_shirt.title() + ".") make_shirt('Mediana', '<NAME>')
9835983
from rtcbot import Microphone, Speaker import asyncio import logging logging.basicConfig(level=logging.DEBUG) m = Microphone() s = Speaker() s.playStream(m) async def testme(): await asyncio.sleep(5) s.stop() m.unsubscribe() asyncio.ensure_future(testme()) asyncio.get_event_loop().run_forever()
9835996
from typing import TypedDict __all__ = ('WsConnectionInfo',) class WsConnectionInfo(TypedDict): url: str
9836035
import numpy as np import pytest from sklearn.linear_model import LogisticRegression from feature_selection_ga import FeatureSelectionGA, FitnessFunction MODEL = LogisticRegression() @pytest.mark.parametrize( "model, features, target", [(MODEL, np.array([[0, 0], [0, 1], [1, 0], [1, 1]]), np.array([0, 0, 1, ...
9836069
from __future__ import annotations import sys from json.decoder import JSONDecodeError from typing import Any import requests from ikea_api._constants import DEFAULT_HEADERS from ikea_api.exceptions import GraphQLError, IKEAAPIError, UnauthorizedError if sys.version_info < (3, 8): from typing_extensions import ...
9836099
import pytest import numpy as np def test_ImageArrayUInt8ToFloat32(): from batchup.image.utils import ImageArrayUInt8ToFloat32 x = np.array([[0, 127, 255], [30, 60, 90]], dtype=np.uint8) xf32 = x.astype(np.float32) * np.float32(1.0 / 255.0) assert x.shape == (2, 3) x_wrapped = ImageArrayUInt8To...
9836103
from flask_unchained import AppFactoryHook, Bundle, FlaskUnchained from typing import * from ..bundle_blueprint import BundleBlueprint # FIXME test template resolution order when this is used in combination with # RegisterBlueprintsHook class RegisterBundleBlueprintsHook(AppFactoryHook): """ Registers a bun...
9836150
import json import sys import csv import math def main(): json_file = sys.argv[1] sa_obj = {} with open(json_file) as f: sa_obj = json.load(f) outputs = [] inputs = [] for v in sa_obj["output_variables"]: outputs.append(v["variable_name"]) for v in sa_obj["input_variable...
9836162
import json import time # This class reads server configuration file and initializes server's variables class initialize_server(): file_password = '<PASSWORD>' duration = '02:00' #Default Value config = '' def get_password(): initialize_server.read_config() return initialize_server.file_password def get_dur...
9836171
import click from .main import get from .brownfield_vms import get_brownfield_vms from .utils import FeatureFlagGroup from calm.dsl.log import get_logging_handle LOG = get_logging_handle(__name__) @get.group("brownfield", cls=FeatureFlagGroup) def brownfield_get(): """Get brownfield items""" pass @brownf...
9836211
from datetime import datetime, timedelta from freezegun import freeze_time from tenant_schemas_celery.cache import SimpleCache def test_cache_get_should_return_default_value_if_key_doesnt_exist(): cache = SimpleCache() expected_value = object() actual_value = cache.get("something-non-existant", expecte...
9836228
import FWCore.ParameterSet.Config as cms # This is an ugly hack (but better what was before) to record if the # loadDigiAliases() was called with premixing or not. Unfortunately # which alias to use depends on that. If we had a premixing Modifier, # this hack would not be needed. _loadDigiAliasesWasCalledPremix = None...
9836231
import requests, hashlib, mimetypes, json, datetime from flask import current_app from app.config import Config def sha256_checksum(fileobj, block_size=65536): sha256 = hashlib.sha256() for block in iter(lambda: fileobj.read(block_size), b''): sha256.update(block) fileobj.seek(0) return sha2...
9836265
import os import sys import torch import cflearn from cflearn.misc.toolkit import eval_context from cflearn.misc.toolkit import download_reference # prepare folder = os.path.dirname(__file__) repo_name = "U-2-Net-master" repo_path = os.path.join(folder, repo_name) os.system("wget https://github.com/xuebinqin/U-2-Net...
9836278
import tensorflow as tf import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np from custom_ops.custom_ops_factory import zero_out_channels with tf.Session(''): A = np.ones((1, 3, 3, 5)) channels = [True, False, True, True, True] B = zero_out_channels(A, channels) print B ...
9836281
import numpy as np import torch import json import os from scipy.sparse import csr_matrix, save_npz import numba as nb from xclib.utils.sparse import _map def save_predictions(preds, result_dir, valid_labels, num_samples, num_labels, get_fnames=['knn', 'clf', 'combined'], pre...
9836318
from app.schemas.api_key import APIKey, RevokeOrActivateAPIKey from app.schemas.certificate import Certificate from app.schemas.classification import Classification from app.schemas.dns_record import BaseDnsRecord, DnsRecord from app.schemas.domain import Domain from app.schemas.file import File from app.schemas.har im...
9836341
import torch # import torchvision import torchvision.models as models import torch.nn as nn import torch.nn.functional as F import numpy as np from visual_net import resnet18 def batch_organize(out_match_posi, out_match_nega): # audio B 512 # posi B 512 # nega B 512 out_match = torch.zeros(out_match...
9836358
import json import pytest import requests_mock from furl import furl from unittest.mock import Mock, patch from apex_legends import ApexLegends from apex_legends.base import Client from apex_legends.domain import Platform, Player api = ApexLegends('apikey') BASE_URL = Client.BASE_URL @pytest.fixture() def mock(): ...
9836396
print('www.geekdigging.com') print("www.geekdigging.com") print('小明说:"吃了吗?"') print("小明说:\"吃了吗?\"") print(''' 这是一个多行字符串的实例 多行字符串可以使用制表符 TAB ( \t )。 也可以使用换行符 [ \n ]。 ''') print('I \nlike Python!') print("") print('I\tlike\tPython!') print("横向制表符:\\t") print(r"横向制表符:\t") print(len('I like P...
9836397
class TestImports(object): def test_imports(self): import torch # workaround for TLS error from solaris.utils import core, geo, config, tile, cli from solaris import data from solaris.vector import polygon, graph, mask from solaris.tile import raster_tile, vector_tile ...
9836417
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) count=dict() lines=list() for line in handle: line=line.rstrip() if not line.startswith("From"): continue if not line.startswith("From:"): continue else: words=line.split() lines.ap...
9836419
import unittest from smtm import SimulationTrader from unittest.mock import * class SimulationTraderIntegrationTests(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_ITG_simulation_trader_full(self): trader = SimulationTrader() end_date = "2020-...
9836422
import requests import personaje import database def obtener_personaje(): r = requests.get('https://rickandmortyapi.com/api/character/') texto = r.json() paginas = texto['info']['pages'] db = database.basedatos() db.crear_tabla_personajes() for i in range(1,paginas+1): r = requests.ge...
9836438
import json import attr import pytest @attr.s class Quantity: value = attr.ib() unit = attr.ib() @attr.s class Pipe: length = attr.ib() diameter = attr.ib() class JSONSerializer: def serialize_quantity(self, quantity: Quantity) -> str: ... return json.dumps(attr.asdict(quanti...
9836449
import json from kivy.clock import Clock from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager import utils utils.load_kv("root.kv") class Root(ScreenManager): """ The Root (or Assembler) of the App. """ def __init__(self, **kwargs): super().__init__(**kwargs) ...
9836489
def handle(user): from core.models import Controller, ControllerSite, ControllerUser, User from collections import defaultdict # user = User.get(user_id) controller_users = ControllerUser.objects.filter(user=user) existing_controllers = [cu.controller for cu in controller_users] all_contro...
9836494
import pytest from factiva.core import UserKey, const from factiva.core.tools import load_environment_value from factiva.news.snapshot import Snapshot, SnapshotQuery # TEST DATA. Fill out these values with valid data # Environment values are loaded for automated testing. ENVIRONMENT_USER_KEY = load_environment_value(...
9836518
import argparse import json from prism import Prism def main(args): metric = Prism(model_dir="../m39v1", lang=args.language) candidates = [] references = [] sources = [] with open(args.input_file, "r") as f: for line in f: data = json.loads(line) candidates.appen...
9836523
from datetime import datetime from django.contrib.postgres.search import SearchQuery, SearchRank from django.db import connection, models from django.db.models.expressions import F from django.test import TestCase from django.test.utils import isolate_apps from tsvector_field.query import Headline from tsvector_field...
9836544
import requests # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''IceWarp Mail Server Directory Traversal''', "description": '''IceWarp Mail Server versions prior to 11.1.1 suffer from a directory traversal vulnerability.''', "severity": "high", "refe...
9836589
from queue import Queue class ResManager: def __init__(self, max_size=4096) -> None: super().__init__() self._queue = Queue(max_size) def get_task(self): return self._queue.get() def put_task(self, url): self._queue.put(url) res_manager = ResManager(max_size=4096)
9836636
class Response: json_key: str def __init__(self): self._text = str() def say(self, text_or_ssml: str): self.text = text_or_ssml def reprompt(self, text_or_ssml: str): print("Reprompt of bixby not yet implemented") @property def text(self) -> str: return self._...
9836645
import random import logging from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol import conf from rpc import RndServiceApi, RndNodeApi logger = logging.getLogger(__name__) def getPlowConnection(host=None, port=None): available = [h.split(":"...
9836667
import sys sys.path.append('../py') from iroha import * from iroha.iroha import * d = IDesign() mod = IModule(d, "mod") tab = ITable(mod) st0 = IState(tab) tab.initialSt = st0 st1 = IState(tab) st2 = IState(tab) st3 = IState(tab) tab.states.append(st0) tab.states.append(st1) tab.states.append(st2) tab.states.append(s...
9836682
from django.contrib.gis.geos import Point from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "OLD" addresses_name = "2021-03-25T12:33:04.363809/Oldham Democracy_Club__06May2021.tsv" stations_name = "2021-03-25T1...
9836702
try: from cStringIO import StringIO as BytesIO except: # Python 3 from io import BytesIO import numpy as np import PIL.Image import shutil from math import sqrt from skimage.transform import rescale, resize, downscale_local_mean from skimage.exposure import adjust_gamma def save_image_array(img, filename, res...
9836719
from setuptools import find_packages, setup setup( version="1.2.1", name="pymeteosource", packages=find_packages(), install_requires=["wheel", "requests", "pytz"], extras_require={"pandas": "pandas"}, description="Meteosource API wrapper library", author="Meteosource", author_email="<E...
9836742
import contextlib import tempfile import shutil import os from pandas.api.types import is_numeric_dtype import numpy as np import cooler @contextlib.contextmanager def isolated_filesystem(): """A context manager that creates a temporary folder and changes the current working directory to it for isolated file...
9836790
class attrdict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self class LazyImport: def __init__(self, *args): self.args = args def __getattr__(self, attr): self.__dict__ = __import__(*self.args).__dict__ return self.__dict__[attr] def lazy_import(names)...
9836793
from status import Status import psutil from collections import namedtuple statistic_tuple = namedtuple('statistic', ['mean', 'stddev', 'max']) class HostStatus(Status): """ Extension of Status , to store additional information used by hosts. """ def __init__(self, start): super(HostSt...
9836809
import io import unittest from unittest.mock import patch, Mock from then.configs.yaml import parse_yaml from then.exceptions import ConfigError class TestYaml(unittest.TestCase): @patch('yaml.load') def test_parse(self, m): parse_yaml(Mock()) m.assert_called_once() def test_exception(se...
9836833
import json import os current_dir = os.path.dirname(__file__) def open_data(name): return open(os.path.join(current_dir, '../data/out.{}'.format(name)), 'r', encoding='utf-8') with open_data('word_langs.json') as f: word_langs_idx = json.load(f) with open_data('word_meanings.json') as f: word_meanings...
9836853
from decimal import Decimal from uuid import uuid4 import pytest from toy import fields from toy.exceptions import ValidationException from toy.resources import Resource def test_basic_uuid_field(): field = fields.UUIDField(name='uuid') uuid = uuid4() field.value = uuid assert field.name == 'uuid'...
9836919
import os import numpy as np import random import torch.nn.functional as F from torch.autograd import Variable import torch import torch.utils.data as dataf import torch.nn as nn import matplotlib.pyplot as plt from scipy import io from sklearn.decomposition import PCA # setting parameters DataPath = '/home/hrl/Pychar...
9836928
import random print ('Game Hack The Old Terminal!') random.seed() wordSize = 3; variants = 9; word = ''; words = list() if wordSize <= 1 or variants <= 1 or variants % wordSize > 0 : print('Wrong parameters of word size or variants.') quit() i = 0; asciiA = 97; asciiZ = 122 while i < wordSize : word += chr(random.r...
9836929
from distutils.core import setup setup(name='parasbolv', version='1.0.0', description='A lightweight Python library designed to simplify the rendering of ' + 'highly-customisable SBOL Visual glyphs and diagrams', author='<NAME>, <NAME>, <NAME>', author_email='<EMAIL>, <EMA...
9836935
from celery.task import task import time @task def add(x, y): print("Got add()") return x + y @task def add_delayed(x, y): print("Got add_delayed()") time.sleep(1) print("Woke up from add_delayed()") return x+y @task def fail(): print("Got fail()") raise Exception @task def delay...
9836951
import pytest from httoop import URI, Body, Date, Headers, Method, Protocol, Request, Response, Status from httoop.gateway.wsgi import WSGIBody from httoop.messages.message import Message from httoop.uri.http import HTTP, HTTPS from httoop.uri.schemes import FTP, IMAP, LDAP, MMS, NFS, GitSSH, SvnSSH @pytest.mark.par...
9837001
import os import yaml import uf3 from uf3.util import user_config def test_type_check(): assert type(user_config.type_check(1.0, False)) == bool assert type(user_config.type_check(1.0, 2)) == int assert type(user_config.type_check(3, 4.0)) == float assert type(user_config.type_check("5", 6)) == int ...
9837007
from typing import Union import numpy as np from numpy import ndarray from sklearn.preprocessing import MaxAbsScaler, MinMaxScaler from pickle import dump as pkl_dump, load as pkl_load from json import dump as json_dump, load as json_load from bayesian_mmm.utilities.utilities import check_ndarray_is_matrix class Nor...
9837022
from .AsyncComponent import AsyncComponent from .CollapseComponent import CollapseComponent from .DelayedEventComponent import DelayedEventComponent from .FragmentComponent import FragmentComponent from .MyPersistedComponent import MyPersistedComponent from .MyPersistedComponentNested import MyPersistedComponentNested ...
9837054
import numpy as np class TruncatedSVD: def __init__(self, n_components: int = 2): self.n_components = n_components self.Sigma = None self.U = None self.VT = None def fit(self, X): self.U, self.Sigma, self.VT = np.linalg.svd(X) self.VT = self.VT.T # 此句为修复语句,但不明...
9837058
import time def speed_test(slow_func, fast_func, *func_inputs): start_ = time.time() res1 = slow_func(*func_inputs) end_ = time.time() print("Elapsed (without numba jit) = %s" % (end_ - start_)) # DO NOT REPORT THIS... COMPILATION TIME IS INCLUDED IN THE EXECUTION TIME! start = time.time() ...
9837067
from allauth.socialaccount.providers.github.provider import GitHubProvider class CustomGitHubProvider(GitHubProvider): package = "metaci.oauth2.github" provider_classes = [CustomGitHubProvider]
9837086
from docker import errors as docker_errors import logging import components import driver_base from tools.minicluster import client log = logging.getLogger(__name__) class MiniClusterDriver(driver_base.ClusterDriverABC): """ Driver to make failure-testing framework work with a Peloton cluster set up on ...
9837099
import logging import tornado.web import tornado.gen import tornado.iostream import sentry_sdk from waterbutler import tasks from waterbutler.server import utils from waterbutler.core import exceptions logger = logging.getLogger(__name__) class BaseHandler(utils.CORsMixin, utils.UtilMixin, tornado.web.RequestHand...
9837115
import _img def load_png(_file, background=False): png = _img._PngLoader(_file) if background: png.load_in_background() return png return png.load_all() def load_jpeg(_file, background=False): jpeg = _img._JpegLoader(_file) if background: jpeg.load_in_background() ...
9837206
from unicodedata import category from django.core.management.base import BaseCommand, CommandError from workflows.models import Category, AbstractWidget, AbstractInput, AbstractOutput, AbstractOption from django.core import serializers from optparse import make_option import uuid class Command(BaseCommand): ...
9837227
import open3d as o3d import argparse import os import sys import copy import logging import numpy import numpy as np import torch import torch.utils.data import torchvision from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from tqdm import tqdm # Only if the files are in example folder. BA...
9837238
from numba import cuda, njit from numba.core.extending import overload from numba.cuda.testing import CUDATestCase, skip_on_cudasim, unittest import numpy as np # Dummy function definitions to overload def generic_func_1(): pass def cuda_func_1(): pass def generic_func_2(): pass def cuda_func_2():...
9837253
from __future__ import absolute_import import logging from itertools import imap from kafka.consumer.simple import SimpleConsumer from kafka.client import KafkaClient from pgshovel.replication.validation import validate_state from pgshovel.interfaces.streams_pb2 import Message from pgshovel.streams.utilities import ...
9837255
import os import sys import glob import shutil import argparse import mv3dhelper import zrpc import time def help_information(): print('Usage: python run_multicam_extrin_calib.py <workspace_folder> <dataset_folder> <cam_num> <output_folder> ') def merge_undist_cam_folders(undist_cam_folder_list, merged_undist_c...
9837299
import numpy as np import matplotlib.pyplot as plt def compute_value_function(num_states, action_range): """ Computes the value function for the 1000 state random walk as described in Sutton and Barto (2017). :return: The value function for states 1 to 1000. Index 0 is not used in this array (i.e. should ...
9837392
from os import listdir from os.path import isfile, isdir, join, splitext import sys import time import datetime import calendar def dateToTimestamp(format, date): return calendar.timegm(time.strptime(date, format)) args = sys.argv[1:] mainFolder = args[0] maxUsers = int(args[1]) maxDate = time.strptime(args[2], ...
9837476
def min_days_bloom2(roses, k, n): r_sorted = sorted([(x, i) for i, x in enumerate(roses)], reverse=True) d = {} while r_sorted: x, i = r_sorted.pop() if i-1 in d and i+1 in d: start = d.pop(i-1) end = d.pop(i+1) d[start] = end d[end] = start ...
9837550
PHONE_FORM_CONSTANTS = { 'ISD_Code':{ 'max_length': 5, "data-dojo-type": "dijit.form.ValidationTextBox", "data-dojo-props": r"'required' :'true' ,'regExp':'[\\d]+','invalidMessage':'Invalid Character' " }, 'STD_Code':{ 'max_length': 6, ...
9837626
import sys import re import json import os file_name = 'src/main/resources/files/accepted_words.txt' def read_json_file(file_path): data = None with open(file_path, 'r') as f: data = json.load(f) return data def read_common_words(file_path): common_words = set() with open(file_path, 'r') ...