id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1753119 | from datetime import datetime
from mongoengine import *
class SurveyModel(Document):
"""
설문지
"""
meta = {
'collection': 'survey'
}
creation_time = DateTimeField(
default=datetime.now
)
# 설문지 생성 시간
title = StringField(
required=True
)
description ... |
1753125 | from ..biotools import windows_overlap
import itertools
import numpy as np
class MutationChoice:
"""Represent a segment of a sequence with several possible variants.
Parameters
----------
segment
A pair (start, end) indicating the range of nucleotides concerned. We
are applying Python ra... |
1753137 | from .infer import CLPSystem
def command():
import argparse
parser = argparse.ArgumentParser()
# Command mode
parser.add_argument(dest="mode", type=str)
# Server config
parser.add_argument("--host", type=str, default='127.0.0.1')
parser.add_argument("--port", type=int, default=5000)
... |
1753229 | from model.specs import (
Deposit, DepositData, BeaconState, BeaconBlock,
config, SLOTS_PER_EPOCH,
initialize_beacon_state_from_eth1, upgrade_to_altair,
)
SECONDS_PER_SLOT = config.SECONDS_PER_SLOT
MIN_GENESIS_TIME = config.MIN_GENESIS_TIME
from eth2spec.utils.ssz.ssz_impl import hash_tree_root
from eth2sp... |
1753237 | import re
import time
import urlparse
import logging
from paython.exceptions import DataValidationError, MissingDataError
from paython.lib.api import XMLGateway
logger = logging.getLogger(__name__)
class FirstDataLegacy(XMLGateway):
"""First data legacy support"""
# This is how we determine whether or not w... |
1753246 | from rtamt.spec.ltl.discrete_time.visitor import LTLVisitor
from rtamt.node.ltl.predicate import Predicate
from rtamt.node.ltl.variable import Variable
from rtamt.node.ltl.neg import Neg
from rtamt.node.ltl.conjunction import Conjunction
from rtamt.node.ltl.disjunction import Disjunction
from rtamt.node.ltl.implies im... |
1753259 | import FWCore.ParameterSet.Config as cms
process = cms.Process("read")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1)
)
process.source = cms.Source("EmptySource")
process.rpcconfsrc1 = cms.ESProducer("RPCTriggerHsbConfig",
hsb0Mask = cms.vint32(1,2,3,0,1,2,3,0),
hsb1Mask = cms.vint... |
1753329 | from pyrep.robots.end_effectors.gripper import Gripper
class BaxterGripper(Gripper):
def __init__(self, count: int = 0):
super().__init__(count, 'BaxterGripper',
['BaxterGripper_leftJoint',
'BaxterGripper_rightJoint'])
|
1753335 | import time
from seldom.db_operation import SQLiteDB, MySQLDB
# 定义过去时间
past_start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() - 100000))
past_end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() - 100000 + 7200))
# 发布会开始&结束时间
start_time = time.strftime("%Y-%m-%d %H:%M:%S"... |
1753387 | import unittest
from .timeUtil import *
from .timeBase import *
from .systemProcessingBase import *
class TestTimeUtil(unittest.TestCase):
def test_1(self):
# with 计时器() as t:
# 延时(1)
# print(t.取耗时())
t = 时间统计()
延时(1.22)
print(t.取秒())
print(t.取毫秒())
... |
1753402 | try:
import django
if django.VERSION[:3] <= (3, 2, 0):
default_app_config = "rosetta.apps.RosettaAppConfig"
except ImportError:
pass
VERSION = (0, 9, 8)
def get_version(limit=3):
"""Return the version as a human-format string."""
return '.'.join([str(i) for i in VERSION[:limit]])
|
1753435 | from collections import namedtuple
NutritionInformation = namedtuple('NutritionInformation', ['calories', 'fat', 'carbohydrates'])
nutrition = NutritionInformation(calories=100, fat=5, carbohydrates=10)
assert nutrition.calories == 100
|
1753453 | import logging
log = logging.Logger("obj")
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
log.addHandler(ch)
def get_vert_index(e):
p = e.split("/")
return int(p[0]) - 1
def face_from_line(parts):
if len(parts) != 3:
raise Exception("faces must be triangles")
a = get_vert_index(par... |
1753510 | from typing import Pattern, Dict
import regex
from recognizers_text import RegExpUtility
from ...resources.chinese_date_time import ChineseDateTime
from ..extractors import DateTimeExtractor
from ..parsers import DateTimeParser
from ..base_dateperiod import DatePeriodParserConfiguration
from .duration_extractor impor... |
1753515 | from wireless.services.trex_wireless_device_service import WirelessDeviceService
from wireless.trex_wireless_device import WirelessDevice
from wireless.services.trex_wireless_service_event import WirelessServiceEvent
from wireless.services.unit_tests.mocks import _pipe, _Connection
from wireless.pubsub.pubsub import Pu... |
1753526 | import tkinter
from tkinter import ttk, messagebox
def do_hello_world():
messagebox.showinfo("Important Message", "Hello World!")
root = tkinter.Tk()
big_frame = ttk.Frame(root)
big_frame.pack(fill='both', expand=True)
button = ttk.Button(big_frame, text="Click me", command=do_hello_world)
button.pack()
root.m... |
1753531 | from iconservice import *
TAG = 'Receipt'
class InterCallInterface(InterfaceScore):
@interface
def call_event_log(self, p_log_index: int, p_bool: bool, p_addr: Address, p_int: int, p_bytes: bytes, p_str: str):
pass
class Receipt(IconScoreBase):
@eventlog
def event_log_no_index(self, p_bool: ... |
1753539 | import os
import tempfile
import pytest
import numpy as np
from yass.batch import BatchProcessor
@pytest.fixture
def path_to_data(request):
temp = tempfile.NamedTemporaryFile(delete=False)
path = temp.name
def delete_file():
os.unlink(path)
request.addfinalizer(delete_file)
array = (np.... |
1753543 | import dataclasses
import torch
import torch.nn as nn
import torch.nn.functional as F
@dataclasses.dataclass
class Node:
inp: any
module: nn.Module
activated: bool
stride: int
dim: int
def __hash__(self):
return hash(self.module)
class NetFactory(nn.Module):
def __init__(self):
super().__in... |
1753549 | import dgl
class HeteroGraphNeighborSampler:
"""Neighbor sampler on heterogeneous graphs
Parameters
----------
g : DGLHeteroGraph
Full graph
category : str
Category name of the seed nodes.
nhops : int
Number of hops to sample/number of layers in the node flow.
f... |
1753550 | from django.conf import settings
from django.core.management import BaseCommand
from devices.models import Device
os_mapping = {
"w7": "win",
"w10": "win",
"win7": "win",
"win10": "win"
}
class Command(BaseCommand):
def handle(self, *args, **options):
devices = Device.objects.exclude(hos... |
1753565 | import riemann
from riemann import simple, utils
from riemann.encoding import addresses as addr
from riemann.script import serialization as ser
riemann.select_network('zcash_sapling_main')
prevout_addr_1 = 't1S3kN4zusjHtDEwfdaCMgk132bqo9DaYW4'
prevout_addr_2 = 't1VQCUYzApF5eWf4UFAGdWwaFEpBfG2su1A'
# This is the scri... |
1753571 | import unittest
import os
import subprocess
class TestTaxonomicClassification(unittest.TestCase):
'''
Test the taxonomic classification workflows:
We test by checking if the correct files are created at the end of the workflow.
'''
# @classmethod
# def setUpClass(cls):
# os.ch... |
1753590 | import os
from .utils import tempdir_wrapper
def test_tempdir_wrapper():
with tempdir_wrapper("/tmp/foobar") as tempfile:
assert tempfile == "/tmp/foobar"
with tempdir_wrapper() as tempfile:
assert os.path.isdir(tempfile)
assert not os.path.isdir(tempfile)
|
1753607 | import os
import matplotlib.pyplot as plt
import itertools
import pickle
import imageio
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import numpy as np
# training parameters
batch_size = ... |
1753650 | from typing import Dict, List, Tuple, Set, Optional
from collections import defaultdict
from . import crypto
from .crypto import G1, H1, G2, H2, add, multiply, pairing, normalize
from .crypto import PointG1, PointG2
INVALID_SHARE = -1
class Node:
n: int
t: int
idx: int # a one based index, typically a... |
1753655 | from plyer.utils import platform
from plyer.compat import PY2
from kivy.logger import Logger
if platform == 'android':
from android.broadcast import BroadcastReceiver
from . import notification
else:
notification = None
Logger.warning(
'Platform is not android, ignoring AndroidNotification and '... |
1753730 | import scanpy as sc
import anndata as ad
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix
def geneactivity(adata,
gtf_file,
key_added='gene',
upstream=5000,
feature_type='gene',
annotation='HAVANA',
... |
1753737 | import logging
import plistlib
from django.http import HttpResponse
from django.urls import reverse
from zentral.conf import settings
from zentral.utils.certificates import split_certificate_chain
from zentral.utils.payloads import generate_payload_uuid, get_payload_identifier
from zentral.utils.payloads import sign_pa... |
1753743 | import os
import sys
import json
import collections
from datetime import datetime
from alfred.utils import eval_util
def compute_metrics(subgoal_success, subgoal_idx, reward, task, t_agent):
'''
compute metrics for subgoal evaluation
'''
pl = float(t_agent) + 1 # +1 for last action
expert_pl = l... |
1753836 | import requests
from . import FeedSource, _request_headers
class Bittrex(FeedSource):
def _fetch(self):
feed = {}
url = "https://bittrex.com/api/v1.1/public/getmarketsummaries"
response = requests.get(url=url, headers=_request_headers, timeout=self.timeout)
result = response.json()... |
1753858 | import qtree
from qtensor.ProcessingFrameworks import NumpyBackend
from qtensor import utils
from loguru import logger as log
class TensorNet:
@property
def tensors(self):
return self._tensors
def slice(self, slice_dict):
raise NotImplementedError
def __len__(self):
return len... |
1753860 | import random
import string
import sys
from rediscluster import RedisCluster
startup_nodes = [{"host": "127.0.0.1", "port": "7000"}]
# Note: decode_responses must be set to True when used with python3
rc = RedisCluster(startup_nodes=startup_nodes, decode_responses=True)
# 10 batches
batch_set = {i: [] for i in range... |
1753862 | import torch
import torch.nn as nn
class NetworkFC(nn.Module):
def __init__(self, x_dim, out_dim=1, num_feat=30):
super(NetworkFC, self).__init__()
self.fc1 = nn.Linear(x_dim, num_feat)
self.fc2 = nn.Linear(num_feat, num_feat)
self.fc3 = nn.Linear(num_feat, out_dim)
def... |
1753869 | from __future__ import annotations
from librespot import util
from librespot.crypto import Packet
from librespot.proto import Mercury_pb2 as Mercury, Pubsub_pb2 as Pubsub
from librespot.structure import Closeable, PacketsReceiver, SubListener
import io
import json
import logging
import queue
import struct
import thread... |
1753898 | import numpy as np
from termcolor import cprint
from aoc_wim.zgrid import ZGrid
from aoc_wim.zgrid import array2txt
glyphs = """
.##.
#..#
#..#
####
#..#
#..#
..##..
.#..#.
#....#
#....#
#....#
######
#....#
#....#
#....#
#....#
###.
#..#
###.
#..#
#..#
###.
#####.
#....#
#....#
#....#
#####.
#....#
#....#
#...... |
1753906 | from __future__ import absolute_import, division, print_function
from builtins import super, range, zip, round, map
import logging
import os
from glob import glob
import argparse
logger = logging.getLogger(__name__)
def main():
'''This module is designed for cleaning log files that might accumulate in the valida... |
1753955 | from tensorimage.data_augmentation._base import TensorFlowOp
import tensorflow as tf
class AdjustContrast(TensorFlowOp):
def __init__(self, contrast_factor):
super().__init__()
self.contrast_factor = contrast_factor
def apply(self, image):
image = tf.image.adjust_contrast(image, self.... |
1753956 | from pathlib import Path
import os
import sys
import io
import errno
import subprocess
import shutil
import shlex
from pkg_resources import resource_filename
import appdirs
import yaml
from .util import (
mkdir_p,
create_symlink,
resolve_path,
resolve_path_pathlib,
jsondump,
to_string,
... |
1753962 | from fch.core.timemapdownloader import TimeMapDownloader
from fch.core.mementodownloader import MementoDownloader
from fch.follower.followeranalysis import FollowerAnalysis
from fch.follower.followerparser import FollowerParser
import os
import sys
import subprocess
class FollowerCount:
'''
Thi... |
1753973 | from numpy import array as np_array
from numpy import diff as np_diff
from numpy import isnan as np_isnan
from numpy import isinf as np_isinf
# @added 20210424 - Feature #4014: Ionosphere - inference
def get_percent_different(base_value, compare_value, always_return_as_positive=True):
"""
Given a value, deter... |
1753982 | import random
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import spacy
from utils import translate_sentence, bleu, save_checkpoint, load_checkpoint
from torch.utils.tensorboard import SummaryWriter # to print to tensorboard
from torchtext.datasets import Multi30k
from torchtext.da... |
1754016 | import importlib
import logging
from time import sleep, time
import django
import django.conf
from django.template import TemplateSyntaxError, engines
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from .. import (
cache as cache_m,
call,
conf,
exceptions,
... |
1754031 | from overrides import overrides
from allennlp.data import Instance
from allennlp.common.util import JsonDict
from allennlp.predictors.predictor import Predictor
@Predictor.register('sentence_word')
class SentenceWordPredictor(Predictor):
""""Predictor wrapper for the SentenceWordClassificationModel"""
@overr... |
1754068 | import os
import torch
import tqdm
import logging
import csv
from torch.utils.data.dataset import Dataset
from transformers import PreTrainedTokenizer
from typing import List, Optional
from dataclasses import dataclass
from filelock import FileLock
logger = logging.getLogger(__name__)
@dataclass
class DatasetInputEx... |
1754069 | import argparse
from .gui import plot_plotly
from .sme import SME_Structure
from .solve import SME_Solver
from .synthesize import Synthesizer
if __name__ == "__main__":
parser = argparse.ArgumentParser(
"PySME",
description=(
"Synthesizes stellar spectra and determines best fit paramet... |
1754081 | from haystack import indexes
from common.models import Officer, AllegationCategory, Allegation, Investigator, Area, OfficerAllegation
from search.models.session_alias import SessionAlias
from search.models.proxy_models import AllegationCategoryProxy, AllegationProxy
from search.search_backends import CustomEdgeNgramFi... |
1754111 | import os
import tvm
from tvm.contrib import cc, util
def test_add(target_dir):
n = tvm.var("n")
A = tvm.placeholder((n,), name='A')
B = tvm.placeholder((n,), name='B')
C = tvm.compute(A.shape, lambda i: A[i] + B[i], name="C")
s = tvm.create_schedule(C.op)
fadd = tvm.build(s, [A, B, C], "llvm"... |
1754161 | import pytest
from HABApp.core import Items
from HABApp.core.items import Item
@pytest.fixture
def clean_reg():
Items._ALL_ITEMS.clear()
yield
Items._ALL_ITEMS.clear()
def test_pop(clean_reg):
Items.add_item(Item('test'))
assert Items.item_exists('test')
with pytest.raises(Items.ItemNotFou... |
1754199 | import torch
import datasets
import models
# global
device = 'cuda' # used device, which can be 'cpu' or 'cuda'
model = './models/pretrained/resnet34_cifar100.pth' # pretrained teacher model
savedir = './save/resnet34_cifar100_0' # save directory... |
1754226 | import numpy as np
from keras import backend as K
from util.pose_utils import keys_to_stack, stack_by_keys, pose_index
class BaseGenerator(object):
""" A generator that dynamically creates batches from a list of N examples. """
def __init__(self, N, batch_size, create_y):
"""
Para... |
1754275 | from django.conf import settings
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Atom1Feed
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from blog.models import Post
class BlogIndexView(ListView):
template_name = "blog/index.... |
1754305 | import libegomotion
def main(job_id, params):
print 'Job #%d' % job_id
print params
loss = libegomotion.run(
"/home/kivan/source/cv-stereo/config_files/config_kitti_01.txt",
int(params['patch_size'][0]), int(params['num_levels'][0]),
float(params['scale_factor'][0]), int(params['max... |
1754306 | import os
import os.path as osp
from torchvision.datasets.folder import IMG_EXTENSIONS, make_dataset
from .builder import DATASETS
from .video_dataset import VideoDataset
@DATASETS.register_module()
class ImageDataset(VideoDataset):
def __init__(self, ann_file, pipeline, start_index=0, **kwargs):
super... |
1754314 | import hashlib
import os
import tempfile
from azure.confidentialledger import (
LedgerUserRole,
TransactionState,
)
from .constants import NETWORK_CERTIFICATE, USER_CERTIFICATE
from .testcase import ConfidentialLedgerTestCase
CONFIDENTIAL_LEDGER_URL = "https://fake-confidential-ledger.azure.com"
class Conf... |
1754337 | from openapi_schema_to_json_schema import to_json_schema as convert
def test_properties():
schema = {
"type": 'object',
"required": ['bar'],
"properties": {
"foo": {
"type": 'string',
"example": '2017-01-01T12:34:56Z'
},
"... |
1754358 | import typer
from chitra import __version__
from chitra.cli import builder
app = typer.Typer(
name="chitra CLI ✨",
add_completion=False,
)
app.add_typer(
builder.app,
name="builder",
)
@app.command()
def version():
typer.echo(f"Hey 👋! You're running chitra version={__version__} ✨")
|
1754370 | import random
import os
import time
import copy
from TCAction import TCActionBase
from NativeLog import NativeLog
from Utility import Encoding
from Utility import MakeFolder
AP_PROP = ("ssid", "ssid_len", "pwd",
"pwd_len", "channel", "enc", "apc")
SMART_TYPE = ("esp-touch", "airkiss")
TEST_METHOD = ("ssi... |
1754385 | from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.db.models import Q
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from openbook_auth.models import User
from openbook_notifications.models.notification import Notification
cla... |
1754395 | from common import utils
from common.constants import FUN_ARG, LOC_VAR, ENUM_ABBREV_CODE, UNKNOWN_LABEL
from common.constants import VOID, INT, TTYPES
from collections import Counter
from elements.regs import Reg
from elements.offsets import IndirectOffset
def make_variables(locs, binary):
variables = dict()
... |
1754409 | import configparser
from PyQt5 import QtCore, QtGui, QtWidgets
from autobowgui_ui import Ui_Dialog
class AutoBowGui(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super(AutoBowGui, self).__init__(parent)
self.setupUi(self)
self.setFixedHeight(self.sizeHint().height())
... |
1754436 | from deepaffects.realtime.util import get_deepaffects_client, chunk_generator_from_file, chunk_generator_from_url, chunk_generator_from_playlist
TIMEOUT_SECONDS = 10000
apikey = "YOUR_API_KEY"
file_path = "PLAYLIST_PATH"
ticker = "TICKER_SYMBOL"
out_file_name = "OUT_FILE_NAME"
verbose = "True"
metadata = [
('apik... |
1754454 | from django.shortcuts import resolve_url as r
from django.test import TestCase
from orcamentos.proposal.models import Work
from .test_base import BaseWorkTest
class WorkTest(BaseWorkTest, TestCase):
def test_create(self):
self.assertTrue(Work.objects.exists())
def test_str(self):
self.assert... |
1754457 | error_codes = {
"InvalidPoint": "InvalidInput",
"InvalidLinePolygon": "InvalidInput",
"InvalidPointInput": "InvalidInput",
}
error_code_corpus = {
"InvalidUnits": lambda units: f"'{units}' is not a valid unit.",
"InvalidLength": "<length> must be a positive number",
"InvalidArea": "<area> must ... |
1754470 | rb'\fob'
rb'''\fob'''
rb"\fob"
rb"""\fob"""
Rb'\fob'
Rb'''\fob'''
Rb"\fob"
Rb"""\fob"""
rB'\fob'
rB'''\fob'''
rB"\fob"
rB"""\fob"""
RB'\fob'
RB'''\fob'''
RB"\fob"
RB"""\fob"""
|
1754482 | from .base_mermaid import MermaidBase
from .utils import *
import mermaid.utils as py_utils
import mermaid.simple_interface as SI
class MermaidIter(MermaidBase):
def name(self):
return 'mermaid-iter'
def initialize(self,opt):
"""
:param opt: ParameterDict, task settings
:return:... |
1754485 | import time
import torch
class _Timer:
"""Timer."""
def __init__(self, name):
self.name_ = name
self.elapsed_ = 0.0
self.started_ = False
self.start_time = time.time()
def start(self):
"""Start the timer."""
assert not self.started_, "timer has already be... |
1754486 | import logging
import os
import shutil
from typing import Any, Dict, List, NewType, Optional
from .DefBuilder import DefBuilder
from .DocModel import DocModel
from .TemplateOptions import TemplateOptions
from .TemplateRenderer import TemplateRenderer
from .utils import log_and_raise_errors, stringify_front_matter
log... |
1754511 | from setuptools import find_packages, setup
setup(
author="<NAME>",
author_email="<EMAIL>",
name="drillsrs",
long_description="Spaced repetition learning in CLI",
version="0.3",
url="https://github.com/rr-/drill",
packages=find_packages(),
entry_points={"console_scripts": ["drill-srs = ... |
1754575 | import json
import os
import pathlib
from typing import Any, Callable, List
import pytz
import yaml
EXCEPTIONS = {
"TypeError": TypeError,
"KeyError": KeyError,
"ValueError": ValueError,
"NotImplementedError": NotImplementedError,
"UnknownTimeZoneError": pytz.UnknownTimeZoneError,
}
def load_tes... |
1754590 | import requests
import lxml
from lxml import etree
from lxml.html import fromstring
root = etree.parse(r'C:\Users\Kiril\PycharmProjects\Diploma2020\data\corpus.xml')
root = root.getroot()
corpus = etree.SubElement(root, "corpus")
source_examples = dict()
text_num = dict()
status_codes = dict()
failed_elements = dict(... |
1754593 | import logging
from datetime import timedelta
from django.utils.deprecation import MiddlewareMixin
import requests
from requests import HTTPError
from osmaxx.api_client import ConversionApiClient
from osmaxx.conversion import status
from osmaxx.excerptexport.models import Export
from osmaxx.utils.shortcuts import ge... |
1754610 | import fileinput
CRABS = [int(x) for x in fileinput.input()[0].split(',')]
part_1 = part_2 = 10000000000000
for pos in range(max(CRABS) + 1):
part_1_fuel = 0
part_2_fuel = 0
for c in CRABS:
part_1_fuel += abs(pos - c)
delta = abs(pos - c)
part_2_fuel += ((delta + 1) * delta) //... |
1754627 | import _jsonnet
import json
def jsonnet_loads(jsonnet_str, ext_vars=None):
"""
Parses jsonnet string into json
:param jsonnet_str: Jsonnet function
:param ext_vars: External vars that can be passed as {'SOME_PARAM': 'AI2'} and used in the jsonnet as {name: std.extVar("SOME_PARAM")}
:return:
""... |
1754633 | import tempfile
import os
import coremltools
import tensorflow as tf
import PIL.Image
import skimage.transform
import skimage.filters
import numpy
from tensorflow.python.platform import gfile
from image_segmentation import data_generator
import image_segmentation
import requests
from io import BytesIO
class ModelPar... |
1754668 | import numpy as np
class Glorot(object):
"""
Understanding the difficulty of training deep feedforward neural networks
<NAME>, <NAME>
http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf
"""
def __init__(self, **kwargs):
pass
@staticmethod
def __str__():
return "Glo... |
1754711 | from django.core.exceptions import ValidationError
EMPTY_VALUES = (None, "", b"", [], (), {}, False)
def required_validator(value):
if value in EMPTY_VALUES:
raise ValidationError("This field is required.", code="required")
|
1754766 | import importlib
import sys
from unittest import mock
import pytest
@pytest.fixture
def drop_orjson():
import orjson
del orjson
with mock.patch.dict(sys.modules, values={"orjson": None}):
yield
@pytest.fixture
def drop_ujson():
import ujson
del ujson
with mock.patch.dict(sys.modu... |
1754771 | import sys
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
test_dir = os.path.join(current_dir, 'tests')
if 'DJANGO_SETTINGS_MODULE' not in os.environ:
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_email_multibackend.test_settings'
DJANGO_SETTINGS_MODULE = 'django_email_multibackend.test_se... |
1754812 | import pytest
import smt_switch as ss
import pono
from typing import Set
@pytest.mark.parametrize("create_solver", ss.solvers.values())
def test_fts_unroller(create_solver):
solver = create_solver(False)
bvsort4 = solver.make_sort(ss.sortkinds.BV, 4)
bvsort8 = solver.make_sort(ss.sortkinds.BV, 8)
arrs... |
1754843 | import os.path as op
from bento.distutils.tests.common \
import \
DistutilsCommandTestBase
import bento.core.testing
class TestEggInfoCommand(DistutilsCommandTestBase):
@bento.core.testing.skip_if(True)
def test_simple(self):
from bento.distutils.dist \
import \
... |
1754857 | from flask import request, current_app as app
from flask import abort, jsonify
from flask_restplus import Resource, Namespace, fields
from elasticsearch import Elasticsearch
import elasticsearch
from app.main.lib.fields import JsonObject
from app.main.lib.shared_models.shared_model import SharedModel
api = Namespace('... |
1754863 | from django.db import models
from django.contrib.auth.models import User
import time
import datetime
# Create your models here.
class Plan(models.Model):
price_cents = models.IntegerField()
name = models.CharField(max_length=15)
num_bots_allowed = models.IntegerField()
max_trade_size_usd = mode... |
1754871 | from heapq import heappush, heappop, heapify
from collections import defaultdict, Counter
def encode(charFrequency):
heap = [[v, [k, ""]] for k, v in charFrequency.items()]
heapify(heap)
while len(heap) > 1:
left = heappop(heap)
right = heappop(heap)
for pair in left[1:]:
... |
1754890 | from django.db import models
from django.contrib.auth.models import (
BaseUserManager,
AbstractBaseUser,
PermissionsMixin,
)
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.conf import settings
from allauth.account... |
1754904 | import matplotlib.pyplot as plt
import numpy as np
from tabulate import tabulate
############################################
##### Utility functions for evaluation #####
############################################
def init_iou(im_batch, thresh):
iou = dict()
for ix in range(im_batch):
iou[ix + 1] =... |
1754931 | from argparse import Namespace
import GPy
import heapq
import numpy as np
from rdkit import Chem
from sklearn.ensemble import RandomForestRegressor
import torch.nn as nn
from typing import Any, Callable, List, Tuple
from .predict import predict
from chemprop.data import MoleculeDataset, StandardScaler
from chemprop.fe... |
1754969 | create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,'lid':'1' ,'n1':'B' ,'n2':'B'})
create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,'lid':'2' ,'n1':'+' ,'n2':'B'})
create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,'lid':'3' ,'n1':'B' ,'n2':'+'})
create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,... |
1754972 | import os, sys, new
# WARNING: this is all nicely RPython, but there is no RPython code around
# to *compile* regular expressions, so outside of PyPy this is only useful
# for RPython applications that just need precompiled regexps.
#
# XXX However it's not even clear how to get such prebuilt regexps...
import rsre_c... |
1755006 | from sfepy.terms.terms import Term, terms
class LinearVolumeForceTerm(Term):
r"""
Vector or scalar linear volume forces (weak form) --- a right-hand side
source term.
:Definition:
.. math::
\int_{\Omega} \ul{f} \cdot \ul{v} \mbox{ or } \int_{\Omega} f q
:Arguments:
- material... |
1755036 | def conv2d(x, kernel, strides=(1, 1), padding='valid',
data_format=None, dilation_rate=(1, 1)):
"""2D convolution.
# Arguments
kernel: kernel tensor.
strides: strides tuple.
padding: string, "same" or "valid".
data_format: "channels_last" or "channels_first".
... |
1755048 | import os
import random
import datetime
import argparse
import time
import argparse
import numpy as np
from torchvision import models
import torch.nn as nn
import torch
import random
import dlib
import cv2
import imutils
from imutils.video import VideoStream
from imutils import face_utils
from moviepy.editor import *... |
1755057 | from urllib.parse import quote_plus
import logging
from typing import List
from dacite import from_dict
from dacite.exceptions import (
DaciteFieldError,
ForwardReferenceError,
MissingValueError,
UnexpectedDataError,
WrongTypeError,
)
from pymongo import MongoClient
from pymongo.errors import Connec... |
1755078 | class Stack(object):
def __init__(self):
self.stack = []
self.mx = []
self.n = 0
def push(self, x):
self.stack.append(x)
mx = self.mx[-1] if self.n > 0 else float('-inf')
self.mx.append(max(mx, x))
self.n += 1
def pop(self):
if self.n == 0:
... |
1755106 | import json
from flask import current_app, jsonify
from sqlalchemy import asc, desc
from apps.auth.models.users import UserBindProject
from apps.interface.models.interfacecase import InterfaceCase
from apps.interface.models.interfacecaseset import InterfaceCaseSet
from apps.interface.models.interfaceconfig import Int... |
1755122 | import csv
import json
import random
input_file = "/home/justin/Eloquent/Datasets/idk/idkdatasettest_small.tsv"
output_file = "/home/justin/Eloquent/Datasets/idk/idk_dataset_fluency_turk_in.jsonl"
#task = "sentiment"
#taskVerb = "understood what emotional sentiment was conveyed by"
#task = "Respond"
#taskVerb = "unde... |
1755132 | import os
import sys
import time
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
from helpers.cluster import ClickHouseCluster
cluster = ClickHouseCluster(__file__)
node = cluster.add_instance("node", stay_alive=T... |
1755159 | import cgi
import json
import urlparse
from nose.tools import eq_
import mock
from django.core.cache import cache
from django.core.urlresolvers import reverse
from airmozilla.base.tests.testbase import DjangoTestCase, Response
class TestCuratedGroups(DjangoTestCase):
def tearDown(self):
super(TestCura... |
1755197 | from setuptools import setup
import os
import os.path
import fnmatch
def find_files(directory, pattern, recursive=True):
files = []
for dirpath, dirnames, filenames in os.walk(directory, topdown=True):
if not recursive:
while dirnames:
del dirnames[0]
for filename i... |
1755201 | import stem.interpreter, sys
from core.modules.base import Program
from core.modules.console import print
class TorConsole(Program):
"""Interactive interpreter for interacting with Tor directly."""
def __init__(self):
super().__init__()
def run(self):
del sys.argv[:2]
stem.int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.