id
stringlengths
3
8
content
stringlengths
100
981k
3373174
from __future__ import print_function import logging logger = logging.getLogger(__file__) logging.basicConfig( format="[%(asctime)s - %(filename)s:line %(lineno)s] %(message)s", datefmt='%d %b %H:%M:%S') logger.setLevel(logging.INFO) import os import sys import numpy as np from keras.utils import generic_util...
3373214
import os import unittest from brazil_distrito_federal import distrito_federal _SOURCE_ID = "abc123" _SOURCE_URL = "https://covid19.ssp.df.gov.br/resources/dados/dados-abertos.csv?param=[random]" _PARSED_CASE = ({ "caseReference": { "sourceId": "abc123", "sourceUrl": "https://covid19.ssp.df.gov.br/...
3373222
try: VERSION = __import__('pkg_resources').get_distribution('fabric-bolt').version except Exception as e: VERSION = 'unknown'
3373233
import numpy as np import torch from itertools import compress, chain, product, combinations import networkx as nx def get_pairwise_scores(span_representations, clusters, pairwise_scorer): first, second = zip(*list(combinations(range(len(span_representations)), 2))) first, second = torch.tensor(first), torch....
3373241
import pandas as pd import numpy as np def create_table(n=7): df = pd.DataFrame({"x": range(1, 11), "y": n}) df['x*y'] = df.x * df.y return df
3373293
import pandas as pd import torch from torch.utils.data import Dataset import numpy as np from sustainbench.datasets.sustainbench_dataset import SustainBenchDataset from sustainbench.common.grouper import CombinatorialGrouper from sustainbench.common.utils import subsample_idxs, shuffle_arr import os import h5py from s...
3373350
import clr clr.AddReference("Aurora") clr.AddReference("System.Drawing") from Aurora import Global from Aurora.Settings import KeySequence, IEffectScript, VariableRegistry from Aurora.Devices import DeviceKeys from Aurora.EffectsEngine import EffectLayer from Aurora.Utils import RealColor from System.Drawing import C...
3373378
import basevcstest class TestVCSBoxfill(basevcstest.VCSBaseTest): def testBoxfillLev1Lev2Ext1(self): s = self.clt("clt", slice(0, 1), squeeze=1) b = self.x.createboxfill() b.level_1 = 20 b.level_2 = 80 b.ext_1 = "y" self.x.plot(s, b, bg=self.bg) self.checkIm...
3373382
import logging import syft as sy from syft.workers import WebsocketServerWorker import torch import argparse from torchvision import datasets from torchvision import transforms import numpy as np from syft.frameworks.torch.federated import utils from init import n_workers def get_dataset(worker_number:int): """ ...
3373391
from unittest import TestCase from unittest.mock import patch, PropertyMock, MagicMock from basketball_reference_web_scraper.html import PlayByPlayRow class TestPlayByPlayRow(TestCase): @patch.object(PlayByPlayRow, 'home_team_play_description', new_callable=PropertyMock) def test_is_home_team_play_when_home_...
3373402
from django.shortcuts import render_to_response from django.template import RequestContext def page(request): return render_to_response('page.html', locals(), context_instance=RequestContext(request))
3373421
import re import json import requests # from fake_useragent import UserAgent class Crawler: def __init__(self): self.base_url = 'https://minsu.meituan.com/gw/ugc/api/v1/product/comments?productId=%s&pageNow=%s&pageSize=1000' self.shop_id = None self.page_num = 1 self.info = {} de...
3373470
from collections import namedtuple SENSDICT = {"BFL": 0, "FL": 1, "LFKF": 2, "VX": 3, "LBK": 4} CSR = namedtuple("CSR", ["data", "indices", "indptr", "shape", "nnz"]) KMCRSV = 4294967295 # -1u, asking for reservoir kmeans++ sampling. __all__ = ["SENSDICT", "CSR", "KMCRSV"]
3373503
import argparse from inout import convert_sequence_to_hdf5, load_ply if __name__ == '__main__': parser = argparse.ArgumentParser( description='Import a sequence of PLY files and convert to HDF5 file format') parser.add_argument('input_filename_pattern', help='Input filename pat...
3373517
import numpy as np from collections import defaultdict, Counter import pickle import string import pprint import torch from torch.autograd import Variable import re PAD_TOKEN = '<pad>' UNK_TOKEN = '<unk>' ROOT_TOKEN = '<root>' RANDOM_SEED = 1 def parse_conllu(filename, clean=True): """ Par...
3373537
from markdown.extensions import Extension from .md_utils import TrivialTextPattern, MetadataAction # Markdown extension # ================== class MaybeEscapeDollar(MetadataAction): def available(self, meta): if 'formulas' not in meta or meta['formulas'] != ['False']: return # ESCAPE...
3373552
import torch import numpy as np from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers import AdamW, get_linear_schedule_with_warmup from sklearn.metrics import accuracy_score from tqdm import tqdm from loading import Loader, CustomerDataset, collate_fn from config import Param...
3373615
import os from api.config import config from flask.views import MethodView from flask import jsonify, make_response from flask_jwt_extended import jwt_required from api.helpers.log import ( fetch_all_project_logs, fetch_all_category_logs, fetch_all_user_logs, fetch_all_entity_logs, ) from api.middleware.projec...
3373625
import pickle import socket from shared.consts import HEADER_SIZE, PACKET_SIZE, MAX_PROBES def compose_message(data: dict): message = pickle.dumps(data) message = bytes(f"{len(message):<{HEADER_SIZE}}", 'utf-8') + message return message def get_message(connection: socket.socket, size: int, packet_size=...
3373636
import pickle from collections import OrderedDict from functools import wraps from typing import Union, Callable from .storage import SQLiteStorage MISS = object() def make_key(*args, **kwargs): if kwargs: return (args, *(x for kv in sorted(kwargs.items()) for x in kv)) else: return args d...
3373647
import json import time import pytest from plenum.test.helper import sdk_get_and_check_replies from plenum.test.pool_transactions.helper import sdk_sign_and_send_prepared_request from plenum.common.exceptions import RequestNackedException from plenum.common.constants import TXN_TYPE, AUDIT, CURRENT_PROTOCOL_VERSION f...
3373813
import collections import gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim USE_WANDB = False # if enabled, logs data on wandb server class ReplayBuffer: def __init__(self, buffer_limit): self.buffer = collections.deque(maxlen=buffer_li...
3373851
import unittest import unittest.mock as mock from unittest.mock import patch, AsyncMock, MagicMock, PropertyMock from homeassistant.helpers import entity_registry import aiounittest import sys import os import uuid import sleep_as_android sys.path.append(os.path.join(sys.path[0], "../../custom_components")) from sle...
3373879
import logging import common.ibc.processor import juno.constants as co import common.ibc.processor import common.ibc.handle from juno.config_juno import localconfig from settings_csv import JUNO_NODE def process_txs(wallet_address, elems, exporter): for elem in elems: process_tx(wallet_address, elem, expo...
3373904
from __future__ import print_function, with_statement, absolute_import import logging from cloudpickle import CloudPickler from ..clipper_admin import CLIPPER_TEMP_DIR import os import tempfile import sys cur_dir = os.path.dirname(os.path.abspath(__file__)) if sys.version_info < (3, 0): try: from cStringI...
3373986
from autodesk.application.autodeskservice import AutoDeskService from autodesk.application.deskservice import DeskService from autodesk.application.sessionservice import SessionService from autodesk.deskcontroller import DeskController from autodesk.hardware.noop import NoopPin from autodesk.lightcontroller import Ligh...
3374017
import datetime from walrus import * class TestHelper(object): def test_simple_string_ops(self): self.assertTrue(self.db.set('name', 'charlie')) self.assertEqual(self.db.get('name'), 'charlie') self.assertIsNone(self.db.get('not-exist')) self.assertFalse(self.db.setnx('name', 'hu...
3374020
import os import shutil import signal import tempfile import unittest from cate.util.web.serviceinfo import read_service_info from cate.util.web.webapi import find_free_port, WebAPI from cate.webapi.wsmanag import WebAPIWorkspaceManager from tests.core.test_wsmanag import WorkspaceManagerTestMixin _SERVICE_INFO_FILE ...
3374030
def test(): assert ( doc.text == "Ich mag niedliche Katzen und Faultiere." ), "Bist du dir sicher, dass du den Text korrekt verarbeitet hast?" assert ( niedliche_katzen == doc[2:4] ), "Bist du dir sicher, dass du die korrekte Span für niedliche_katzen ausgewählt hast?" assert ( ...
3374071
import os os.environ.setdefault("DJANGO_CONFIGURATION", "Prod") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "manager.settings") from django.core.asgi import get_asgi_application # noqa: E402 application = get_asgi_application()
3374090
from runtime import * """if not""" def main(): a = False b = False if not a: b = True assert( b == True ) a = 0 b = False if not a: b = True assert( b == True ) a = 0.0 b = False if not a: b = True assert( b == True ) a = None b = False if not a: b = True assert( b == True ) main()
3374094
from talon import Module, actions, imgui, Module, registry, ui mod = Module() mod.mode("help_search", "Mode for showing the search help gui") main_screen = ui.main_screen() search_text = None search_type = None @imgui.open(x=ui.main_screen().x) def gui(gui: imgui.GUI): gui.text(f"Search - {search_type}: {searc...
3374122
from django.test import TestCase from django.urls import reverse from wagtail.core.models import Page from wagtail.tests.utils import WagtailTestUtils from wagtailquickcreate.tests.standardpages.models import IndexPage class WagtailQuickCreateTests(TestCase, WagtailTestUtils): fixtures = ['wagtailquickcreate/te...
3374123
import os import pytest from django.core.management import call_command from opencivicdata.divisions import Division as FileDivision from opencivicdata.core.models import Division @pytest.mark.django_db def test_loaddivisions(capsys): assert Division.objects.count() == 0 call_command("loaddivisions", "in")...
3374125
import time import numpy as np import igraph from scipy.sparse import issparse def construct_graph(W, directed = False, adjust_weights = True): start_time = time.time() assert issparse(W) s, t = W.nonzero() w = W.data if not directed: idx = s < t s = s[idx] t = t[idx] w = w[idx] if adjust_weights:...
3374126
from __future__ import division import os from pyomo.environ import * from switch_model.financials import capital_recovery_factor as crf def define_arguments(argparser): argparser.add_argument('--demand-response-share', type=float, default=0.30, help="Fraction of hourly load that can be shifted to other ti...
3374167
import asyncio import json import os import uuid import random import aiofiles import aiohttp import warnings from bs4 import BeautifulSoup class TumblrImagesScraper: """This implementation is deprecated. You can contribute with your own implementation to keep this scraper alive""" def __init__(self): ...
3374178
import threading import os import shutil import sublime from .show_error import show_error from .console_write import console_write from .unicode import unicode_from_os from .clear_directory import clear_directory from .automatic_upgrader import AutomaticUpgrader from .package_manager import PackageManager from .pack...
3374184
import typing from dace import SDFG, SDFGState import dace.sdfg.nodes as nd from daceml.autodiff.backward_pass_generator import BackwardPassGenerator def add_backward_pass( sdfg: SDFG, state: SDFGState, outputs: typing.List[typing.Union[nd.AccessNode, str]], inputs: typing.List[typing.Union[nd.Acces...
3374254
from rx import Observable Observable.from_(["Alpha", "Beta", "Gamma", "Delta", "Epsilon"]) \ .map(lambda s: len(s)) \ .filter(lambda i: i >= 5) \ .subscribe(lambda value: print("Received {0}".format(value)))
3374285
import sys import struct import hashlib SEGS_MAX_SIZE = 0x9000 assert len(sys.argv) == 4 md5 = hashlib.md5() with open(sys.argv[3], 'wb') as fout: with open(sys.argv[1], 'rb') as f: data_flash = f.read() fout.write(data_flash) # First 4 bytes include flash size, etc. which may be change...
3374343
import numpy as np from PIL import Image src = np.array(Image.open('data/src/lena.jpg')) mask = np.array(Image.open('data/src/horse_r.png').resize(src.shape[1::-1], Image.BILINEAR)) print(mask.dtype, mask.min(), mask.max()) # uint8 0 255 mask = mask / 255 print(mask.dtype, mask.min(), mask.max()) # float64 0.0 1.0 ...
3374352
from pytest_requests import HttpRequest class ApiHttpBinGetRedirect302(HttpRequest): method = HttpRequest.EnumHttpMethod.GET url = "http://httpbin.org/redirect-to" params = { "url": "https://debugtalk.com", "status_code": 302 }
3374401
import struct from abc import ABCMeta, abstractmethod from typing import Tuple, Optional, List, Set, Union, NamedTuple, Deque from bxcommon import constants from bxcommon.messages.abstract_block_message import AbstractBlockMessage from bxcommon.messages.bloxroute import compact_block_short_ids_serializer from bxcommo...
3374433
from relational_erm.graph_ops.representations import edge_list_to_adj_list, redundant_edge_list_to_adj_list import networkx as nx import numpy as np import scipy as sp def is_connected(edge_list): V = np.unique(edge_list).shape[0] as_csr = sp.sparse.csr_matrix((np.ones_like(edge_list[:, 0]), (edge_list[:, 0],...
3374450
import pandas as pd def get_nonlinearity(db_path, channel): """ reads from a pandas hdf5 database """ if 'db' not in get_nonlinearity.__dict__: get_nonlinearity.db = pd.read_hdf(db_path, key="data") return (get_nonlinearity.db.loc[channel].nonlin1, get_nonlinearity.db.loc[channel].non...
3374457
import re try: # Block it from trying to import something which should not be on the python sys.path # https://github.com/hktonylee/SublimeNumberKing/issues/4 import expand_region_handler import utils except: from . import utils def expand_to_symbols(string, selection_start, selection_end): opening_symbol...
3374471
import requests import time def main(): with open("debug/urls_txt.txt", "r") as f: data = f.readlines() urls = data[-1000:] # import ipdb; ipdb.set_trace() for url in urls: id, url = url.split("\t") url = url.replace("\n", "") params = {'User-Agent' : "Mozilla/5.0 (Windows NT 10.0;...
3374500
import imageio from os import listdir from os.path import isfile, join from natsort import natsort images = [] PATH_TO_GIF = 'color-reduction.gif' PATH_TO_IMAGES = "Images/" filenames= [f for f in listdir(PATH_TO_IMAGES) if isfile(join(PATH_TO_IMAGES, f))] filenames = natsort.natsorted(filenames...
3374520
import logging from abc import ABC from os import path from jmeter_api.basics.element.elements import BasicElement from jmeter_api.basics.utils import Renderable, tree_to_str class BasicListener(BasicElement, ABC): def __init__(self, name: str = 'BasicElement', comments: str =...
3374666
from pathlib import Path import numpy as np if __name__ == "__main__": perms = [] for i in range(100): pp = np.random.permutation(27) # print(pp) for ref in perms: if (pp==ref).all(): print("REGENERATE!!!!") perms.append(pp) perms = np.stack(...
3374667
import torch from torch import nn import torch.nn.functional as F class KSSELayer(nn.Module): def __init__(self, in_chans, out_chans, ext_chans, min_ext_size=1, max_ext_size=17, use_bias=True): super().__init__() self.extractors = nn.ModuleList() for dilation in range(min_ext_size // 2, (m...
3374725
from typing import Callable, Tuple, TypeVar import jax.numpy as jnp from jax import jit, lax, random from jax_md import dataclasses, quantity, util, space Array = util.Array f32 = util.f32 T = TypeVar('T') ShiftFn = space.ShiftFn InitFn = Callable[..., T] ApplyFn = Callable[[T], T] Simulator = Tuple[InitFn, ApplyFn] ...
3374747
import xarray as xr try: from xarray import call_on_dataset except ImportError: def call_on_dataset(func, obj, name, *args, **kwargs): if isinstance(obj, xr.DataArray): ds = obj.to_dataset(name=name) else: ds = obj result = func(ds, *args, **kwargs) if...
3374750
from src.circuits.gate import Gate from queue import Queue # this file contains the circuit for one iteration of a support vector machine # here we use sub gradient descent # the circuit is represented via a python dictionary # each gate is given a unique ID and label # the unique ID for the gate will serve as its key...
3374752
class Node: def __init__(self, data = None, next=None): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def insert(self, data): newNode = Node(data) if(self.head): current = self.head while(current.next): current = current.nex...
3374831
import torch import torch.nn as nn class SCG_block(nn.Module): def __init__(self, in_ch, hidden_ch=6, node_size=(32,32), add_diag=True, dropout=0.2): super(SCG_block, self).__init__() self.node_size = node_size self.hidden = hidden_ch self.nodes = node_size[0]*node_size[1] ...
3374837
import argparse import torch import numpy as np import os import sys import time import math import json import logging from datetime import datetime from dataloader import DataLoader from model import CaptionModel, CrossEntropyCriterion from train import test import utils import opts import requests logger = logg...
3374870
import unittest import os from datetime import date from bs4 import BeautifulSoup from tests.test_abs_parser import ABS_FILES from browse.services.document.metadata import AbsMetaSession from browse.domain.license import ASSUMED_LICENSE_URI from browse.services.util.external_refs_cits import include_inspire_link, \ ...
3374881
from os import path, walk, rename, urandom, remove, rmdir from sys import argv from uuid import uuid4 ################################################################################ def main(): "Test arguments and either destroy path or print help." if len(argv) == 2 and path.isdir(argv[1]): destroy(...
3374899
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField from wtforms.validators import InputRequired class LoginForm(FlaskForm): username = StringField('Username', [InputRequired()]) password = PasswordField('Password', [InputRequired()]) keep_logged = BooleanField('Re...
3374910
import sys from phi.flow import * world.batch_size = 5 HOW_TO = """ Press 'Play' to continuously generate data until stopped. Each step computes one frame for each scene in the batch (batch_size=%d). The number of frames per simulation can be adjusted in the model parameters section. The text box next to 'Play' l...
3374914
import jinja2 import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../metricbeat/tests/system'))) from metricbeat import BaseTest as MetricbeatTest class AuditbeatXPackTest(MetricbeatTest): @classmethod def setUpClass(self): self.beat_name = "auditb...
3374917
import tornado.ioloop import tornado.web from controllers.account import LoginHandler from controllers.home import HomeHandler class MainHandler(tornado.web.RequestHandler): def get(self): # self.write("Hello, world") # self.render("main.html") self.redirect('http://www.baidu.com') setting...
3374935
from pkg_resources import Requirement, resource_filename MOVIE_NAME_14 = "m110818_075520_42141_c100129202555500000315043109121112_s1_p0" MOVIE_NAME_20 = "m130522_092457_42208_c100497142550000001823078008081323_s1_p0" MOVIE_NAME_21 = "m130731_192718_42129_c100564662550000001823085912221321_s1_p0" MOVIE_NAME_23 = "m1409...
3374947
from sys import stdin def bet(p): if p > 0.5: return 10000 + 10000 * (2 * p - 1) * (1 - p) return 10000 + 10000 * (1 - 2 * p) * p print "\n".join(str(bet(float(ln))) for i, ln in enumerate(stdin) if i)
3374979
from firebase_admin import auth from mapswipe_workers.auth import firebaseDB from mapswipe_workers.definitions import logger def update_username(uid): """Set username in Firebase DB based on auth.display_name for user id.""" fb_db = firebaseDB() try: user = auth.get_user(uid) username = u...
3375019
value = [1, 2, 3, 4, 5] key = ['a', 'b', 'c', 'd', 'e'] # 以给定内容为键,创建值为空的字典 dic = dict.fromkeys(key) print(dic) # 使用dict()根据给定的键、值创建字典 dic = dict(name = 'aa',age = 23) print (dic) # zip创建字典 dic = dict(zip(key, value)) print(dic) # 读取字典内容 print(dic.get('a'),dic['a']) # 字典中定义其它类型数据 dic['a']= [] dic['a'].append(12) di...
3375060
class Solution: # @param {integer} numCourses # @param {integer[][]} prerequisites # @return {boolean} def canFinish(self, numCourses, prerequisites): # try to do topological sort, if cannot finish, there is a loop in_edges = {} out_edges = {} nodes = [] for i in ...
3375073
from __future__ import (absolute_import, division, print_function, unicode_literals) from mpl_toolkits.axes_grid1.axes_divider import ( Divider, AxesLocator, SubplotDivider, AxesDivider, locatable_axes_factory, make_axes_locatable) from mpl_toolkits.axes_grid.axislines import Axes Loca...
3375096
import copy import torch from torch import nn from .pe import PositionalEncoding from .encoder_layer import EncoderLayer device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def get_padding_mask(seq: torch.Tensor, pad_idx: int = 0) -> torch.Tensor: """ Mask tokens that are pads (not pad: 1, ...
3375114
def is_security_scope(factor_type: str): return factor_type in ["phone", "mobile", "fax", "email", "id-no", "date-of-birth"]
3375167
import random MEMBER_SIZES = 3 with open("fp_profiling", "r") as fh: lines = [line.strip().split() for line in fh.readlines()] totals = {} lasts = {} for stamp, stage, token, module in lines: stamp = float(stamp) if token not in totals: totals[token] = (0, 0, 9999999999, 0, []) if stage == "S...
3375181
from nautobot.core.apps import NavMenuAddButton, NavMenuGroup, NavMenuItem, NavMenuImportButton, NavMenuTab menu_items = ( NavMenuTab( name="Organization", weight=100, groups=( NavMenuGroup( name="Tenancy", weight=300, items=( ...
3375237
import requests def baidu(question, answers): # 进行百度 url = 'https://www.baidu.com/s' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36' } data = { 'wd': question } res = requests.g...
3375241
import dill import numpy as np from abc import abstractmethod from abc import ABCMeta from typing import Any from typing import Dict from typing import List from typing import Type from typing import Union from ....misc.toolkit import WithRegister from ....misc.toolkit import check_available from ....misc.toolkit im...
3375243
import tvm import numpy as np from collections import OrderedDict from tvm.tensor_graph.core2.graph.abstract import Compute, FloatTensor from tvm.tensor_graph.core2.graph.concrete import Compute as concrete_compute from tvm.tensor_graph.core2.graph.concrete import FloatTensor as concrete_floattensor TEST_CASES = Ord...
3375247
from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .message import MessageProtocolEntity class TextMessageProtocolEntity(MessageProtocolEntity): ''' <message t="{{TIME_STAMP}}" from="{{CONTACT_JID}}" offline="{{OFFLINE}}" type="text" id="{{MESSAGE_ID}}" notify="{{NOTIFY_NAME}}"> ...
3375266
import logging import pkg_resources def add_config_arg(parser, nargs="*", **kwargs): """Add an argument to the parser to request a policy configuration.""" parser.add_argument( '-c', '--config', type=str, nargs=nargs, default=[pkg_resources.resource_filename(__name__, ...
3375267
from datetime import datetime from unittest import mock import pytest from airflow import DAG from airflow.exceptions import AirflowException, TaskDeferred from airflow.models.dagrun import DagRun from airflow.models.taskinstance import TaskInstance from airflow.utils.types import DagRunType from astronomer.providers...
3375284
import re from django.utils.encoding import force_text from django.core.exceptions import ValidationError class DomainNameValidator(object): """ Domain name validator adapted from Django's EmailValidator. """ message = 'Enter a valid domain name.' code = 'invalid' domain_regex = re.compile( ...
3375308
from insights.tests import context_wrap from insights.parsers.lvdisplay import LvDisplay LV_DISPLAY = """ Adding lvsapp01ap01:0 as an user of lvsapp01ap01_mlog --- Volume group --- VG Name vgp01app Format lvm2 Metadata Areas 4 Metadata Sequence No 56 VG Access ...
3375408
from os.path import isfile from os.path import join as pjoin from tempfile import TemporaryDirectory as InTemporaryDirectory import numpy.testing as npt from checkpoint import crypt def test_generate_key(): with InTemporaryDirectory() as tdir: key_name = 'secret_key.key' invalid_key = 'secret_ke...
3375428
from operator import methodcaller from telemetry_loader.streams.core import consumer from elasticsearch.helpers import expand_action from telemetry_loader.connections import connections_var chunk_size = 500 max_chunk_bytes = 100 * 1024 * 1024 @consumer async def load_elastic(it): client = connections_var.get()...
3375440
import os import pprint import shutil import pandas as pd from tqdm import tqdm, trange import numpy as np import torch import torch.nn.functional as F from common.utils.load import smart_load_model_state_dict from common.trainer import to_cuda from common.utils.create_logger import create_logger from vcr.data.build ...
3375449
from cpu import getCPU import sys def getCPUFlags(cpuName): cpu = getCPU(cpuName) return ' '.join(cpu.gccFlags) if __name__ == '__main__': if len(sys.argv) == 2: cpuName = sys.argv[1] try: print(getCPUFlags(cpuName)) except KeyError: print('Unknown CPU "%s"' % cpuName, file=sys.stderr) else: print(...
3375490
try: from setuptools import setup except ImportError: from distutils.core import setup with open("requirements.txt") as f: requirements = f.read().strip().split("\n") setup(name="edn_format", version="0.7.5", author="<NAME>", author_email="<EMAIL>", description="EDN format reader ...
3375510
from tools.tabla_tipos import * class symbol: def __init__(self, id_, tipo, datos): self.id_ = str(id_) self.tipo = str(tipo) self.datos = str(datos)
3375536
from array import array from random import random from math import sin import arcade import imgui from imflo.node import Node from imflo.pin import Input class MeterNode(Node): def __init__(self, page): super().__init__(page) self.values = array('f', [sin(x * 0.1) for x in range(100)]) se...
3375554
import os from contextlib import contextmanager @contextmanager def override_env(variable: str, value: str): """Context manager to temporarily override an environment variable. The variable is restored to its initial value (if any) when exiting the context. # Example ```python from bocadill...
3375565
from anago.utils import load_data_and_labels, load_glove, filter_embeddings from anago.models import ELModel, save_model, load_model from anago.preprocessing import ELMoTransformer from anago.trainer import Trainer from anago.tagger import Tagger from keras.optimizers import Adam from nerds.models import NERModel fro...
3375572
import io import os import cv2 import time from os.path import join from pytorchvideo.data.encoded_video import EncodedVideo from pytorchvideo.transforms.functional import uniform_temporal_subsample import decord import lmdb import imutils import json from pathlib import Path from ego4d.evaluation.sta_metri...
3375580
import komand from .schema import DeleteHostInput, DeleteHostOutput # Custom imports below class DeleteHost(komand.Action): def __init__(self): super(self.__class__, self).__init__( name="delete_host", description="Delete a host", input=DeleteHostInput(), o...
3375585
from nose2.tools import such with such.A("system") as it: @it.should("do something") def test(): pass it.createTests(globals())
3375587
from huobi.client.account import AccountClient from huobi.client.trade import TradeClient from huobi.constant import * from huobi.utils import * symbol_test = "eosusdt" account_id = g_account_id trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key) order_id = trade_client.create_order(symbol=symbol...
3375644
from datetime import date from io import StringIO import numpy as np import pandas as pd import pytest from pvoutput import pvoutput def test_date_to_pvoutput_str(): VALID_DATE_STR = "20190101" assert pvoutput.date_to_pvoutput_str(VALID_DATE_STR) == VALID_DATE_STR ts = pd.Timestamp(VALID_DATE_STR) a...
3375678
import logging from typing import TYPE_CHECKING, List, Optional from pysqlcipher3 import dbapi2 as sqlcipher from rotkehlchen.accounting.structures.base import HistoryBaseEntry from rotkehlchen.assets.asset import Asset from rotkehlchen.constants import ZERO from rotkehlchen.constants.limits import FREE_HISTORY_EVENT...
3375681
import re from typing import AnyStr, Iterable, List, Match from .Reader import Reader from .Snippet import Snippet from .snippetExceptions import \ SnippetAlreadyCloseException, \ SnippetAlreadyExistException, \ SnippetNotBeginException, \ SnippetNotEndWarning BEGIN_STATE = "begin" END_STATE = "end" S...
3375845
import inspect import sys from typing import Any, NamedTuple, Type if sys.version_info < (3, 8): from typing_extensions import get_args else: from typing import get_args import msgpack # type: ignore[import] from pydantic import BaseModel from xpresso import Request from xpresso.binders.api import SupportsE...
3375869
import platform import importlib import itertools def _not_implemented(*args, **kwargs): raise NotImplementedError("format not supported") def _init(): _platform_mod_name = '.' + platform.system() _platform_mod = importlib.import_module(_platform_mod_name, 'jaraco.clipboard') # support copy and pas...