id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3370683 | import numpy as np
import scipy.io
import torch
import torch.utils.data as data_utils
import common
class Dataset():
def __init__(self, args):
"""load cSVHN dataset"""
print("Loading cSVHN dataset...")
train_data = scipy.io.loadmat('./data/svhn/train_32x32.mat')
test_data = ... |
3370729 | from typing import Sequence
from ulid import constants
# The encoding and decoding arithmetics are based on the implementation of RobThree
# https://github.com/RobThree/NUlid/blob/89f5a9fc827d191ae5adafe42547575ed3a47723/NUlid/Ulid.cs#L168
ENCODE: str = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
DECODE: Sequence[int] = [
... |
3370802 | import os
from django.conf import settings
from django.core import mail
from django.template.loader import render_to_string
def to_str(context, template_file, template_dir=None):
return render_to_string(
os.path.join(template_dir, template_file), context).strip()
def send_mail(to, context, template_dir=... |
3370851 | import datetime
from dateutil.parser import isoparse
from dateutil.rrule import MONTHLY, rrule
from scrapy import Request
from gazette.items import Gazette
from gazette.spiders.base import BaseGazetteSpider
class MtCuiabaSpider(BaseGazetteSpider):
TERRITORY_ID = "5103403"
name = "mt_cuiaba"
allowed_doma... |
3370860 | import numpy as np
import threading
import logging
from pysvso.lib.log import LoggerAdaptor
_logger = logging.getLogger("mapblock")
from pysvso.py_pose_graph.frame import Frame
from pysvso.py_pose_graph.point3d import CameraPoint3D, WorldPoint3D
from pysvso.matcher import ROIMatcher
from pysvso.optimizers.bundle_adj... |
3370880 | from django.db import models
DEVICE_ENVIRONMENT = [
('LAB', 'lab device'),
('PROD', 'production device'),
]
class OperatingSystem(models.Model):
name = models.CharField(max_length=255)
netmiko_type = models.CharField(max_length=255)
terminal_length_cmd = models.CharField(max_length=255)
fetc... |
3370895 | from flask_unchained import AppFactoryHook
from flask_unchained.hooks.views_hook import ViewsHook
from ..model_resource import ModelResource
from ..extensions.api import Api
class RegisterModelResourcesHook(AppFactoryHook):
"""
Registers ModelResources and configures ModelSerializers on them.
"""
na... |
3370907 | import unittest
from pytopojson.hash.hash import HashMap
def equal(a, b):
return a is b
def hash(o):
return o["hash"]
class HashMapTestCase(unittest.TestCase):
def test_hashmap_can_get_an_object_by_key(self):
map = HashMap(10, hash, equal)
key = {"hash": 1}
map.set(key, 42)
... |
3370931 | from a10sdk.common.A10BaseClass import A10BaseClass
class Stats(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param elect_master_discard_challenger: {"description": "vMaster discard challenger counter of aVCS election", "format": "counter", "type": "number", "oid": "3... |
3370968 | import logging
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
import os
import seaborn as sns
import yaml
import torch
from model.training import build_lr_scheduler
sns.set_style('whitegrid', {'axes.edgecolor': '.2'})
sns.set('poster', rc={"xtick.bottom": True, "ytick.left": T... |
3371001 | from unittest import TestCase
from pyparsing import ParserElement
from pydbml.definitions.table_group import table_group
ParserElement.setDefaultWhitespaceChars(' \t\r')
class TestProject(TestCase):
def test_empty(self) -> None:
val = 'TableGroup name {}'
res = table_group.parseString(val, par... |
3371002 | from modAL.density import similarize_distance, information_density
from sklearn.datasets import make_blobs
from scipy.spatial.distance import euclidean
X, y = make_blobs(n_features=2, n_samples=10, centers=3, random_state=0, cluster_std=0.7)
cosine_density = information_density(X)
euclidean_density = information_dens... |
3371034 | import asyncio
import logging
from aioax25 import interface
from aioax25 import kiss as kiss
from aioax25.aprs import APRSInterface
LOG = logging.getLogger("APRSD")
class Aioax25Client:
def __init__(self, config):
self.config = config
loop = asyncio.new_event_loop()
asyncio.set_event_lo... |
3371065 | person = ('xiaobai', 18)
print(person[0],person[1])
from collections import namedtuple
Person = namedtuple('Person', 'name age city') # 类似于定义class
xiaobai = Person(name="xiaobai", age=18, city="paris") # 类似于新建对象
print(xiaobai)
import collections
# 将纸牌定义为具名元组,每个纸牌都有等级和花色
Card = collections.namedtuple('Card', ... |
3371071 | import setuptools
setuptools.setup(
name='groove2groove',
author='<NAME>',
description='Music style transfer and style translation models',
url='https://github.com/cifkao/groove2groove',
python_requires='>=3.6',
install_requires=[
'scipy'
],
extras_require={
'gpu': 'muse... |
3371093 | import importlib
def load_loss_weight(dataset_name):
"""Loss weight to balance the categories
weight = -log(frequency)"""
if dataset_name[-1]=='g':
dataset_name = dataset_name[:-1]
try:
Weight = importlib.import_module('utils.aux_data.%s_weight'%dataset_name)
if '... |
3371128 | import sys
import unittest
from unittest import TestSuite
def suite(test_name):
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromName(test_name))
return suite
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage {test_name}")
sys.exit(1)
... |
3371143 | import os
import sys
import httplib
from time import time,sleep,strftime,gmtime
from urlparse import urljoin, urlsplit
from socket import gethostbyname
from binascii import crc32
'''
This utility will request the same url every 1 second, I suggest you have this script return a simple timestamp,
this can be us... |
3371159 | from enum import Enum
import math
try:
import drawBot as db
except ImportError:
db = None
YOYO = "ma"
MINYISMAXY = False
class Edge(Enum):
MaxY = 1
MaxX = 2
MinY = 3
MinX = 4
CenterY = 5
CenterX = 6
def txt_to_edge(txt):
if isinstance(txt, str):
txt = txt.lower()
... |
3371160 | import os
import argparse
import joblib
import numpy as np
from PIL import Image
from torchvision import transforms, datasets
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn import metrics
from face_recognition import preprocessing, FaceFeaturesExtractor... |
3371181 | import os
import re
import sys
import time
from .lineedit.prompt import ModalPromptSession, ModeSpec
from .lineedit.history import ModalInMemoryHistory, ModalFileHistory
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.formatted_text import ANSI
from prompt_toolkit.layout.processors import HighlightMat... |
3371205 | import os
from pathlib import PurePath
class PathUtils(object):
@classmethod
def join(cls, *paths):
return PurePath(*paths).as_posix()
@classmethod
def user_home_dir(cls):
return cls.join(os.path.expanduser("~"))
@classmethod
def src_root_dir(cls):
return cls.join(os... |
3371209 | from libs.openexchange import OpenExchangeClient
APP_ID = "72dba35060b54cf9ad3ffbdc68de9174"
client = OpenExchangeClient(APP_ID)
usd_amount = 1000
gbp_amount = client.convert(usd_amount, 'USD', 'GBP')
print(f"USD{usd_amount} is GBP{gbp_amount}") |
3371232 | import os
import glob
import random
import time
import json
from datetime import datetime
from statistics import mean
import argparse
from PIL import Image
import numpy as np
from scipy.io import loadmat
import cv2
import torch
import torch.optim as optim
from torch.autograd import Variable
import torch.nn.functional... |
3371274 | import struct
import argparse
def write_spdz(input_folder, data):
f = open(input_folder + "/f0", 'w')
for d in data[0]:
sign = d < 0
output = struct.pack("?", sign)
f.write(output)
output = struct.pack("Q", abs(int(d)))
f.write(output)
f.close()
f = open(input_f... |
3371306 | import warnings
import numpy as np
class Multitrack():
""" Multitrack audio object
Load audio either directly as a numpy array with shape [samples, channels].
All channels must have the same number of samples.
"""
def __init__(self, data=None, files=None, num_channels=1, rate=44100, blo... |
3371311 | import torch
import torch.nn as nn
class EntropyLoss(nn.Module):
# Return Scalar
def forward(self, adj, anext, s_l):
entropy = (torch.distributions.Categorical(
probs=s_l).entropy()).sum(-1).mean(-1)
assert not torch.isnan(entropy)
return entropy
class LinkPredLoss(nn.Mod... |
3371318 | import os
from datetime import datetime
from unittest.mock import patch
import pytest
from sigal.gallery import Video
from sigal.settings import Status, create_settings
from sigal.video import generate_thumbnail, generate_video, process_video, video_size
CURRENT_DIR = os.path.dirname(__file__)
SRCDIR = os.path.join(... |
3371320 | import process_data
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
# Load all train and test data (*... |
3371331 | import sys
import pytest
from aerospike import exception as e
aerospike = pytest.importorskip("aerospike")
try:
import aerospike
except:
print("Please install aerospike python client.")
sys.exit(1)
def get_key_with_digest_only(key):
"""
Takes a key tuple, and removes a key tuple
without a pri... |
3371348 | import sys
from types import SimpleNamespace
from typing import Callable
# noinspection PyPackageRequirements
import pytest as pytest
from jinja2 import TemplateNotFound
from markupsafe import Markup
from fixtures import registered_extension, starlette_render_partial
import jinja_partials
def test_render_empty(regi... |
3371409 | import pygetwindow as gw
import win32gui
def get_hwnd(Title):
"""
Returns the HWND number for provided string
Example:
> window_title = "Lost Ark"
> hwnd = get_hwnd(window_title)
#### Lost Ark (3412402) window was located.
"""
try:
a = gw.getWindowsWithTitle(Title)... |
3371419 | from unittest import TestCase
import zen
class ProfileTestCase(TestCase):
def test_all_sources(self):
G = zen.DiGraph()
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(4,5)
cp = zen.control.profile(G,normalized=False)
self.assertEquals(cp,(2,0,0))
cp = zen.control.profile(G)
self.assertEquals(cp,(1... |
3371504 | import os
import sys
import autograd.numpy as np
# WARNING SCIPY NOT AUTOGRAD
from scipy.spatial.distance import cdist
base_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..")
sys.path.append(base_dir)
from src.kernels.base import Kernel
from utils.decorators import accepts
class GaussianKernel(... |
3371530 | from . import data_sampler
from . import gaussian_process
from . import neural_network
from . import preprocessing_helper
from . import model
from .gaussian_process import GaussianProcess
from .data_sampler import DataSampler
from .neural_network import NeuralNetwork
|
3371536 | import unittest
import numpy as np
from pysprint.core._evaluate import spp_method
class TestEvaluate(unittest.TestCase):
def setUp(self):
self.delays = np.array(
[
-1700.0,
-1700.0,
-1500.0,
-1500.0,
-1300.0,
... |
3371539 | from aparse import click, ConditionalType
import os
import tqdm
import json
from typing import Optional
from collections import OrderedDict
from itertools import chain
import tensorflow as tf
from viewformer.utils.tensorflow import load_model
from viewformer.data.loaders import get_loaders
from viewformer.data._common ... |
3371587 | import glob
import sys
import os
def print_module_index(module, header):
modules = module.split('.')
if len(modules) > 1:
os.chdir('/'.join(modules[0:-1]))
pattern = modules[-1] + '/*.rst'
stream = open(modules[-1] + '.rst', 'w')
else:
pattern = modules[0] + '/*.rst'
... |
3371609 | import asyncio
import pytest
@pytest.fixture(scope="session")
@pytest.mark.async_timeout(0.01)
async def fixture_timeout_in_setup_session():
await asyncio.sleep(1)
yield 1
@pytest.fixture(scope="session")
@pytest.mark.async_timeout(0.01)
async def fixture_timeout_session():
await asyncio.sleep(1)
re... |
3371613 | from __future__ import absolute_import, unicode_literals
import argparse
import logging
import os
import re
import sys
import textwrap
from collections import namedtuple
from io import open
from textwrap import dedent
from warnings import warn
from ksconf import KsconfPluginWarning
from ksconf.conf.parser import (Con... |
3371622 | import os
import json
import pathlib
import bpy
import pprint
from . import Global
from . import NodeArrange
from . import Versions
from . import MatDct
from . import Util
from . import BumpToNormal
# region top-level methods
def srgb_to_linear_rgb(srgb):
if srgb < 0:
return 0
elif srgb < 0.04045:
... |
3371645 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open("kineticstoolkit/VERSION", "r") as fh:
version = fh.read()
setuptools.setup(
name='kineticstoolkit',
version=version,
description='An Open-Source Python Package to Facilitate Research in Biomechanics.',
... |
3371671 | from __future__ import print_function
import os
import numpy as np
from tractor.ellipses import EllipseESoft
from tractor.utils import _GaussianPriors
def log_info(logger, args):
msg = ' '.join(map(str, args))
logger.info(msg)
def log_debug(logger, args):
import logging
if logger.isEnabledFor(logging... |
3371681 | import os
import numpy as np
import torch
import torch.nn as nn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from PIL import Image
import math
from models.utils import *
from quantization.quantize import Quantization
def get_density(w):
n_nonzeros = (w.abs()>0).sum().item()
... |
3371736 | from dagster import InputDefinition, Nothing, OutputDefinition, check, op, solid
from .configs import define_spark_config
def create_spark_solid(
name, main_class, description=None, required_resource_keys=frozenset(["spark"])
):
return core_create_spark(
dagster_decorator=solid,
name=name,
... |
3371752 | import bisect
import numpy as np
from scipy.interpolate import interp1d
def deep_interp_0_fast(dx, x, y):
FIX = False
if len(y.shape) == 1:
y = y[:, None]
FIX = True
ret = np.zeros((dx.shape[0], y.shape[1]))
index = list(x)
for i in range(dx.shape[0]):
idx = bisect.bisect_left(index, dx[i])
... |
3371797 | from abc import ABC, abstractmethod
import numpy as np
from .KerasModel import limitTFMem
from ..utils.DataContainer import DataContainer
# Factory style method for creating the KInfer object
def getKInferInstance(kitype, model_fn):
if kitype == 'numpy':
return KInferWithNumpy(model_fn)
elif kit... |
3371816 | import operator
import re
import ipaddr
from itertools import izip
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models.fields import FieldDoesNotExist
from django.db.models import Q
from django.db.models.related import RelatedObject
from mozdns.address_record.models import Ad... |
3371826 | from urllib import parse
from xiaohongshu.shield import get_sign
def main():
# 对接口路径、url参数、header中的xy-common-params、xy-platform-info、请求的data进行签名
path = '/api/sns/v4/note/user/posted'
params = parse.urlencode({'user_id': '5eeb209d000000000101d84a'})
xy_common_params = parse.urlencode({})
xy_platfo... |
3371870 | from typing import Optional, Sequence, Tuple, Union
import numpy as np
import pandas as pd
from sgkit.typing import ArrayLike
def _tuple_len(t: Union[int, Tuple[int, ...], str, Tuple[str, ...]]) -> int:
"""Return the length of a tuple, or 1 for an int or string value."""
if isinstance(t, int) or isinstance(... |
3371937 | import logging
import sentry_sdk
import sentry_sdk.integrations.aiohttp
import sentry_sdk.integrations.logging
sentry_logging = sentry_sdk.integrations.logging.LoggingIntegration(
level=logging.INFO, event_level=logging.ERROR
)
def setup(server_version, dsn):
sentry_sdk.init(
dsn=dsn,
integr... |
3371951 | from typing import List
import pytest
import torch
from ludwig.encoders.set_encoders import SetSparseEncoder
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
@pytest.mark.parametrize("vocab", [["a", "b", "c", "d", "e", "f", "g", "h"]])
@pytest.mark.parametrize("embedding_size", [10])
@pytest.mark.parametriz... |
3371986 | from distutils.version import LooseVersion
from django.core.management import BaseCommand
from corehq.apps.app_manager.const import APP_V1
from corehq.apps.app_manager.dbaccessors import get_apps_in_domain
from corehq.apps.builds.utils import get_default_build_spec
def turn_on_secure_submissions_for_all_apps(domain... |
3372007 | from .utils import getData
class Sozluk:
"""TDK API kullanarak verilen kelimeler hakkinda JSON datasi dondurur,
ayni zamanda anlam, deyim ve cumle ici ornekler getirir.
"""
def __init__(self, kelime):
self.data = getData(kelime)
self.kelime = kelime
self.anlamlar = []
... |
3372012 | from __future__ import division
import json
import os
import subprocess
from pbase.ptext.field import Field, NestedField
from pbase.ptext.attribute import Attribute
from pbase.papp.argument import Argument
from pbase.papp.trainer import Trainer
from zoo.ner.model.ner_tensorflow import NERModel
pid = os.getpid()
cl... |
3372014 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.davis_thin import davis_thin
def test_davis_thin():
"""Test module davis_thin.py by downloading
davis_thin.csv and testing shape of
extrac... |
3372020 | from pathlib import Path
import randomname
def test_get_name():
name = randomname.get_name('music_theory', 'cats').split('-', 1)
assert len(name) > 1
assert name[0] in randomname.util.get_groups_list('a/music_theory')
assert name[1] in randomname.util.get_groups_list('n/cats')
assert 'asdf' in ra... |
3372026 | T = int(input())
for i in range(T):
input()
cs, ec = [int(x) for x in input().split()]
total = cs + ec
IQs = [int(x) for x in input().split()]
while len(IQs)<total:
IQs += [int(x) for x in input().split()]
csIQs = IQs[0:cs]
ecIQs = IQs[cs:len(IQs)]
total = 0
for x in csI... |
3372071 | from __future__ import absolute_import, division, print_function
import numpy as np
import h5py
import pandas as pd
import sys
sys.path.append('../')
import get_unique_craters as guc
class TestLongLatEstimation(object):
def setup(self):
ctrs = pd.HDFStore('./sample_crater_csv.hdf5', 'r')
ctrs_met... |
3372116 | from .driver import GenericDBDriver, DBDriver
import sqlalchemy
from typing import Union
def db_driver(db: Union[sqlalchemy.engine.Engine,
sqlalchemy.engine.Connection],
**kwargs) -> DBDriver:
engine: sqlalchemy.engine.Engine = db.engine
engine_name: str = engine.name
... |
3372140 | from defined.post_init import GET_CAOS_FOLDER
from defined.generator import generator_text
from defined.constants import sync_info
from offline.modify import set_tasks_dir
from utils import get_problems, c_file
import os
from bs4 import BeautifulSoup as bs
from clint.textui import puts
def sync(session, sync_samples... |
3372148 | import json
import os
import boto3
import requests
WEBHOOK_PARAMETER_NAME = os.environ.get("WEBHOOK_URL_PARAMETER", "/slackops/webhook-url")
API_ENDPOINT = os.environ.get("API_ENDPOINT", "https://e6f0vj492m.execute-api.eu-central-1.amazonaws.com/prod/v1/approval")
def build_slack_message(event: dict):
custom_dat... |
3372152 | import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
import argparse
import datetime
import json
import contextlib
from func_timeout import func_timeout, FunctionTimedOut
import multiprocessing
import numpy as np
import os
import random
import sys
import time
f... |
3372206 | import numpy as np
import pytest
from stardist import star_dist3D, Rays_GoldenSpiral, relabel_image_stardist3D
from utils import random_image, real_image3d, check_similar, circle_image, Timer
from time import time
@pytest.mark.parametrize('img', (real_image3d()[1], random_image((33, 44, 55))))
@pytest.mark.parametrize... |
3372212 | import os
import re
from flask import Response, redirect
from subprocess import PIPE, Popen
from wsgi_utils import PipeWrapper
TRANSCODABLE_FORMATS = ['mp3', 'ogg', 'flac', 'm4a', 'wav']
def _format_of_file(filename):
return re.search('\.([^.]+)$', filename).group(1)
class Transcoder(object):
def __init__(se... |
3372262 | from analyzer.syntax_kind import SyntaxKind
class VariableDeclarationSyntax(object):
def __init__(self, var_token, variables, export_token, semicolon_token):
self.kind = SyntaxKind.VariableDeclaration
self.var_token = var_token
self.variables = variables
self.export_token = export_... |
3372264 | from uibasetest import *
class TestFloatingIp(UIBaseTest):
floating_ip = []
def setup(self):
super(TestFloatingIp, self).setup()
self.uidriver.click_menu(self.uimap.menu_networking, self.uimap.menu_floating_ip)
def test_01_allocate_new_ip(self):
if not self.uidriver.is_element_p... |
3372267 | import dbcopy
import pytrellis
import nets
# In the below filters: accept HF/HL/and HBSX fixed connections to be copied
# for now.
def exclude_abcd_conns(conn):
if isinstance(conn, pytrellis.FixedConnection):
src = conn.source
sink = conn.sink
else:
(src, sink) = conn
if (src.endswi... |
3372280 | import mrl
import gym
from mrl.replays.core.shared_buffer import SharedMemoryTrajectoryBuffer as Buffer
import numpy as np
import pickle
import os
from mrl.utils.misc import batch_block_diag
class OnlineHERBuffer(mrl.Module):
def __init__(
self,
module_name='replay_buffer'
):
"""
Buffer that... |
3372374 | from abc import ABCMeta, ABC
from collections import Sized
from typing import Callable, Iterable
from deepstochlog.networkevaluation import RequiredEvaluation
from deepstochlog.term import Term
class LogicNode(Sized):
def accept_visitor(self, visitor: "LogicNodeVisitor"):
raise NotImplementedError()
... |
3372476 | from PIL import Image
from cube2equi import find_corresponding_pixel
def convert_img(infile, outfile):
inimg = Image.open(infile)
wo, ho = inimg.size
# Calculate height and width of output image, and size of each square face
h = wo/3
w = 2*h
n = ho/3
# Create new image with width w, and... |
3372615 | token = '0<PASSWORD>' #Put Your bots token here
prefix = '~' #put prefix here
link = 'https://discordapp.com/oauth2/authorize?client_id=000000000000000000&scope=bot&permissions=0000000' #put bot invite link here
ownerid = '00000000000000000' #put your id here
|
3372661 | import base64
import ctypes
import functools
import krb5_ctypes
__all__ = ['Context']
class Error(Exception):
def __init__(self, ctx_raw, code):
self.code = code
msg_c = krb5_ctypes.krb5_get_error_message(ctx_raw, code)
self.message = msg_c.value
krb5_ctypes.krb5_free_error_messag... |
3372673 | import os
import shutil
import sys
def delete_links(links, logger):
"""
Unmake all of the links.
:param links: A list containing paths to link objects to be deleted.
:param logger: A Management Tools Logger object for handling output.
"""
for link in links:
try:
logger... |
3372696 | import pygame
from OpenGL.GL import *
import ptextgl
screen = pygame.display.set_mode((640, 640), pygame.OPENGL | pygame.DOUBLEBUF)
glViewport(0, 0, 640, 640)
glClearColor(0.3, 0, 0, 1)
jframe = 0
while not any(event.type in (pygame.KEYDOWN, pygame.QUIT) for event in pygame.event.get()):
glClear(GL_COLOR_BUFFER_BIT)... |
3372724 | import numpy as np
from transonic import Type, NDim, Array, boost
T = Type(np.float64, np.complex128)
N = NDim(1)
A = Array[T, N]
@boost
def func(a: A):
i: int
n: int = a.shape[0]
for i in range(n):
a[i] = a[i] + 1.
|
3372732 | import pytest
from commercetools.utils import fix_token_url
@pytest.mark.parametrize(
"token_url,expected_url",
[
("https://auth.sphere.io", "https://auth.sphere.io/oauth/token"),
("https://auth.sphere.io/oauth/token", "https://auth.sphere.io/oauth/token"),
("https://auth.commercetool... |
3372737 | from ftfy import bad_codecs, guess_bytes
def test_cesu8():
cls1 = bad_codecs.search_function('cesu8').__class__
cls2 = bad_codecs.search_function('cesu-8').__class__
assert cls1 == cls2
test_bytes = (b'\xed\xa6\x9d\xed\xbd\xb7 is an unassigned character, '
b'and \xc0\x80 is null')
... |
3372780 | import os
from planemo.galaxy.profiles import translate_alias
from planemo.galaxy.workflows import GALAXY_WORKFLOWS_PREFIX
from planemo.tools import uri_to_path
from .runnable import (
for_path,
for_uri,
)
def for_runnable_identifier(ctx, runnable_identifier, kwds, temp_path=None, return_all=False):
"""C... |
3372839 | import energym
from energym.envs.env import OutputsWrapper
from copy import deepcopy
from energym.spaces.box import Box
class RescaleOutputs(OutputsWrapper):
r"""Rescales the continuous outputs space of the environment to a given range. By default, variables are rescaled
between 0 and 1."""
def __init__(... |
3372882 | import _plotly_utils.basevalidators
class TransitionValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="transition", parent_name="layout", **kwargs):
super(TransitionValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
3372888 | from typing import List
from argo_workflow_tools.dsl import dsl_decorators
from argo_workflow_tools.dsl.workflow import Workflow
@dsl_decorators.Task(image="python:3.10")
def generate_list(partitions: int, partition_size: int):
items = []
for i in range(partitions):
items.append(list(range(1, partiti... |
3372889 | from tipfy import REQUIRED_VALUE
default_config = {
'locale': 'en_US',
'timezone': 'America/Chicago',
'required': REQUIRED_VALUE,
}
|
3372908 | import numpy as np
from ..base import BaseSKI
from tods.feature_analysis.StatisticalVecSum import StatisticalVecSumPrimitive
class StatisticalVecSumSKI(BaseSKI):
def __init__(self, **hyperparams):
super().__init__(primitive=StatisticalVecSumPrimitive, **hyperparams)
self.fit_available = False
self.predict_avai... |
3372915 | import json
from abc import ABCMeta, abstractmethod
from typing import Dict
from py_fake_server.request import Request
class HeaderDoesNotExist:
def __repr__(self):
return "<HEADER DOES NOT EXIST>"
class BaseValidator(metaclass=ABCMeta):
@abstractmethod
def validate(self, request: Request):
... |
3372935 | from __future__ import absolute_import
from pychron.core.ui import set_toolkit
set_toolkit('qt4')
from pychron.paths import paths
paths.build('_unittest')
#build_directories(paths)
from pychron.core.helpers.logger_setup import logging_setup
logging_setup('arar')
from test.database import isotope_manager_factory
... |
3372936 | import unittest
from PyStacks.PyStacks.template import templateCF
class TestTemplate(unittest.TestCase):
def test_templateCF_GenericDynamoDbTables(self):
resources = {
'dynamodb_tables': {
'testTable': {
'name': 'testTable',
'attributes... |
3372943 | from setuptools import setup, find_packages
# read README
try:
import pypandoc
readme = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
readme = open('README.md').read()
setup(
name="PyCoolPlot",
version="0.0.4",
url="https://github.com/AtsushiSakai/PyCoolPlot",
author="... |
3372946 | from django.urls import include, path
from django.views.generic import TemplateView
home = TemplateView.as_view(template_name="home.html")
urlpatterns = [
# ObjectDownloadView.
path(
"object/",
include("demoproject.object.urls", namespace="object"),
),
# StorageDownloadView.
path(... |
3373001 | import os
num_cpu_per_worker = 1
cpu_range = [0,159]
def get_legal_cpus(cpu_range, num_cpu_per_worker):
num_available_cpus = cpu_range[1] - cpu_range[0] + 1
affinities = []
for i in range(int(num_available_cpus / num_cpu_per_worker)):
affinities.append(
[
cpu_range[0] +... |
3373012 | import numpy
import sys
PyRLA_dir = '../../'
sys.path.append(PyRLA_dir)
from sketch import *
def sketched_lsr(x_mat, y_mat, sketch_size=None, sketch_type='count'):
'''
Sketched Least Squares Regression
Alternative of numpy.linalg.lstsq(x_mat, y_mat)
Input
x_mat: n-by-d feature matrix;
... |
3373015 | import numpy as np
from pymoo.core.algorithm import Algorithm
from pymoo.core.individual import Individual
from pymoo.operators.repair.to_bound import set_to_bounds_if_outside
from pymoo.problems.meta import MetaProblem
class LineSearch(Algorithm):
def __init__(self, **kwargs):
super().__init__(**kwargs... |
3373020 | import make_ctags
def test_compile():
df = make_ctags.compile(None, paths=['simple.py'])
assert len(df) == 1
assert df.columns.tolist() == ['path', 'name', 'ctags_raw', 'linecount']
|
3373050 | import numpy as np
import numpy.testing as npt
import pytest
import freud
class TestAngularSeparationGlobal:
def test_getN(self):
boxlen = 10
N = 500
box, points = freud.data.make_random_system(boxlen, N, is2D=True)
_, query_points = freud.data.make_random_system(boxlen, N // 3, ... |
3373062 | import logging
import random
from datetime import datetime
from typing import List
import torch
from torch import optim, nn
from torch.utils.tensorboard import SummaryWriter
from hearthstone.ladder.ladder import Contestant, update_ratings, print_standings, save_ratings
from hearthstone.simulator.host import RoundRobi... |
3373088 | import os
from fabric.api import env
from fabric.api import sudo
from fabric.api import prefix
from fabric.contrib.project import rsync_project
from fabric.context_managers import settings
from contextlib import contextmanager
env.hosts = []
env.serve_root = '/srv/www/django'
env.project_name = 'microweb'
env.virt... |
3373094 | import os
import pytest
from jina.excepts import PretrainedModelFileDoesNotExist
from .. import SpellChecker
from ..pyngramspell import PyNgramSpell
cur_dir = os.path.dirname(os.path.abspath(__file__))
def test_missing_model_path():
wrong_path_vectorizer = os.path.join(
cur_dir, '/model/non_existant.pic... |
3373096 | import sys
import unittest
from unittest.case import TestCase
import pytest
sys.path.append("../../../")
from datetime import date, datetime, timedelta
from plugins.TodayAtMun.DiaryUtil import DiaryUtil
from plugins.TodayAtMun.__init__ import TodayAtMun
class TestDateMethods(unittest.TestCase):
"""Testing TodayA... |
3373117 | from distutils.core import setup
install_requires = ['hy>=0.13.0']
#python setup.py register -r pypitest
#python setup.py register -r pypi
# next command not recommended but what can you do in Windows...
#python setup.py sdist upload -r pypitest
#python setup.py sdist upload
# 08/017 windows: python setup.py sdist up... |
3373170 | from pudzu.charts import *
from pudzu.sandbox.bamboo import *
atlas = pd.read_csv("datasets/countries.csv").split_columns('country', "|").explode('country').set_index("country")
df = pd.read_csv("datasets/demographics_jewish.csv").set_index("country").sort_values("historical", ascending=False).fillna(0)
def rla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.