id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3222780 | import numpy as np
x = np.linspace(-1, 1, 2000)
y = np.cos(x) + 0.3*np.random.rand(2000)
p = np.polynomial.Chebyshev.fit(x, y, 90)
t = np.linspace(-1, 1, 200)
plt.plot(x, y, 'r.')
plt.plot(t, p(t), 'k-', lw=3)
plt.show()
|
3222794 | r"""Order utilities for 0x applications.
Setup
-----
Install the package with pip::
pip install 0x-order-utils
Some methods require the caller to pass in a `Web3.BaseProvider`:code: object.
For local testing one may construct such a provider pointing at an instance of
`ganache-cli <https://www.npmjs.com/package... |
3222801 | from typing import List, Tuple, Union
import cv2
import numpy as np
from scipy import optimize
from color_tracker.utils.tracker_object import TrackedObject
def crop_out_polygon_convex(image: np.ndarray, point_array: np.ndarray) -> np.ndarray:
"""
Crops out a convex polygon given from a list of points from a... |
3222813 | import numpy as np
import tensorflow as tf
from tensorflow_similarity.samplers import TFRecordDatasetSampler
def _int64_feature(value):
"""Returns an int64_list from a bool / enum / int / uint."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def to_tfrecord(sid, value):
feature... |
3222850 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect as _inspect
from edward.models.random_variable import RandomVariable as _RandomVariable
from tensorflow.contrib import distributions as _distributions
# Automatically generate random variable c... |
3222879 | import FWCore.ParameterSet.Config as cms
process = cms.Process("MERGE")
process.source = cms.Source("EmptySource")
process.doit = cms.EDAnalyzer ("IntTestAnalyzer",
valueMustMatch = cms.untracked.int32(90),
moduleLabel = cms.untracked.InputTag("missing"))
process.maxEvents = cms.untracked.PSet(input = cms.untrac... |
3222894 | from setuptools import setup
with open('README.rst') as f:
long_description = f.read()
setup(
name='yweather',
version='0.1.1',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/tsroten/yweather',
description=('a Python module that provides an interface to the Yahoo! '
... |
3222902 | class FFNNModel():
def __init__(self, num_layers, hidden_size, out_size):
self.num_layers = num_layers
self.hidden_size = hidden_size
self.out_size = out_size
def train(self, dataloader):
a = str(dataloader)
res = f'Trained FFNN with hyperparameters LAYERS: {self.num_lay... |
3222929 | import pytest
import tempfile
import pathlib
import yaml
import subprocess
import os
import textwrap
import shutil
import numpy as np
import ase.io
import torch
from nequip.data import AtomicDataDict
from test_train import ConstFactorModel, IdentityModel # noqa
@pytest.fixture(
scope="module",
params=[
... |
3222937 | import scipy.io as sio
def load_annot(fname):
def parse_pose(dt):
res = {}
annot2 = dt['annot2'][0,0]
annot3 = dt['annot3'][0,0]
annot3_univ = dt['univ_annot3'][0,0]
is_valid = dt['isValidFrame'][0,0][0,0]
res['annot2'] = annot2
res['annot3'] = annot3
... |
3222939 | import pytest
from machinable.group import normgroup, resolve_group
def test_normgroup():
assert normgroup(None) == ""
assert normgroup("test") == "test"
assert normgroup("/test") == "test"
assert normgroup("/test/me") == "test/me"
assert normgroup("test/") == "test/"
with pytest.raises(Value... |
3222944 | import FWCore.ParameterSet.Config as cms
# Analyze and plot the tracking material
from SimTracker.TrackerMaterialAnalysis.trackingMaterialAnalyser_ForPhaseI_cfi import *
|
3222982 | import torch
import dgl.function as fn
import torch.nn as nn
import numpy as np
# from models.networks import *
OPS = {
'V_None' : lambda args: V_None(args),
'V_I' : lambda args: V_I(args),
'V_Max' : lambda args: V_Max(args),
'V_Mean' : lambda args: V_Mean(args),
'V_Min' : lambda args: V... |
3222985 | import gym
# TODO - "max_reward" as a name make sense?
class EarlyTerminationWrapper(gym.Wrapper):
"""
Wrapper that determines when to terminate the episode.
This currently just supports termination due to a reward cutoff,
but can be extended to take in a termination function in the future.
"""
... |
3222989 | import csv, MySQLdb
import sys
"""
The MIT License (MIT)
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation... |
3223019 | import json
import logging
import inspect
import io
import os
my_path = os.path.dirname(__file__)
def check_hashseed(desired_seed = 0):
if os.environ.get('PYTHONHASHSEED') != desired_seed:
info(f"Ideally set PYTHONHASHSEED={desired_seed} for perfect reproducibility")
return False
return True
... |
3223046 | from __future__ import absolute_import
from __future__ import print_function
import os
import sys
from conversion_imagenet import TestModels
def get_test_table():
return { 'tensorflow' :
{
# Cannot run on Travis since it seems to consume too much memory.
'nasnet-a_large' : [
... |
3223108 | from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import math
import torch
import torch.nn as nn
class _DynamicInputDenseBlock(nn.Module):
def __init__(self, conv_modules, debug):
super(_DynamicInputDenseB... |
3223123 | from __future__ import division
def humanize_bytes(n, precision=2):
# Author: <NAME>
# Licence: MIT
# URL: http://code.activestate.com/recipes/577081/
"""Return a humanized string representation of a number of bytes.
Assumes `from __future__ import division`.
>>> humanize_bytes(1)
'1 byt... |
3223145 | import os
import time
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
import torch.backends.cudnn as... |
3223163 | from django.contrib.auth import get_user_model
from rest_framework import serializers
UserModel = get_user_model()
class UserSerializer(serializers.ModelSerializer):
known_words = serializers.StringRelatedField(many=True, required=False)
unknown_words = serializers.StringRelatedField(many=True, required=Fals... |
3223203 | import numpy as np
from PIL import Image
#---------------------------------------------------------#
# 将图像转换成RGB图像,防止灰度图在预测时报错。
# 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB
#---------------------------------------------------------#
def cvtColor(image):
if len(np.shape(image)) == 3 and np.shape(image)[2] == 3:
... |
3223210 | import os
from tqdm import trange
import torch
from torch.nn import functional as F
from torch import distributions as dist
from src.common import (
compute_iou, make_3d_grid, add_key,
)
from src.utils import visualize as vis
from src.training import BaseTrainer
class Trainer(BaseTrainer):
''' Trainer object f... |
3223251 | import heapq
import math
class Solution:
def minimumDeviation(self, nums: List[int]) -> int:
pq = []
minNum = math.inf
for num in nums:
if num & 1:
num *= 2
heapq.heappush(pq, -num)
minNum = min(minNum, num)
minDev = math.i... |
3223278 | import os
import sys
from fastapi_websocket_rpc import logger
from fastapi_websocket_rpc.rpc_channel import RpcChannel
# Add parent path to use local src as package for tests
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import asyncio
from multiprocessing import Process
i... |
3223344 | import collections
import glob
import os
import pickle
import re
import numpy as np
import scipy.stats as stats
from nasbench_analysis.eval_darts_one_shot_model_in_nasbench import natural_keys
def parse_log(path):
f = open(os.path.join(path, 'log.txt'), 'r')
# Read in the relevant information
train_accu... |
3223443 | import ast
from typing import Dict, List
from boa3.model.builtin.interop.nativecontract.Neo.getneoscripthashmethod import NeoContract
from boa3.model.builtin.interop.nativecontract.nativecontractmethod import NativeContractMethod
from boa3.model.type.itype import IType
from boa3.model.variable import Variable
class ... |
3223451 | from pathlib import Path
import abc
import inspect
import time
import tensorflow as tf
from synethesia.framework.model_skeleton import Model
class SessionHandler(object):
def __init__(self, model, model_name, checkpoint_dir="./checkpoints", logdir="./logs", max_saves_to_keep=5):
if not isinstance(model... |
3223460 | from rlbot_gui import gui
# This is a useful way to start up RLBotGUI directly from your bot project. You can use it to
# arrange a match with the settings you like, and if you have a good IDE like PyCharm,
# you can do breakpoint debugging on your bot.
if __name__ == '__main__':
gui.start()
|
3223515 | from octis.models.model import AbstractModel
import numpy as np
from gensim.models import hdpmodel
import gensim.corpora as corpora
import octis.configuration.citations as citations
import octis.configuration.defaults as defaults
class HDP(AbstractModel):
id2word = None
id_corpus = None
use_partitions = ... |
3223520 | import os
import logging
from .log_formatter import LogFormatter
m_logger = None
def setLogger(logger):
global m_logger
m_logger = logger
def getLogger():
global m_logger
if m_logger is None:
return logging.getLogger()
else:
return m_logger
def setup_logging(cfg, app_name):
... |
3223544 | from pybamm import exp, constants
def electrolyte_conductivity_Ramadass2004(c_e, T):
"""
Conductivity of LiPF6 in EC:DMC as a function of ion concentration.
Concentration should be in dm3 in the function.
References
----------
.. [1] <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. "Development of... |
3223641 | import os
import json
import functools
import logging
import platform
import copy
from .exceptions import (
SaveWarningExc
)
from .constants import (
M_OVERRIDEN_KEY,
M_ENVIRONMENT_KEY,
METADATA_KEYS,
SYSTEM_SETTINGS_KEY,
PROJECT_SETTINGS_KEY,
PROJECT_ANATOMY_KEY,
DEFAULT_PROJECT_KEY
)... |
3223652 | import inspect
import re
from strawberry import object_type
from strawberry.auto import StrawberryAuto, auto
from strawberry.enum import EnumDefinition
from strawberry.field import StrawberryField
from strawberry.schema.name_converter import NameConverter
from strawberry.types.fields.resolver import StrawberryResolver... |
3223679 | import enum
import time
from datetime import timedelta
from uuid import uuid4
import boto3
from celery.decorators import periodic_task
from celery.schedules import crontab
from django.conf import settings
from django.core.files.storage import default_storage
from django.core.mail import EmailMessage
from django.templa... |
3223682 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import paddle
import paddle.fluid as fluid
from src.utils.config import cfg
from src.models.libs.model_libs import scope, name_scope
from src.models.libs.model_libs import bn, bn_relu, relu, FC... |
3223750 | from ramda.pair import pair
from ramda.private.asserts import *
def pair_test():
assert_equal(pair("foo", "bar"), ["foo", "bar"])
|
3223760 | import numpy as np
from ..computation import Graph, Transformer, Constant
from .statistics import ArgMin, ArgMax
from .util import apply_to_axis
__all__ = [
'HasDuplicate',
'HasDuplicateMin',
'HasDuplicateMax',
'NumberUniqueValues',
'SumReoccurringDataPoints',
'SumReoccurringValues',
]
class... |
3223761 | from setuptools import setup
setup(name="Prosodylab-Aligner",
version="2.0",
description="Forced alignment with HTK",
author="<NAME>",
author_email="<EMAIL>",
url="http://github.com/kylebgorman/Prosodylab-Aligner/",
install_requires=["PyYAML >= 3.11",
"scipy... |
3223771 | import logging
import time
import pytest
import zenko_e2e.conf as conf
from kubernetes import client, config
from kubernetes.client.rest import ApiException
from ..fixtures import *
from .. import util
_log = logging.getLogger('cosmos') # pylint: disable=invalid-name
MD5_HASHES = {
"file1": "b781c1f5179214f6d7f3... |
3223783 | from setuptools import setup, find_packages
setup(
name = 'summa',
packages = find_packages(exclude=['test']),
package_data = {
'summa': ['README', 'LICENSE']
},
version = '1.2.0',
description = 'A text summarization and keyword extraction package based on TextRank',
long_descriptio... |
3223813 | from propara.data.proglobal_dataset_reader import ProGlobalDatasetReader
from allennlp.common.testing import AllenNlpTestCase
class TestDataReader(AllenNlpTestCase):
def test_read_from_file(self):
sc_reader = ProGlobalDatasetReader()
dataset = sc_reader.read('tests/fixtures/proglobal_toy_data.tsv... |
3223900 | import pba
from pba_plot import minmaxmean
# x= 0.5
# y = 0.1
# if pba.norm(0.5, 0.1) < 0.5: print(pba.norm(0.5, 0.1) < 0.5)
counter_strict =[]
counter_poss = []
pba.mmms(10, 50, 40, 6.2)
pba.mmms(5,10,7.5, 8)
b= minmaxmean(5, 10, 7.5)
b.show() |
3223910 | from pyids.algorithms.optimizers.rs_optimizer import RSOptimizer
from ...data_structures.ids_ruleset import IDSRuleSet
import math
import numpy as np
import logging
class SLSOptimizer:
def __init__(self, objective_function, objective_func_params, optimizer_args=dict(), random_seed=None):
self.delta = 0.3... |
3223912 | import random
from eth2spec.test.context import (
ForkMeta,
ALTAIR,
with_presets,
with_fork_metas,
)
from eth2spec.test.helpers.constants import (
ALL_PRE_POST_FORKS,
MINIMAL,
)
from eth2spec.test.helpers.fork_transition import (
do_fork,
transition_until_fork,
transition_to_next_epo... |
3224031 | from kivy.properties import StringProperty
from answer_widgets import SymbolTableAnswerWidget
from task_widgets.task_base.intro_hint import IntroHint
from utils import SYMBOLS_ALPHABET, import_kv
from .find_in_table import FindInTable, FindInTableDescriptionWidget
import_kv(__file__)
class IntroHintFindSymbol(Intro... |
3224061 | from cleo.io.inputs.argument import Argument
from .command import Command
class ListCommand(Command):
name = "list"
description = "Lists commands."
help = """\
The <info>{command_name}</info> command lists all commands:
<info>{command_full_name}</info>
You can also display the commands for a speci... |
3224073 | from prml.nn.array.array import Array
from prml.nn.config import config
import numpy as np
def ones(size):
return Array(np.ones(size, dtype=config.dtype))
|
3224086 | from typing import Callable
from rx.core import Observable
def _as_observable() -> Callable[[Observable], Observable]:
def as_observable(source: Observable) -> Observable:
"""Hides the identity of an observable sequence.
Args:
source: Observable source to hide identity from.
... |
3224137 | from scheduler.exceptions import KubeHTTPException
from scheduler.resources import Resource
from scheduler.utils import dict_merge
class Service(Resource):
short_name = 'svc'
def get(self, namespace, name=None, **kwargs):
"""
Fetch a single Service or a list
"""
url = '/namesp... |
3224141 | from setuptools import setup, find_packages
setup(name="billots",
version="0.1.1",
description="Official project of billots.org cryptocurrency.",
keywords="billots cryptocurrency billot",
url="https://github.com/billychasen/billots",
author="<NAME>",
author_email="<EMAIL>",
li... |
3224153 | from __future__ import absolute_import
from .attention import *
from .core import *
from .wrappers import *
|
3224252 | import requests
from configure import BAIDU_API_KEY,BAIDU_APP_ID,BAIDU_SECRET_ID
from aip import AipImageClassify, AipOcr
class ImageClassify:
def __init__(self,app_id,api_key,secret_key):
self.image_client = AipImageClassify(app_id,api_key,secret_key)
self.words_client = AipOcr(app_id,api_key,sec... |
3224292 | class TypeRegistry:
def __init__(self):
self.data = {}
def registry(self, model_cls, record_type):
self.data[model_cls] = record_type
def __iter__(self):
return self.data.items().__iter__()
def __getitem__(self, item):
return self.data[item]
def get_type(self, obj... |
3224300 | from typing import Union, Set, Tuple, List
from shapely.geometry import Polygon, MultiPolygon
from h3 import h3
MultiPolyOrPoly = Union[Polygon, MultiPolygon]
def _extract_coords(polygon: Polygon) -> Tuple[List, List[List]]:
"""Extract the coordinates of outer and inner rings from a Polygon"""
outer = list(p... |
3224344 | from abc import abstractmethod
from utils import Shell
from nodes import WorkerNode
class Operator(object):
def __init__(self, shell: Shell):
self._shell = shell
@abstractmethod
def _turn_on(self, nodes: list):
raise NotImplementedError
@abstractmethod
def _turn_off(self, nodes... |
3224359 | import json
from youtube_search import YoutubeSearch
# Gets yt link of given query.
async def song_search(event, query, max_results, details=False):
try:
results = json.loads(YoutubeSearch(query, max_results=max_results).to_json())
except KeyError:
return await eor(event, "Unable to find rele... |
3224362 | from WMCore.WebTools.RESTModel import RESTModel, restexpose
from cherrypy import HTTPError
import unittest, logging, json
from WMQuality.WebTools.RESTServerSetup import cherrypySetup, DefaultConfig
from WMQuality.WebTools.RESTClientAPI import makeRequest, methodTest
class REST_Exceptions_t(RESTModel):
def __init__... |
3224415 | from moviepy import *
from moviepy.video.tools.segmenting import find_objects
# Load the image specifying the regions.
im = ImageClip("../../ultracompositing/motif.png")
# Loacate the regions, return a list of ImageClips
regions = find_objects(im)
# Load 7 clips from the US National Parks. Public Domain :D
clips =... |
3224470 | from rest_api.models import ErrorResponse
def handle_invalid_request(error):
return __generate_error_response(error, 400)
def handle_internal_error(error):
return __generate_error_response(error, 500)
def __generate_error_response(error, status_code):
return ErrorResponse(msg=str(error), status_code=s... |
3224472 | from io import StringIO
from itertools import zip_longest
from typing import TypeVar
from lft.event import EventSystem, Event
from lft.event.mediators import DelayedEventMediator, TimestampEventMediator, JsonRpcEventMediator
T = TypeVar("T")
def test_event_system():
results = []
event_system = EventSystem(... |
3224503 | import datetime
import hashlib
import json
import logging
import calendar
from construct import (Struct, Bytes, Const, Int16ub, Int32ub, GreedyBytes,
Adapter, Checksum, RawCopy, Rebuild, IfThenElse,
Default, Pointer, Pass, Enum)
# for debugging parsing
# from construct im... |
3224601 | import h5py
import numpy as np
x = []
y = []
hdf5_file = h5py.File('all_data.hdf5', "r")
data = hdf5_file["sim_data"][:, ...]
hdf5_file.close()
print(data.shape)
for i in range(data.shape[0]):
for j in range(data.shape[1]-1):
x.append(data[i, j, ...])
y.append(data[i, j+1, ...])
train_shape = (len(... |
3224604 | import operator as op
import pytest
from sweetpea import fully_cross_block
from sweetpea.primitives import Factor, DerivedLevel, WithinTrial
from sweetpea.design_partitions import DesignPartitions
color = Factor("color", ["red", "blue"])
text = Factor("text", ["red", "blue"])
congruency = Facto... |
3224633 | from collections import defaultdict, Counter
import random
from math import log
from itertools import repeat
import sys
class MarkovModel(object):
"""
High-order Markov model of string sequences.
Args:
order (int): the desired order of the Markov model.
Returns:
an instance of MarkMod... |
3224637 | import json
import networkx as nx
from typing import List, Set, Tuple
from nltk.corpus import stopwords
from collections import defaultdict, Counter
def tuple_contains(tup1: Tuple, tup2: Tuple) -> Tuple[bool, int]:
"""Check whether tuple 1 contains tuple 2"""
len_tup1, len_tup2 = len(tup1), len(tup2)
for ... |
3224638 | import os
import torch
import codecs
import gensim
import logging
import numpy as np
import pandas as pd
from collections import Counter
from gensim.models.keyedvectors import KeyedVectors
from nltk.corpus import stopwords
class Dictionary( object ):
"""
from_embedding: Initializes vocab from embedding file. ... |
3224646 | from keras.layers import concatenate
from keras import optimizers
from keras.callbacks import EarlyStopping, ModelCheckpoint
import numpy as np
import json
from sanspy.utils import get_df, alias, mem_usage
from sanspy.callbacks import SaveHistoryEpochEnd
class Model(object):
"""
Model class as a wrapper for Keras. C... |
3224664 | import unittest
import responses
from connectedcar import connectedcar, const
class Testconnectedcar(unittest.TestCase):
def setUp(self):
self.client_id = 'apiKey'
self.client_secret = "clientSecret"
self.redirect_uri = "redirectUri"
self.scope = ['profile']
self.client =... |
3224696 | from django import template
from oms_cms.backend.pages.models import Pages, BlockPage
register = template.Library()
@register.simple_tag(takes_context=True)
def for_pages(context):
"""Вывод страниц"""
return Pages.objects.filter(published=True, lang=context["request"].LANGUAGE_CODE)
@register.simple_tag(t... |
3224698 | import tensorflow as tf
from tensorflow.keras import Input
from tensorflow.keras.layers import Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import regularizers
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from graphgallery.nn.layers.tensorflow import GCNConv
f... |
3224727 | from dataclasses import dataclass, field
from typing import List
from torch import nn
@dataclass
class TrainingWMArgs:
trigger_words: List = field(default_factory=lambda: ['default'])
poisoned_ratio: float = field(default=0.3)
keep_clean_ratio: float = field(default=0.3)
ori_label: int = field(defau... |
3224756 | r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
3224768 | from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from hubspot.cms.hubdb.api.rows_api import RowsApi
from hubspot.cms.hubdb.api.rows_batch_api import RowsBatchApi
from hubspot.cms.hubdb.api.tables_api import TablesApi
|
3224808 | import json
import logging
import time
from calendar import timegm
from time import sleep
import click
import pause
import pyautogui
import pyfiglet
from pywinauto import keyboard
# Teams could be started from script, but requires change owner permissions. Better to launch Teams 2.0 first and
# then set the focus to ... |
3224816 | import sys
import os
import numpy as np
import pickle
import h5py
if __name__ == "__main__":
__package__ = "modules.alt_splice"
### local imports
from .verify import *
from .write import *
from ..rproc import rproc, rproc_wait
from ..helpers import compute_psi, codeUTF8
def _prepare_count_hdf5(options, OUT, even... |
3224826 | import argparse
from corpus_readers import PandasBasedCorpus
import json
from cv_utils import CVManager, run_cv_evaluation
from global_constants import *
import os
from collections import defaultdict
from gram_matrix_extractors import compute_default_predefined_coling_gram_matrices
from corpus_readers import unpickle_... |
3224843 | import json
from collections import defaultdict
import matplotlib.pyplot as plt
with open("/home/aistudio/work/PCB_DATASET/Annotations/train.json") as f:
data = json.load(f)
imgs = {}
for img in data['images']:
imgs[img['id']] = {
'h': img['height'],
'w': img['width'],
'area': img['hei... |
3224851 | from __future__ import division
import sys
from pprint import pprint as pp
import requests
import re
import string
import operator
import getopt
import time
class hist():
def __init__(self, data):
self.mi = float(data['m'])
self.ma = float(data['M'])
self.num = int(data['n'])
self.d... |
3224861 | import mmcv
import numpy as np
import trimesh
from os import path as osp
def _write_ply(points, out_filename):
"""Write points into ``ply`` format for meshlab visualization.
Args:
points (np.ndarray): Points in shape (N, dim).
out_filename (str): Filename to be saved.
"""
N = points.s... |
3224873 | from brownie import Contract
from cachetools.func import ttl_cache
from yearn.cache import memory
from yearn.multicall2 import fetch_multicall
from yearn.prices import magic
@memory.cache()
def is_balancer_pool(address):
pool = Contract(address)
required = {"getCurrentTokens", "getBalance", "totalSupply"}
... |
3224891 | from __future__ import print_function
def pretty_print_examples(examples):
for example in examples:
for lang in example:
print(lang, example[lang])
print()
|
3224927 | import threading
class SyncedThread(threading.Thread):
def __init__(self, target, args=(), kwargs={}):
self._end = threading.Event()
self._start = threading.Event()
def _target(*args, **kwargs):
with target(*args, **kwargs):
self._start.set()
s... |
3224939 | import numpy as np
import cv2
import torch
class _DetectorBase:
def __init__(self, cfg):
self.cfg = cfg
@staticmethod
def cv2torch(cv_kpt: cv2.KeyPoint, pnt_3d: bool) -> torch.Tensor:
pnt = (
torch.ones((3, 1), dtype=torch.float)
if pnt_3d
else torch.on... |
3224967 | import pytest
from plenum.common.constants import STEWARD_STRING, VALIDATOR
from pytest import fixture
from plenum.common.throughput_measurements import RevivalSpikeResistantEMAThroughputMeasurement
from plenum.common.util import getMaxFailures
from plenum.test.helper import sdk_send_random_and_check, assertExp, sdk_g... |
3224968 | import logging
from django_rq import job
from extras.enums import LogLevel
from .sync import PeeringDB
logger = logging.getLogger("peering.manager.peeringdb.jobs")
# One hour timeout as this process can take long depending on the host properties
@job("default", timeout=3600)
def synchronize(job_result):
job_r... |
3225024 | import aceutils
aceutils.cdToScript()
aceutils.mkdir('../Doxygen')
aceutils.cd(r'../Doxygen/')
aceutils.call(r'doxygen ../Script/Doxyfile_cpp_XML') |
3225029 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression, LassoCV, RidgeCV
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.metric... |
3225034 | from aiohttp import web
import asyncio
import asyncio.tasks
import datetime
import functools
import logging
import itertools
import typing
import json
from ..models import Update
from ..utils import helper
DEFAULT_WEB_PATH = '/webhook'
DEFAULT_ROUTE_NAME = 'webhook_handler'
BOT_DISPATCHER_KEY = 'BOT_DISPATCHER'
RESP... |
3225037 | from tdw.controller import Controller
from tdw.tdw_utils import TDWUtils
from time import sleep
from platform import system
"""
Create a fluid "container" with the NVIDIA Flex physics engine. Run several trials, dropping ball objects of increasing mass into the fluid.
"""
class FlexFluid(Controller):
... |
3225104 | import argparse
import logging
import multiprocessing
import time
from functools import partial, update_wrapper
from defaults import EXTRACTION_MAX_READ_PAIRS, EXTRACTION_MAX_NM, EXTRACTION_MAX_INTERVAL_TRUNCATION, EXTRACTION_TRUNCATION_PAD
import pysam
compl_table = [chr(i) for i in xrange(256)]
compl_table[ord('A')... |
3225144 | import os
from pathlib import Path
import tempfile
import h5py
from hexrd.ui.image_stack_dialog import ImageStackDialog
import numpy as np
from PySide2.QtCore import QEvent, QObject, Qt, QThreadPool, Signal, QTimer
from PySide2.QtWidgets import (
QApplication, QDockWidget, QFileDialog, QInputDialog, QMainWindow,
... |
3225150 | from __future__ import generator_stop
from collections import OrderedDict, deque, ChainMap
from collections.abc import Iterable
import uuid
from .utils import (normalize_subs_input, root_ancestor,
separate_devices,
Msg, ensure_generator, single_gen,
short_uid... |
3225153 | def get_progress_bar_string(
done, total, prefix="", suffix="", decimals=1, length=100, fill="█"
):
percent = ("{0:." + str(decimals) + "f}").format(100 * (done / float(total)))
filledLength = int(length * done // total)
bar = fill * filledLength + "-" * (length - filledLength)
return f"{prefix}|{ba... |
3225171 | from geoscript.util import xml
from org.locationtech.jts.geom import GeometryCollection
def writeKML(g, format=True, xmldecl=False, namespaces=True):
"""
Writes a geometry object as KML.
*format* specifies whether to format or pretty print the result.
*xmldecl* specifies whether to include the XML declaratio... |
3225190 | import pprint
from typing import Optional, List, Tuple, Set, Dict
import numpy as np
from overrides import overrides
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from python import SENTENCE_IDX
from python.handwritten_baseline import SENTENCE_EMBEDDINGS
from python.handwritten_b... |
3225200 | try:
from fs.googledrivefs import GoogleDriveFS
from google.oauth2.credentials import Credentials
except ImportError:
GoogleDriveFS = None
from ._pyfilesystem2 import PyFilesystem2FilesSource
class GoogleDriveFilesSource(PyFilesystem2FilesSource):
plugin_type = 'googledrive'
required_module = Goo... |
3225243 | ALTERNATIVE_TRACK_NAMES = [
['Allan Scott Park Morphettville', 'Morphettville', 'Morphettville Parks'],
['Ararat', 'NMIT Ararat Park', 'Wimmera@Ararat'],
['Beaumont', 'Beaumont Newcastle'],
['Canberra', 'Canberra Acton'],
['Canterbury', 'Canterbury Park'],
['Devonport Synthetic', 'Devonport Tape... |
3225267 | from unimodals.common_models import LeNet, MLP, Constant
from private_test_scripts.all_in_one import all_in_one_train, all_in_one_test
import torch
from torch import nn
from datasets.avmnist.get_data import get_dataloader
from fusions.common_fusions import Concat, MultiplicativeInteractions2Modal
from training_structur... |
3225321 | from django.utils.translation import ugettext_noop as _
from api import status
from api.api_views import APIView
from api.exceptions import ObjectNotFound, PreconditionRequired, ObjectAlreadyExists
from api.task.response import SuccessTaskResponse
from api.utils.db import get_object
from api.dc.storage.serializers imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.