id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3287698 | import base64
import requests
from kairos_face import exceptions
from kairos_face import settings
from kairos_face.utils import validate_file_and_url_presence, validate_settings
_verify_base_url = settings.base_url + 'verify'
def verify_face(subject_id, gallery_name, url=None, file=None, additional_arguments={}):
... |
3287705 | import sys
import py
import pypy
pytest_plugins = "pytester"
def setpypyconftest(testdir):
path = str(py.path.local(pypy.__file__).dirpath().dirpath())
testdir.makeconftest("""
import sys
sys.path.insert(0, %r)
from pypy.conftest import *
""" % path)
def test_pypy_collection(testd... |
3287720 | from PATHS import *
import pandas as pd
import json
def get_movie_ids():
return json.load(open(movielens_match_movieid))
def get_ratings():
df = pd.read_csv(movie_lens_title_path, chunksize=200000, low_memory=False, encoding="ISO-8859-1")
return df
def map_titles():
ids = sorted(get_movie_ids())
cntr = 0
for... |
3287729 | import os
import sys
import glob
import toml
from importlib import import_module
import re
import math
import colorsys
import webcolors
from pathlib import Path
from robosat_pink.tiles import tile_pixel_to_location, tiles_to_geojson
#
# Import module
#
def load_module(module):
module = import_module(module)
... |
3287744 | import json
from csv import DictReader as cdr
"""
# Data processing steps
This script was used to process a few xlsx files to look at expediture data
based on income and region
- source: http://www.bls.gov/cex/
- files under Region of residence by income before taxes:
- xregnmw.xlsx
- xregnne.xlsx
- xregns.xls... |
3287759 | import os
import re
import six
import base64
import hashlib
import functools
import warnings
from os.path import isabs, abspath
from zope.interface import Interface, Attribute, implementer
from twisted.internet import defer
from twisted.python import log
from txtorcon.util import find_keywords, version_at_least
from... |
3287773 | import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("zerver", "0030_realm_org_type"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrat... |
3287875 | from __future__ import unicode_literals
import datetime
import decimal
import json
from collections import OrderedDict
from django.contrib.auth import get_permission_codename
from django.contrib.auth.decorators import login_required
from django.core.exceptions import FieldDoesNotExist
from django.core.exceptions imp... |
3287890 | import pytest
import numpy as np
from sklearn.datasets import load_iris
from sknet.network_construction import KNNConstructor
from sknet.unsupervised import StochasticParticleCompetition
@pytest.fixture
def X_y_generator():
X, y = load_iris(return_X_y=True)
y = np.array(y, dtype='float32')
return X, y... |
3287926 | import math
import moderngl_window
class BasicWindowConfig(moderngl_window.WindowConfig):
"""Minimal WindowConfig example"""
gl_version = (3, 3)
title = "Basic Window Config"
def __init__(self, **kwargs):
super().__init__(**kwargs)
def render(self, time, frametime):
... |
3287936 | import pickle
import sqlite3
import numpy as np
import os
# 로컬 디렉토리에서 HashingVectorizer를 임포트합니다
from vectorizer import vect
def update_model(db_path, model, batch_size=10000):
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute('SELECT * from review_db')
results = c.fetchmany(batch_size)
... |
3287988 | from unittest import mock
import pytest
from binderhub.ratelimit import RateLimiter, RateLimitExceeded
def test_rate_limit():
r = RateLimiter(limit=10, period_seconds=60)
assert r._limits == {}
now = r.time()
reset = int(now) + 60
with mock.patch.object(r, "time", lambda: now):
limit = r... |
3288000 | import io
from typing import BinaryIO, Type, TypeVar, TYPE_CHECKING
_T_SizedBytes = TypeVar("_T_SizedBytes", bound="SizedBytes")
def hexstr_to_bytes(input_str: str) -> bytes:
"""
Converts a hex string into bytes, removing the 0x if it's present.
"""
if input_str.startswith("0x") or input_str.startswi... |
3288019 | from ptypes import *
from . import art,graph
from . import *
import operator,functools,itertools
import logging
ptypes.setbyteorder(ptypes.config.byteorder.littleendian)
pbinary.setbyteorder(ptypes.config.byteorder.littleendian)
@Record.define
class BIFF5(ptype.definition):
type, cache = '.'.join([__name__, 'BIF... |
3288023 | from collections import defaultdict
from urllib.parse import urlencode
from flask import g, Flask
import settings
from godmode.acl import ACL
from godmode.models import models, model_map, model_hash
def init_templates(app: Flask):
app.context_processor(godmode_context_processor)
app.add_template_filter(no_e... |
3288028 | import numpy as np
import random
import pandas as pd
import keras
from keras import backend as K
from keras import layers
from keras.datasets import mnist
from keras.datasets import cifar10
from keras.utils import np_utils
from sklearn.model_selection import train_test_split
# IP Address: 172.16.17.32
# User: dbAdmi... |
3288046 | from itertools import izip
import numpy as np
import theano
import theano.tensor as tt
def select_theano_act_function(name, dtype=theano.config.floatX):
"""
Given the name of an activation function, returns a handle for the corresponding function in theano.
"""
if name == 'logistic':
clip = ... |
3288114 | import unittest
import xml.etree.ElementTree as etree
from typing import Optional
from supplement_xml.supplement_xml import elm_to_obj
from supplement_xml.supplement_xml import obj_to_elm
class Test1:
aaa: str
bbb: int
ccc: float
dddd = 0
class Test2:
aaa: str = 'test2'
b... |
3288115 | from coldtype.test import *
from coldtype.midi.controllers import LaunchControlXL
@test((1000, 300))
def test_system_font(r):
return DATText("Hello, world!", Style("Times", 100, load_font=0, fill=0), r.offset(100, 100))
@test((1000, 300), rstate=1)
def test_return_string(r, rs):
ri = r.inset(30)
sx, sy = ... |
3288138 | import numpy as np
import segmentation_models
from farmer.ncc.optimizers import AdaBound
from farmer.ncc import losses, models
from ..model.task_model import Task
from tensorflow import keras
import tensorflow_addons as tfa
class BuildModelTask:
def __init__(self, config):
self.config = config
def... |
3288180 | def onValueChange(channel, sampleIndex, val, prev):
op('tex3d_captures').par.replaceindex = val
op('tex3d_captures').par.resetsinglepulse.pulse()
|
3288238 | from unittest import TestCase
from unittest.mock import Mock
from app.core.config import ProfileGroup
from tests.test_data.test_accounts import get_test_group, get_test_group_no_default
class TestProfileGroup(TestCase):
def setUp(self):
self.profile_group = ProfileGroup('test', get_test_group())
def... |
3288415 | import midi
# Instantiate a MIDI Pattern (contains a list of tracks)
pattern = midi.Pattern()
# Instantiate a MIDI Track (contains a list of MIDI events)
track = midi.Track()
# Append the track to the pattern
pattern.append(track)
# Instantiate a MIDI note on event, append it to the track
on = midi.NoteOnEvent(tick=0, ... |
3288423 | import logging
import re
from discord import CustomActivity
from bot.plugins.base import BasePlugin
from bot.plugins.commands import command
from .models import GameStatus
logger = logging.getLogger(__name__)
class Plugin(BasePlugin):
has_blocking_io = True
@command(pattern=re.compile(r'(?P<status>.+)',... |
3288427 | import functools
from importlib import import_module
from django.core.exceptions import ViewDoesNotExist
from django.utils.module_loading import module_has_submodule
@functools.lru_cache(maxsize=None)
def get_callable(lookup_view):
"""
Return a callable corresponding to lookup_view.
* If lookup_view is a... |
3288434 | import discord
from discord.errors import InvalidArgument
from redbot.core import commands, Config, checks
from redbot.core.utils.menus import DEFAULT_CONTROLS, menu
class NonNitroEmoji(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, identifier=345... |
3288440 | import json
import demistomock as demisto
from CommonServerPython import *
"""
Use the IvantiHeatCreateProblemExample script to create a problem object (JSON) in Ivanti Heat.
The script gets the arguments required to create the problem, such as category, subject, and so on.
It creates the JSON object and sets it insi... |
3288491 | vkin = open("pysnark_vk", "r")
vkout = open("verification_key.json", "w")
print('{', file=vkout)
print(' "protocol": "groth16",', file=vkout)
print(' "curve": "bn128",', file=vkout)
def process_g2(nm, fin, fout, skipcomma=False):
a1=list(map(lambda x:x.strip(),next(fin).split(" ")))
a2=list(map(lambda x:x.str... |
3288506 | import argparse
import base64
import sys
from base64 import b64decode as b64decodeValidate
from base64 import encodebytes as b64encodebytes
from timeit import default_timer as timer
import pybase64
def bench_one(duration, data, enc, dec, encbytes, altchars=None, validate=False):
duration = duration / 2.0
if... |
3288533 | import torch
import torch.nn as nn
class G12(nn.Module):
# Convert MNIST to SVHN
def __init__(self, depth=64):
super(G12, self).__init__()
# Encoding Layer
self.conv1 = nn.Sequential(nn.Conv2d(1, depth, kernel_size=4, stride=2, padding=1),
nn.BatchNor... |
3288553 | from setuptools import setup
setup(name='cleese',
version='0.1.0',
install_requires=['numpy', 'scipy'])
|
3288573 | from django.dispatch import receiver
from django.db import transaction
from baserow.contrib.database.table import signals as table_signals
from baserow.contrib.database.api.tables.serializers import TableSerializer
from baserow.ws.tasks import broadcast_to_group
@receiver(table_signals.table_created)
def table_crea... |
3288591 | import unittest
from sacrerouge.common.testing.util import sacrerouge_command_exists
class TestMultiLing2011Subcommand(unittest.TestCase):
def test_command_exists(self):
assert sacrerouge_command_exists(['setup-dataset', 'multiling2011'])
|
3288615 | from nose import SkipTest
import networkx as nx
from networkx.generators.degree_seq import havel_hakimi_graph
class TestLaplacian(object):
numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test
@classmethod
def setupClass(cls):
global numpy
global assert_equal
glo... |
3288617 | from pprint import pprint
from configparser import ConfigParser
from td.credentials import TdCredentials
from td.client import TdAmeritradeClient
from td.utils.enums import Projections
# Initialize the Parser.
config = ConfigParser()
# Read the file.
config.read('config/config.ini')
# Get the specified credentials.
... |
3288619 | import os
import sys
import pytest
import operator
from ctypes import byref, c_int, c_uint16
import sdl2
from sdl2.stdinc import SDL_TRUE, SDL_FALSE
from sdl2 import SDL_Init, SDL_Quit, rwops, version, audio
if sys.version_info[0] >= 3:
from functools import reduce
sdlmixer = pytest.importorskip("sdl2.sdlmixer")
... |
3288624 | from django.contrib.postgres.fields import ArrayField # pragma: postgres
from django.db import models # pragma: postgres
class ArrayModel(models.Model): # pragma: postgres
char_array_field = ArrayField(null=True, base_field=models.CharField(max_length=32))
int_array_field = ArrayField(null=True, base_field... |
3288696 | from __future__ import print_function
import matplotlib.pyplot as plt
import scipy.spatial
import numpy as np
from matplotlib.colors import colorConverter
import mpl_toolkits.mplot3d as a3
def draw(self, ax=None, **kwargs):
if self.getDimension() == 2:
return self.draw2d(ax=ax, **kwargs)
elif self.ge... |
3288743 | from django.conf import settings
from django.conf.urls.i18n import is_language_prefix_patterns_used
from django.http import HttpResponseRedirect
from django.urls import get_script_prefix, is_valid_path
from django.utils import translation
from django.utils.cache import patch_vary_headers
from django.utils.deprecation i... |
3288782 | from datetime import date, datetime, timedelta
from freezegun import freeze_time
from app.dao.notifications_dao import dao_get_total_notifications_sent_per_day_for_performance_platform
from app.models import KEY_TYPE_NORMAL, KEY_TYPE_TEAM, KEY_TYPE_TEST
from tests.app.db import create_notification
BEGINNING_OF_DAY ... |
3288820 | from . import coordinates
from . import velocities
from . import box_vectors
from . import file_info
|
3288833 | import sys
import pytest
def test_propagate_primary_is_Master_update_watermarks(checkpoint_service):
# expected behaviour is that h must be set as last ordered ppSeqNo
checkpoint_service._is_master = True
checkpoint_service._data.low_watermark = 0
checkpoint_service._data.last_ordered_3pc = (checkpoi... |
3288838 | del_items(0x8007B9E4)
SetType(0x8007B9E4, "int GetTpY__FUs(unsigned short tpage)")
del_items(0x8007BA00)
SetType(0x8007BA00, "int GetTpX__FUs(unsigned short tpage)")
del_items(0x8007BA0C)
SetType(0x8007BA0C, "void Remove96__Fv()")
del_items(0x8007BA44)
SetType(0x8007BA44, "void AppMain()")
del_items(0x8007BAE4)
SetType... |
3288847 | from __future__ import unicode_literals
import logging
import os
import shutil
import tempfile
from io import open
from logging.handlers import BufferingHandler
from unittest import TestCase
from ..db import Database
def create_file(temp_folder, path, size):
path = os.path.join(temp_folder, *path)
dirname =... |
3288886 | import asyncio
from pathlib import Path
from time import time
from pydf import AsyncPydf, generate_pdf
THIS_DIR = Path(__file__).parent.resolve()
html = (THIS_DIR / 'invoice.html').read_text()
OUT_DIR = THIS_DIR / 'output'
if not OUT_DIR.exists():
Path.mkdir(OUT_DIR)
def go_sync():
count = 10
for i in ... |
3288943 | from .corpus_data_wrapper import CorpusDataWrapper
from .convenience_corpus import ConvenienceCorpus, from_model, from_base_dir
from .index_wrapper import Indexes, ContextIndexes
from .sentence_data_wrapper import TokenH5Data, SentenceH5Data
__all__ = [
'CorpusDataWrapper',
'Indexes',
'ContextIndexes',
... |
3288946 | import datetime
from briefmetrics.lib.table import Table, Column
from briefmetrics.lib.gcharts import encode_rows
from briefmetrics.lib import helpers as h
from briefmetrics.lib.report import (
EmptyReportError,
WeeklyMixin,
MonthlyMixin,
cumulative_by_month,
)
from .base import GAReport
from .helpers ... |
3289006 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases() # NOQA
import unittest
import numpy
import chainer
from chainer import cuda
from chainer import g... |
3289029 | import urllib.request
import json
import os
from tqdm import tqdm
with open ('CTC_anns.json', 'r') as fp:
ctc_anns = json.load(fp)
os.mkdir('./images/')
for item in tqdm(ctc_anns['images']):
urllib.request.urlretrieve(item['coco_url'], './images/'+ item['coco_url'].strip().split('/')[-1])
|
3289045 | from auto_yolo import envs
readme = "Testing air variational autoencoder with math."
distributions = None
durations = dict()
n_digits = 2
largest_digit = n_digits * 9
n_classes = largest_digit + 1
config = dict(
n_train=16000, min_digits=n_digits, max_digits=n_digits,
max_time_steps=n_digits, run_all_time_... |
3289068 | import os
from config.dev.settings import *
DEBUG = False
WSGI_APPLICATION = 'config.prd.app.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ.get('DB_NAME', 'fec_prd'),
'USER': os.environ.get('DB_USER', 'fec_prd'),
'PAS... |
3289081 | from .constants import gravitational_acceleration, air_gas_constant
from .Ambient import Ambient
from .Aerodynamic import coefficients_data
|
3289095 | import argparse
import os
from uuid import uuid1
import optuna
from dotenv import load_dotenv
from optuna.integration.pytorch_lightning import PyTorchLightningPruningCallback
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import EarlyStopping, GPUStatsMonitor, ModelCheckpoint
from pytorch_light... |
3289106 | import requests as _requests
from goldsberry.apiconvertor import *
class team_info:
def __init__(self, teamid, season='2015',league='NBA', seasontype=1):
self._url = "http://stats.nba.com/stats/teaminfocommon?"
self._api_param = {'TeamID':teamid,
'LeagueID': nba_league(l... |
3289135 | class Solution:
def multiply(self, T, M):
a = (T[0][0] * M[0][0] + T[0][1] * M[1][0] + T[0][2] * M[2][0])
b = (T[0][0] * M[0][1] + T[0][1] * M[1][1] + T[0][2] * M[2][1])
c = (T[0][0] * M[0][2] + T[0][1] * M[1][2] + T[0][2] * M[2][2])
d = (T[1][0] * M[0][0] + T[1][1] * M[1][0] + T[1][... |
3289145 | from Skoarcery.factoary.Build_Sc import Build_Sc
if __name__ == '__main__':
b = Build_Sc()
b.sanity()
|
3289167 | from django.contrib import admin
from django.contrib.admin.filters import (
SimpleListFilter,
AllValuesFieldListFilter,
ChoicesFieldListFilter,
RelatedFieldListFilter,
RelatedOnlyFieldListFilter
)
class InputFilter(admin.SimpleListFilter):
template = 'baton/filters/input_filter.html'
def ... |
3289181 | import struct
from ctypes import *
SS0 = [696885672, 92635524, 382128852, 331600848, 340021332, 487395612, 747413676, 621093156, 491606364, 54739776, 403181592, 504238620, 289493328, 1020063996, 181060296, 591618912, 671621160, 71581764, 536879136, 495817116, 549511392, 583197408, 147374280, 386339604,
629514... |
3289194 | CONSOLE_API_URL = "https://api.capellaspace.com"
DEFAULT_TIMEOUT = 60
DEFAULT_PAGE_SIZE = 999
DEFAULT_MAX_FEATURE_COUNT = 500
SUPPORTED_SEARCH_FIELDS = {
"bbox",
"intersects",
"collections",
"ids",
"limit",
}
SUPPORTED_QUERY_FIELDS = {
"center_frequency",
"collect_id",
"constellation... |
3289195 | import argparse
import logging
import numpy as np
import os
import sys
import torch
from models.graph2seq_series_rel import Graph2SeqSeriesRel
from models.seq2seq import Seq2Seq
from torch.utils.data import DataLoader
from utils import parsing
from utils.data_utils import canonicalize_smiles, load_vocab, S2SDataset, G2... |
3289222 | from com.huawei.iotplatform.client.dto.ObjectNode import ObjectNode
from com.huawei.iotplatform.client.dto.TagDTO2 import TagDTO2
class BatchTaskCreateInDTO(object):
tags = TagDTO2
param = ObjectNode
def __init__(self):
self.appId = None
self.taskName = None
self.taskType = None
... |
3289236 | from rlil.nn import RLNetwork
from .approximation import Approximation
class VNetwork(Approximation):
def __init__(
self,
model,
optimizer,
name='v',
**kwargs
):
model = VModule(model)
super().__init__(
model,
... |
3289248 | import multiprocessing
import numpy as np
import time
logfile = open("log.txt", "w")
class SharedTrainingStat():
def __init__(self):
self.manager = multiprocessing.Manager()
self.lock = self.manager.Lock()
self.total = self.manager.Value("total", 0)
self.acc = self.manager.Value("... |
3289253 | import os
import glob
import shutil
import sys
from collections import defaultdict
from textwrap import dedent
import datetime
from nbgrader.exchange.abc import ExchangeCollect as ABCExchangeCollect
from .exchange import Exchange
from nbgrader.utils import check_mode, parse_utc
from ...api import Gradebook, MissingEn... |
3289282 | import torch.nn as nn
class GroupNorm(nn.GroupNorm):
def __init__(
self,
num_features: int,
num_groups: int=None,
**kwargs
) -> None:
"""
Convenience wrapper for nn.GroupNorm to make kwargs
compatible with nn.BatchNorm
Infers... |
3289285 | from sklearn.datasets import load_breast_cancer
import pandas as pd
cancer = load_breast_cancer()
df = pd.DataFrame(data=cancer.data, columns=cancer.feature_names)
df['diagnosis'] = cancer.target
df.loc[df.diagnosis==0,'diagnosis'] = -1
df.loc[df.diagnosis==1,'diagnosis'] = 0
df.loc[df.diagnosis==-1,'diagnosis'] = 1
d... |
3289287 | import sys
import imgui
import time
from . import imgui_ext
from .imgui_image_lister import ImGuiImageLister
from . import imgui_cv
from .static_vars import static_vars
from collections import deque
from timeit import default_timer
import os
import pygame
import OpenGL.GL as gl
from imgui.integrations.pygame import ... |
3289318 | import pytest
from tesseractXplore.atlas import get_atlas_dimensions
# Test various combinations of inputs and limits
@pytest.mark.parametrize(
'n_images, x, y, limit_kwarg, expected_dimensions',
[
(14, 75, 75, {}, (154, 539)),
(15, 75, 75, {}, (308, 308)),
(16, 75, 75, {}, (308, 308))... |
3289341 | import flask
from ddtrace import Pin
from ddtrace.contrib.flask import unpatch
from . import BaseFlaskTestCase
class FlaskBlueprintTestCase(BaseFlaskTestCase):
def test_patch(self):
"""
When we patch Flask
Then ``flask.Blueprint.register`` is patched
Then ``flask.Blueprin... |
3289353 | paraphrase = [
[('model_name',), ['gpt2-large']],
[('dataset',), ["datasets/paranmt_filtered"]],
[('batch_size',), [5]],
[('accumulation',), [4]],
[('num_epochs',), [2]],
[('beam_size',), [1]],
[('eval_batch_size',), [1]],
[('learning_rate',), ["5e-5"]],
[('gpu',), ["m40"]],
[('n... |
3289356 | import logging
import json
import re
import core
from core.helpers import Torrent, Url
cookie = None
command_id = 0
label_fix = re.compile('[^a-z0-9_-]')
headers = {'Content-Type': 'application/json', 'User-Agent': 'Watcher'}
logging = logging.getLogger(__name__)
def test_connection(data):
''' Tests connectiv... |
3289410 | from sys import stdin, stdout
# one way to find angrams can be to sort two strings and then check if both of them are equal
s1 = stdin.readline()
s2 = stdin.readline()
if len(s1) != len(s2):
exit()
if set(s1) & set(s2) == set(s1):
print("Contains same Character")
else:
print("Cannot be Anagra... |
3289425 | from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from navigation import Menu
menu_documents = Menu(
icon='fa fa-file', label=_('Documents'), name='documents menu'
)
|
3289449 | from __future__ import annotations
import dataclasses
import io
import math
from fractions import Fraction
from pathlib import Path
from django.core import checks
from django.core.files.base import ContentFile
from django.core.files.storage import Storage
from django.db.models import ImageField
from django.db.models.... |
3289466 | import logging
from scout.constants import CONSEQUENCE, FEATURE_TYPES, SO_TERM_KEYS
from .transcript import build_transcript
LOG = logging.getLogger(__name__)
def build_gene(gene, hgncid_to_gene=None):
"""Build a gene object
Has to build the transcripts for the genes to
Args:
gene(dict): ... |
3289471 | import html
import logging
import queue
import threading
import time
from .incoming_message import IncomingMessage
from .utils import CONF_START, LongpollMessage
logger = logging.getLogger('vkapi.receiver')
class MessageReceiver:
def __init__(self, api, get_dialogs_interval=-1, message_class=IncomingMessage):
... |
3289502 | import numpy as np
import os
from torch.utils.data import Dataset
import glob
import numpy as np
from tqdm import tqdm
import dill as pickle
import torch
from copy import deepcopy
import json
import random
class ROCdataset():
def __init__(self, src_dir, train=True):
print("Loading data ... ")
# loa... |
3289513 | from io import BytesIO
from gzip import GzipFile
from pathlib import Path
import logging
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.config import strip_default_ids
from esphome.cpp_generator import ArrayInitializer
from esphome.yaml_util import dump, load_yaml
from esphome.core imp... |
3289516 | import shutil
import pytest
import yaml
import brownie
from brownie.exceptions import CompilerError
from brownie.project import compile_source
from brownie.project.main import install_package
@pytest.fixture(autouse=True)
def setup():
yield
path = brownie._config._get_data_folder().joinpath("packages")
... |
3289530 | from ansible import utils, errors
import os
import xml.etree.ElementTree as etree
class LookupModule(object):
def __init__(self, basedir=None, **kwargs):
self.basedir = basedir
def tostr(self, node):
if isinstance(node, etree._Element):
if len(node.getchildren()) == 0:
... |
3289556 | import itertools
import operator
import numpy as np
import matplotlib.pyplot as plt
from django.core.management.base import BaseCommand
from app import models
class Command(BaseCommand):
help = "beer"
def add_arguments(self, parser):
parser.add_argument("projects", nargs="+")
def handle(self, ... |
3289609 | from __future__ import print_function
from Crypto.Hash import SHA
from st2actions.runners.pythonrunner import Action
__all__ = [
'ShaIt'
]
class ShaIt(Action):
def run(self, message, handle):
sha_message = message + handle
return SHA.new(sha_message).hexdigest()
|
3289663 | import datetime
import decimal
import json
from time import mktime
class SendwithusJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return int(mktime(obj.timetuple()))
if isinstance(obj, decimal.Decimal):
return float(obj)
... |
3289681 | from amodem import config
def test_bitrates():
for rate, cfg in sorted(config.bitrates.items()):
assert rate * 1000 == cfg.modem_bps
def test_slowest():
c = config.slowest()
assert c.Npoints == 2
assert list(c.symbols) == [-1j, 1j]
|
3289696 | class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
flag = 1
if x < 0:
x = -x
flag = -1
result = 0
while x:
result = result * 10 + x % 10
#出现溢出
if result >= 2 ** 31 - 1:
... |
3289732 | from __future__ import division, absolute_import, print_function
import re
import scipy
from numpy.testing import assert_
def test_valid_scipy_version():
# Verify that the scipy version is a valid one (no .post suffix or other
# nonsense). See numpy issue gh-6431 for an issue caused by an invalid
# ver... |
3289748 | from . import MD5Folder
class AfpFolder(MD5Folder):
def tree_complete(self):
MD5Folder.tree_complete(self)
if not self.info_kbin:
return
# findall needs xpath or it'll only search direct children
names = []
geo_names = []
for tag in self.info_kbin.xml_d... |
3289753 | from hubspot import HubSpot
from hubspot.cms.performance import PublicPerformanceApi
def test_is_discoverable():
apis = HubSpot().cms.performance
assert isinstance(apis.public_performance_api, PublicPerformanceApi)
|
3289780 | import matplotlib.pyplot as plt
import numpy as np
def graph_function(func, min_x, max_x, num=300):
x_ = np.linspace(min_x, max_x, num)
y_ = [func(i) for i in x_]
plt.plot(x_, y_)
plt.show()
def graph_function_and_data(func, x_data, y_data, num=300, min_x=None, max_x=None):
min_x = min(x_data) ... |
3289785 | import datetime
from typing import Tuple
import rlp
CLUSTER_PEER_ID_LEN = 2 ** 64
RESERVED_CLUSTER_PEER_ID = 0
def sxor(s1: bytes, s2: bytes) -> bytes:
if len(s1) != len(s2):
raise ValueError("Cannot sxor strings of different length")
return bytes(x ^ y for x, y in zip(s1, s2))
def roundup_16(x: ... |
3289807 | import asyncio
import os
from ray.serve.benchmarks.microbenchmark import main as benchmark_main
from ray.serve.utils import logger
from serve_test_cluster_utils import (
setup_local_single_node_cluster,
setup_anyscale_cluster,
)
from serve_test_utils import (
save_test_results, )
async def main():
# ... |
3289809 | import pytest
from requests import Response
from tests.conftest import create_mock_response
from py42.exceptions import Py42InvalidRuleError
from py42.exceptions import Py42NotFoundError
from py42.services.alertrules import AlertRulesService
from py42.services.detectionlists.user_profile import DetectionListUserServic... |
3289812 | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='dvb',
version='1.3',
description='query Dresden\'s public tra... |
3289834 | import h5py
from scipy.cluster.hierarchy import ward, dendrogram
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
h5file = h5py.File("96.jl.h5")
X = h5file["X"].value
# n_samples x n_features
assert X.shape[1] == 300
df = pd.read_csv("./countries.csv")
labels = np.array(df.iloc[:, 1])
Z... |
3289848 | from node.behaviors import Adopt
from node.behaviors import DefaultInit
from node.behaviors import Nodify
from node.behaviors import OdictStorage
from node.behaviors import Reference
from node.behaviors.reference import NodeIndex
from node.tests import NodeTestCase
from plumber import plumbing
from zope.interface.commo... |
3289868 | from flask_restful import Resource
from models.user import UserModel
from utils.authorizations import admin_required
class UsersPending(Resource):
@admin_required
def get(self):
return {"users": UserModel.find_users_without_assigned_role().json()}
|
3289883 | import logging
import numpy as np
import pandas as pd
import syne_tune.config_space as sp
from syne_tune.blackbox_repository import (
load,
add_surrogate,
BlackboxRepositoryBackend,
UserBlackboxBackend,
)
from syne_tune.blackbox_repository.blackbox_tabular import BlackboxTabular
from syne_tune.backend... |
3289884 | import os
import copy
import time
import pickle
import numpy as np
import torch
from options import args_parser
from datasets import get_dataset
if __name__ == '__main__':
############# Common ###################
args = args_parser()
if args.gpu:
torch.cuda.set_device(args.gpu)
devic... |
3289940 | import asyncio
from ray import workflow
from ray.tests.conftest import * # noqa
from ray.workflow import workflow_storage
from ray.workflow.storage import get_global_storage
import pytest
def get_metadata(paths, is_json=True):
store = get_global_storage()
key = store.make_key(*paths)
return asyncio.get... |
3289967 | import numpy as np
import scipy
import scipy.cluster
from mss import mss
from firelight.interfaces.color import RGBColor
from firelight.processing.image import colorfulness
from firelight.processing.quantizer import Tree
# from matplotlib import pyplot as PLT
FILTER_LOW_OCCURRENCE_COLORS = True
DOWNSAMPLED_SCREENSHOT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.