id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
423658 | import re
from pathlib import Path
from typing import Annotated, cast
import pytest
from box import BoxError
from arti import Artifact, CompositeKey, Fingerprint, Graph, producer
from arti.backends.memory import MemoryBackend
from arti.executors.local import LocalExecutor
from arti.internal.utils import frozendict
fr... |
423666 | from decimal import Decimal
import pytest
from investments.currency import Currency
from investments.money import Money
def test_money():
usd1 = Money(1, Currency.USD)
usd7 = Money(7, Currency.USD)
rub1 = Money(1, Currency.RUB)
rub3 = Money(3, Currency.RUB)
rub5 = Money(5, Currency.RUB)
as... |
423676 | from setuptools import setup
setup(
name="pgn",
version="0.01",
description="Pytorch graph networks",
author="<NAME>",
author_email="<EMAIL>",
packages=["pgn"],
)
|
423691 | import boto3
import sciwing.constants as constants
import wasabi
import json
from collections import namedtuple
from botocore.exceptions import ClientError
import pathlib
import re
import os
from typing import NamedTuple
PATHS = constants.PATHS
AWS_CRED_DIR = PATHS["AWS_CRED_DIR"]
OUTPUT_DIR = PATHS["OUTPUT_DIR"]
cl... |
423696 | from templeplus.pymod import PythonModifier
from toee import *
import tpdp
from utilities import *
import spell_utils
print "Registering sp-Demonhide"
def demonhideSpellGrantDr(attachee, args, evt_obj):
drAmount = 5
drBreakType = args.get_arg(2)
damageMesId = 126 #ID126 in damage.mes is DR
evt_obj.dama... |
423718 | import gc
import math
import os
import time
import numpy as np
import tensorflow as tf
from tentacle.board import Board
from tentacle.data_set import DataSet
from tentacle.ds_loader import DatasetLoader
DATASET_CAPACITY = 16 * 8000
BATCH_SIZE = 32
class ValueNet(object):
def __init__(self, brain_dir, summary_d... |
423742 | import os
import random
import argparse
import numpy as np
class CycleGANArgParser(object):
def __init__(self):
self.parser = argparse.ArgumentParser(description="args")
self.parser.add_argument(
"--batch_size", type=int, default=9, help="Batch size."
)
self.parser.ad... |
423754 | def retry_until(condition):
def retry(request):
try:
return request()
except Exception as exception:
if condition(exception):
return retry(request)
else:
raise exception
return retry
def retry(max_retries):
retries = [0]
... |
423794 | from pymtl import *
from lizard.model.hardware_model import HardwareModel, Result
from lizard.model.flmodel import FLModel
from lizard.util.rtl.cam import Entry
from lizard.bitutil import clog2, clog2nz
from lizard.bitutil.bit_struct_generator import *
class RandomReplacementCAMFL(FLModel):
@HardwareModel.validat... |
423831 | import torch
import cv2
import numpy as np
import torch.backends.cudnn as cudnn
import os
from tqdm import tqdm
from skimage import io
from net.models import deeplabv3plus
from dataset.my_datasets import MyGenDataSet
from torch.utils import data
def generate_mode_seg0(dataloader, model, path):
for ... |
423838 | from adventofcode.year_2020.day_06_2020 import part_one, part_two
test_input = [
'abc',
'',
'a',
'b',
'c',
'',
'ab',
'ac',
'',
'a',
'a',
'a',
'a',
'',
'b',
]
def test_part_one():
assert 11 == part_one(test_input)
def test_part_two():
assert 6 == p... |
423850 | import FWCore.ParameterSet.Config as cms
process = cms.Process("Test")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1000)
)
process.source = cms.Source("PoolSource",
# fileNames = cms.untracked.vstring('/store/data/CRUZET3/Cosmics/RE... |
423894 | import unittest
from biicode.common.model.symbolic.block_version import BlockVersion
from biicode.common.model.brl.brl_block import BRLBlock
from biicode.common.deps.block_version_graph import BlockVersionGraph
class BlockVersionGraphTest(unittest.TestCase):
def empty_test(self):
'''When one is empty, it... |
423900 | import time
print "Multiply"
def mult(x, y):
print "Hmmm..."
time.sleep(3) # Wait 3 seconds
print "Multiplying %s and %s" % (x, y) # Print two values - requires brackets around x and y.
result = x * y
return result
a = raw_input("First number: ")
a = int(a)
b = raw_input("Second number: ")
b = ... |
423994 | import subprocess
import socket
import time
def pytest_funcarg__echoserver(request):
def setup():
p = subprocess.Popen(
['python3', '12_11_echo_server.py'])
time.sleep(1)
return p
def cleanup(p):
p.terminate()
return request.cached_setup(
setup=... |
424001 | import slack
from djangoProject.settings import SLACK_TOKEN
def send_okr_message(array):
name = array[0]
date_time = array[1]
key_result = array[2]
time_spent = array[3]
objective = array[4]
update = array[5]
image = array[6]
slack_id = array[7]
message = {
'channel': '#ok... |
424043 | from vega_lite_linter import Lint
import json
# with open('./vega_lite_linter/test/multiple/test9.json') as json_file:
# demo = json.load(json_file)
# print(demo)
demo = {
"data": {
"url": "data/cars.json"
},
"mark": "bar",
"encoding": {
"x": {
"field": "Horsepower",
... |
424082 | from ir_measures import measures
from .base import Measure, ParamInfo, SumAgg
class _NumRel(measures.Measure):
"""
The number of relevant documents the query has (independent of what the system retrieved).
"""
__name__ = 'NumRel'
NAME = __name__
SUPPORTED_PARAMS = {
'rel': measures.Par... |
424102 | from paypalrestsdk import BillingPlan, ResourceNotFound
import logging
logging.basicConfig(level=logging.INFO)
try:
billing_plan = BillingPlan.find("P-0NJ10521L3680291SOAQIVT")
print("Got Billing Plan Details for Billing Plan[%s]" % (billing_plan.id))
if billing_plan.activate():
billing_plan = Bi... |
424141 | import datetime
import pytest
from django.contrib.sites.models import Site
from django.utils import timezone
from jcasts.episodes.factories import AudioLogFactory, BookmarkFactory, EpisodeFactory
from jcasts.episodes.models import AudioLog, Bookmark, Episode
from jcasts.podcasts.factories import SubscriptionFactory
... |
424150 | from inspect import signature
from functools import wraps
from typing import (
Any,
Union,
Callable,
Optional,
TypeVar,
Tuple,
Dict,
List,
Iterator,
overload,
)
from contextlib import contextmanager
from weakref import WeakValueDictionary
__all__ = ["Model", "Control", "view", ... |
424170 | from micromlgen import platforms
from micromlgen.svm import is_svm, port_svm
from micromlgen.rvm import is_rvm, port_rvm
from micromlgen.sefr import is_sefr, port_sefr
from micromlgen.decisiontree import is_decisiontree, port_decisiontree
from micromlgen.randomforest import is_randomforest, port_randomforest
from micro... |
424196 | from typing import List
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
Wiki: Permutation
Generation in lexicographic order
按照字典顺序生成的下一个排列
"""
n = len(nums)
k = 0
... |
424224 | from tensorflow.keras.initializers import Initializer
from libspn_keras.initializers.dirichlet import Dirichlet
_DEFAULT_ACCUMULATOR_INITIALIZER = Dirichlet(alpha=1.0, axis=-2)
def set_default_accumulator_initializer(initializer: Initializer) -> None:
"""
Configure the default accumulator that will be used ... |
424235 | import tensorflow as tf
import config
import models
from input_data import AudioWrapper
from helper import Trainer, Evaluator
def train(args):
is_training = True
session = tf.compat.v1.Session(config=config.TF_SESSION_CONFIG)
dataset = AudioWrapper(args, 'train', is_training, session)
wavs, labels =... |
424244 | from tensorflow import keras
from tensorflow.keras import layers
from databases import OmniglotDatabase
from models.lasiummamlgan.database_parsers import OmniglotParser
from models.lasiummamlgan.gan import GAN
from models.lasiummamlgan.maml_gan import MAMLGAN
from networks.maml_umtra_networks import SimpleModel
def ... |
424270 | from django.db import models
from officialWebsite.events.models import Topic
class Resource(models.Model):
name = models.CharField(max_length=255, blank=False, default="")
url = models.URLField(blank=False, default="")
topic = models.ManyToManyField(Topic, blank=True)
def __str__(self):
retur... |
424271 | import logging
from typing import List, TYPE_CHECKING
log = logging.getLogger(__name__)
if TYPE_CHECKING:
from rastervision.pipeline.pipeline_config import PipelineConfig # noqa
class Pipeline():
"""A pipeline of commands to run sequentially.
This is an abstraction over a sequence of commands. Each co... |
424274 | from math import *
import sys
if len(sys.argv) != 6:
print "Usage: <script> <N> <t> <M> <field_case> <sbox_case>"
print "field_case: 0 (binary), 1 (prime)"
print "sbox_case: 0 (x^3), 1 (x^5), 2 (x^(-1))"
exit()
N_fixed = int(sys.argv[1])
t_fixed = int(sys.argv[2])
M = int(sys.argv[3]) # Security level... |
424368 | import numpy as np
from numpy.polynomial import Polynomial
def longstaff_schwartz_iter(X, t, df, fit, exercise_payoff,
itm_select=None):
# given no prior exercise we just receive the final payoff
cashflow = exercise_payoff(X[-1, :])
# iterating backwards in time
for i in re... |
424401 | import logging
import time
from typing import Any, Dict, Optional
import aiohttp
from .entities import UserInfo
logger = logging.getLogger(__name__)
DEFAULT_DISCOVERY_RESPONSE_CACHE_PERIOD = 3600 # 1 hour
class OpenIdConnectDiscovery:
"""Retrieve info from OpenID Connect (OIDC) endpoints"""
def __init_... |
424420 | description='HRPT Graphit Filter via SPS-S5'
devices = dict(
graphit=device('nicos_sinq.amor.devices.sps_switch.SpsSwitch',
description='Graphit filter controlled by SPS',
epicstimeout=3.0,
readpv='SQ:HRPT:SPS1:DigitalInput',
... |
424458 | from distutils.core import setup
with open("README.rst") as f:
long_description = f.read()
setup(
name="elara",
packages=["elara"],
version="0.5.4",
license="three-clause BSD",
description="Elara DB is an easy to use, lightweight key-value database written for python that can also be used as a... |
424461 | import codecs
import os
import ujson
from unicodedata import normalize
from collections import Counter
GO = "<GO>" # <s>: start of sentence
EOS = "<EOS>" # </s>: end of sentence, also act as padding
UNK = "<UNK>" # for Unknown tokens
PAD = "<PAD>" # padding not used
def write_json(filename, dataset):
with co... |
424469 | from pprint import pprint
from jnt.patterns import re_whitespaces
import codecs
import xml.etree.ElementTree as et
from glob import glob
from os.path import join
from collections import defaultdict
from jnt.matching.crowdsourcing_words import load_crowd_clusters
from math import ceil
import re
WORDS_PER_PAGE = 5
def... |
424581 | import re
import math
from collections import Counter
import os
import string
from read import *
import pandas as pd
from pandas import ExcelWriter, ExcelFile
import numpy as np
import matplotlib.pyplot as plt
import spacy
from nltk.corpus import stopwords
import nltk
from sklearn.linear_model import LinearRegression
f... |
424610 | from os import path
import tornado.web
from temboardui.web import (
Blueprint,
TemplateRenderer,
)
PLUGIN_NAME = 'activity'
blueprint = Blueprint()
blueprint.generic_proxy(r'/activity/kill', methods=['POST'])
plugin_path = path.dirname(path.realpath(__file__))
render_template = TemplateRenderer(plugin_path +... |
424616 | from .base_requests import AnymailRequestsBackend, RequestsPayload
from ..exceptions import AnymailRequestsAPIError
from ..message import AnymailRecipientStatus
from ..utils import get_anymail_setting
class EmailBackend(AnymailRequestsBackend):
"""
Postal v1 API Email Backend
"""
esp_name = "Postal"
... |
424621 | from namedlist import namedlist
import numpy as np
import gym
from typing import Any, Union, List
import copy
from overcooked_ai_py.mdp.actions import Action, Direction
from overcooked_ai_py.mdp.overcooked_mdp import PlayerState, OvercookedGridworld, OvercookedState, ObjectState, SoupState, Recipe
from overcooked_ai_p... |
424653 | from __future__ import annotations
__all__ = ["TimeValue", "TimeInterval"]
from dataclasses import dataclass
from datetime import datetime
from dateutil.relativedelta import relativedelta
from hijri_converter import Gregorian, Hijri
from . import constants
class TimeValue(relativedelta):
def __init__(
... |
424669 | import logging
class ConfigConverterBase():
def __init__(self):
self.logger = logging.getLogger(__name__)
self.from_version = 0
self.to_version = 0
from_version = 0
to_version = 0
def upgrade(self, old_config):
return old_config
|
424701 | expected_output = {
"Ethernet1/1": {
"advertising_code": "Passive Cu",
"cable_attenuation": "0/0/0/0/0 dB for bands 5/7/12.9/25.8/56 " "GHz",
"cable_length": 2.0,
"cis_part_number": "37-1843-01",
"cis_product_id": "QDD-400-CU2M",
"cis_version_id": "V01",
"cisc... |
424717 | import asyncio
import errno
import os
import sys
import logging
import ipaddress
from distutils.version import LooseVersion
import ray.dashboard.utils as dashboard_utils
import ray.dashboard.optional_utils as dashboard_optional_utils
# All third-party dependencies that are not included in the minimal Ray
# installat... |
424764 | from testing_helpers import wrap
@wrap
def count_threshold_generator(limit, threshold):
return sum(item > threshold for item in xrange(limit))
#def test_count_threshold_generator():
# count_threshold_generator(1000,490) |
424766 | import os
import sys
import subprocess as sp
def_path = sys.argv[-1]
# print(sys.argv)
dumpbin_path = os.environ.get("dumpbin_path", "dumpbin")
export_all = os.environ.get("EXPORT_ALL", "0")=="1"
syms = {}
for obj in sys.argv[1:-2]:
cmd = f'"{dumpbin_path}" -SYMBOLS "{obj}"'
ret = sp.getoutput(cmd)
# pr... |
424805 | import sublime
import sublime_plugin
class SetMarkCommand(sublime_plugin.TextCommand):
def run(self, edit):
mark = [s for s in self.view.sel()]
self.view.add_regions("mark", mark, "mark", "dot", sublime.HIDDEN | sublime.PERSISTENT)
class SwapWithMarkCommand(sublime_plugin.TextCommand):
def r... |
424827 | import string
from django import forms
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import ugettext_lazy as _
from scatterauth.settings import app_settings
class LoginForm(forms.Form):
signature = forms.CharField(widget=forms.HiddenInput, max_length=101)
pubkey ... |
424835 | import os
import sys
import tty, termios
import string
from pyfiglet import Figlet
from .charDef import *
_, n = os.popen('stty size', 'r').read().split()
COLUMNS = int(n)
def mybeep():
print(chr(BEEP_CHAR), end = '')
def mygetc():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
... |
424849 | import numpy as np
import tensorflow as tf
def tf_integral(x,a):
return 0.5*(x*tf.sqrt(x**2+a)+a*tf.log(tf.abs(x+tf.sqrt(x**2+a))))
def tf_pre_parabol(x,par):
x = x-450.
prev = 2.*par*(tf_integral(tf.abs(x),0.25/(par**2))-tf_integral(0,0.25/(par**2)))
return prev+450.
def projector(param,ph,logo):
'''Apply off... |
424852 | import candles as candles
import trendAnalysis as trend
import oscilators as oscilators
from numpy import *
class Strategy:
positiveSignal = 50
negativeSignal = -50
trendVal = 100
defPositiveSignal = 50
defNegativeSignal = -50
defTrendVal = 100
"""Formacje"""
#Odwrocenie trendu w... |
424859 | from parade.cmdline import execute
class TestCmdline(object):
def test_no_cmd(self):
assert execute() == 0
|
424883 | import torch
import torchtestcase
import unittest
from survae.tests.nn import ModuleTest
from survae.nn.layers import GELU, Swish, ConcatReLU, ConcatELU, GatedTanhUnit
class GELUTest(ModuleTest):
def test_layer_is_well_behaved(self):
batch_size = 10
shape = (6,)
x = torch.randn(batch_size... |
424929 | import torch.nn as nn
import torch
from relogic.logickit.base.utils import log
from typing import Tuple
from relogic.logickit.modules.input_variational_dropout import InputVariationalDropout
from relogic.logickit.modules.bilinear_matrix_attention import BilinearMatrixAttention
import copy
import numpy
from relogic.logi... |
424944 | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from System.Collections.Generic import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from ... |
424971 | from django.conf.urls import include, url
from django.views.generic import RedirectView
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^testapp/', include('testmain.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^progressbarupload/?', include('progressbarupload.urls'... |
424991 | import numpy as np
import pytest
import tensorflow as tf
from tfsnippet.ops import pixelcnn_2d_sample, convert_to_tensor_and_cast
class PixelCNN2DSampleTestCase(tf.test.TestCase):
def test_pixelcnn_2d_sample(self):
height, width = 31, 32
self.assertLess(height * width, 10000)
def make_x... |
424997 | import sys
import reedsolo
reedsolo.init_tables(0x11d)
qr_bytes = '''
01000001
10010110
11010110
00010110
01110111
00000110
10010110
01010111
10110110
????????
????????
????????
????????
????????
????????
????????
????????
01000011
????????
00010101
????????
10111110
????????
01010001
????????
11111000
01011000
????... |
425005 | from mc import *
mc = Minecraft()
playerPos = mc.player.getTilePos()
mc.player.setPos(playerPos.x, mc.getHeight(playerPos.x, playerPos.z)+1, playerPos.z)
|
425014 | import psycopg2
def test_pg_server(pg_server):
with psycopg2.connect(**pg_server['params']) as conn:
with conn.cursor() as cursor:
cursor.execute('SELECT version();')
|
425137 | class Solution:
"""
@param nums: a list of integers
@param m: an integer
@return: return a integer
"""
def splitArray(self, nums, m):
# write your code here
start, end = max(nums), sum(nums)
def doable(target):
count = 1
sum = 0
for num... |
425207 | s="""
.a.fy
int x_a = 10
.b.fy
import:
.aa(*)
"""
from fython.test import *
shell('rm -rf a/ a.* b.* c.*')
writer(s)
# w = load('.b', force=1, release=1, verbose=0, run_main=0)
# print(open(w.module.url.fortran_path, 'r').read())
|
425214 | data = (
((-0.010000, -0.090000), (-0.010000, -0.040000)),
((0.589999, -0.040000), (0.730000, -0.040000)),
((0.990000, -0.980000), (0.990000, -0.840000)),
((0.630000, -0.490000), (0.630000, -0.480000)),
((-0.300000, 0.160000), (-0.250000, 0.160000)),
((0.440000, -0.190000), (0.440000, -0.240000)),
((0.150000, -0.630000... |
425253 | from mushroom_rl.policy import Policy, ParametricPolicy
def abstract_method_tester(f, ex, *args):
try:
f(*args)
except ex:
pass
else:
assert False
def test_policy_interface():
tmp = Policy()
abstract_method_tester(tmp.__call__, NotImplementedError)
abstract_method_tes... |
425269 | import copy
import os
import time
from jinja2 import Environment, FileSystemLoader
from os.path import join, dirname
import pytest
from cosmo_tester.framework.test_hosts import Hosts
from cosmo_tester.framework import util
from .cfy_cluster_manager_shared import REMOTE_CLUSTER_CONFIG_PATH
CONFIG_DIR = join(dirname(_... |
425285 | from unittest import TestCase, skip
import mock
from pjon_python.strategies.pjon_hwserial_strategy import PJONserialStrategy, UnsupportedPayloadType
class TestPJONserialStrategy(TestCase):
def test_send_byte_should_convert_int_to_chr(self):
with mock.patch('serial.Serial', create=True) as ser:
... |
425328 | import numpy as np
from scipy import stats
import torch
def test(test_loader, encoder, decoder, critic_x):
reconstruction_error = list()
critic_score = list()
y_true = list()
for batch, sample in enumerate(test_loader):
reconstructed_signal = decoder(encoder(sample['signal']))
reconst... |
425352 | import unittest
from ABBA import ABBA
import numpy as np
import warnings
from util import dtw
def ignore_warnings(test_func):
def do_test(self, *args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
test_func(self, *args, **kwargs)
return do_test
clas... |
425374 | import csv
import codecs
import random
from utils import normalizeString
def process(_f):
csvfile = codecs.open(_f, 'r+', 'utf_8_sig')
reader = csv.reader(csvfile)
datas = []
for line in reader:
if len(line) != 6: continue
q, d, label = line[3], line[4], line[5]
q = " ".join(q... |
425385 | import csv
import json
from datetime import datetime
import django
import pytest
from django.contrib.auth.models import User
from django.utils import timezone
import data_browser.models
from .core import models
from .util import update_fe_fixture
def dump(val):
print(json.dumps(val, indent=4, sort_keys=True))
... |
425392 | def test_str(RS, str_data):
assert RS(str_data, 0.8) != str_data
assert type(RS(str_data, 0.8)) is str
assert len(RS(str_data, 0.8, repetition=3)) == 3
def test_list(RS, list_data):
assert RS(list_data, 0.8) != list_data
assert type(RS(list_data, 0.8)) is list
assert len(RS(list_data, 0.8, rep... |
425394 | import os
from prometheus_client.core import GaugeMetricFamily
DEFAULT_LOG_PATH = '/var/log/cloudchef/vmware_exporter/vmware_exporter.log'
APP_NAME = 'vmware-exporter'
log_path = os.environ.get('LOG_PATH', DEFAULT_LOG_PATH)
cloudentry_path = '/v1/kv/cmp/cloud_entry/vsphere?recurse'
vms_path = '/v1/kv/cmp/resource/vm... |
425439 | from django.urls import path
from story.views import StoryListView
app_name = "story"
urlpatterns = [
path('', StoryListView.as_view(), name='stories'),
]
|
425440 | import visr_bear
import numpy as np
import numpy.testing as npt
from pathlib import Path
import scipy.signal as sig
from utils import data_path
def do_render(renderer, period, objects=None, direct_speakers=None, hoa=None):
not_none = [x for x in [objects, direct_speakers, hoa] if x is not None][0]
length = no... |
425469 | from unittest import TestCase
from memory import RamController
from memory import MemoryController
class RamTests(TestCase):
def test_create_ram(self):
ram = RamController(500)
self.assertEqual(len(ram), 500)
def test_read_write(self):
ram = RamController(32)
ram[0] = 0xFF
... |
425503 | import ast
import collections
import contextlib
import functools
import inspect
import io
import logging
import sys
import traceback
import types
from typing import Any, Optional, Union
log = logging.getLogger(__name__)
# A type alias to annotate the tuples returned from `sys.exc_info()`
ExcInfo = tuple[type[Exceptio... |
425546 | from gaphor.plugins.console.console import docstring_dedent
def test_docstring_with_leading_space():
docstr = """\
line one
line two
"""
expected = "line one\nline two\n"
assert docstring_dedent(docstr) == expected
def test_docstring_without_leading_space():
docstr = """lin... |
425568 | class Options:
def __init__(self, *, filename: str, collapse_single_pages: bool, strict: bool):
self.filename = filename
self.collapse_single_pages = collapse_single_pages
self.strict = strict
|
425588 | from mamba import description, it, before
from unittest.mock import MagicMock
from crowd_anki.history.archiver import AllDeckArchiver
with description(AllDeckArchiver) as self:
with before.each:
self.deck_without_children = MagicMock()
self.deck_manager = MagicMock()
self.deck_manager.lea... |
425599 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.stats, name='rq_stats'),
url(r'^queues/(?P<queue>.+)/$', views.queue, name='rq_queue'),
url(r'^workers/(?P<worker>.+)/$', views.worker, name='rq_worker'),
url(r'^jobs/(?P<job>.+)/$', views.job, name='rq_job'),
u... |
425617 | import os
import sys
if(len(sys.argv) != 2):
print(__file__ + ' file.lua')
exit()
lua_file = sys.argv[1]
os.system("python2.7 luatool.py --port /dev/tty.SLAB_USBtoUART --src " + lua_file + " --dest " + lua_file + " --baud 115200") |
425631 | def method1(n: int) -> int:
'''Return a list of prime factors of an integer by
first checking if the modulo of the value of d and number is equal to 0.
Then applying the for loop inside the for loop to count a factor only once.
'''
divisors = [d for d in range(2, n // 2 + 1) if n % d == 0]
retu... |
425648 | import pytest
from tests import assert_result
from presidio_analyzer.predefined_recognizers import CryptoRecognizer
@pytest.fixture(scope="module")
def recognizer():
return CryptoRecognizer()
@pytest.fixture(scope="module")
def entities():
return ["CRYPTO"]
# Generate random address https://www.bitaddres... |
425651 | from myhdl import block, Signal, intbv, always, concat, always_seq, instances, modbv
@block
def encode(clock, reset, video_in, audio_in, c0, c1, vde, ade, data_out, channel='BLUE'):
"""
This module performs the TMDS encoding logic of a hdmi encoder for a particular channel.
It is modelled after the xili... |
425697 | import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import numpy as np
import tensorflow as tf
import cv2
import cfg
from shufflenetv2_centernet_V2 import ShuffleNetV2_centernet
# from shufflenetv2_centernet_V2_SEB import Shufflenetv2_Centernet_SEB
# from yolov3_centernet_V2 import yolov3_centernet
from create_label im... |
425701 | import torch
import torch.nn as nn
import torch.nn.functional as F
class PerceptionNet(nn.Module):
def __init__(self):
super(PerceptionNet, self).__init__()
self.conv1 = nn.Conv2d(3, 24, 5, stride=2, bias=False)
self.bn1 = nn.BatchNorm2d(24)
self.conv2 = nn.Conv2d(24, 36, 5, strid... |
425704 | import pytest
import magma as m
import magma.testing
import fault as f
def test_basic():
class _Top(m.Circuit):
io = m.IO(I=m.In(m.Bit), O=m.Out(m.Bit)) + m.ClockIO()
with m.compile_guard("COND", defn_name="COND_compile_guard"):
out = m.Register(m.Bit)()(io.I)
io.O @= io.I
... |
425730 | import os
class Config:
def __init__(self, workspace):
self._config = dict()
self._path = os.path.join(workspace.root, "package.config")
lines = None
if os.path.exists(self._path):
with open(self._path) as f:
lines = f.readlines()
for line in ... |
425734 | import pytest
from bocadillo import configure, create_client, static
FILE_DIR = "js"
FILE_NAME = "foo.js"
FILE_CONTENTS = "console.log('foo!');"
def _create_asset(static_dir):
asset = static_dir.mkdir(FILE_DIR).join(FILE_NAME)
asset.write(FILE_CONTENTS)
return asset
def test_assets_are_served_at_stati... |
425747 | import json
import os
from tensorflow.python.client import timeline
from runai.utils import Hook
class Profiler(Hook):
def __init__(self, module, method, steps, dst):
super(Profiler, self).__init__(module, method)
self._timeline = None
self._step = 0
self._steps = steps
se... |
425802 | import sys
import limix
from limix.core.covar import LowRankCov
from limix.core.covar import FixedCov
from limix.core.covar import FreeFormCov
from limix.core.covar import CategoricalLR
from limix.core.mean import MeanBase
from limix.core.gp import GP
import scipy as sp
import scipy.stats as st
from limix.mtSet.core.i... |
425803 | import collections
class CupClass():
def __init__(self, id):
self.id = id
self.next = None
def problem1(puzzle_input,rounds):
cups = collections.deque([int(i) for i in puzzle_input],len(puzzle_input))
current_cup = cups[0]
length = len(cups)
for move in range(1,rounds+1):
... |
425847 | import importlib
import logging
import traceback
from threading import Thread
from typing import Optional
from django.conf import settings
from django.template.loader import render_to_string
from magic_notifier.utils import get_settings, import_attribute
logger = logging.getLogger("notifier")
class ExternalSMS:
... |
425849 | import torch
import torch.nn as nn
import torch.nn.functional as F
class MLP_Encoder(nn.Module):
def __init__(self, input_dim=784, hidden_dim=256, latent_dim=32, nb_layers=2, deterministic=False, dropout_p=0.0):
"""
A simple MLP encoder with gated activations.
:param input_dim: input featu... |
425862 | from math import sqrt, floor, ceil
from datetime import datetime
from asyncio import TimeoutError
from discord import Message, Color
from discord.errors import Forbidden
from discord.ext.commands import (
Cog,
Context,
command,
group,
cooldown,
BucketType,
)
from nagatoro.converters import Mem... |
425879 | import tensorflow as tf
import matplotlib.pyplot as plt
def segmentation_to_image(pred):
img = tf.argmax(pred, axis=-1)
img = img[..., tf.newaxis]
return tf.keras.preprocessing.image.array_to_img(img)
def predict_tf(model):
def predict_func(sample):
pred = model.predict(tf.expand_dim... |
425933 | from datetime import datetime, timedelta
from time import time
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from drawquest.apps.quest_comments.models import QuestComment
from drawquest.apps.quests.models import Quest
from drawquest.apps.quests.top import top_quests_... |
425954 | from discord.ext import commands
from discord.ext.commands.errors import NotOwner
import errors
import functions
from bot_config import OWNER_ID
def is_owner():
async def predicate(ctx):
if ctx.message.author.id != OWNER_ID:
raise NotOwner("This command can only be run by the owner.")
... |
425966 | import os
import sys
import re
import json
import pandas as pd
import collections
import pytz
from datetime import datetime, timedelta
try:
from jaws import tilt_angle, fsds_adjust
except ImportError:
import tilt_angle, fsds_adjust
#############################################################################... |
425978 | class NeispyException(Exception):
pass
class ArgumentError(NeispyException):
def __init__(self):
super().__init__("인자값이 틀립니다.")
class HTTPException(NeispyException):
def __init__(self, code: int, message: str):
super().__init__(f"{code} {message}")
class MissingRequiredValues(HTTPExcep... |
426000 | import itertools
import typing
from typing import Dict, List, Optional
from hearthstone.asyncio import asyncio_utils
from hearthstone.simulator.agent.actions import EndPhaseAction
from hearthstone.simulator.agent.agent import AnnotatingAgent
from hearthstone.simulator.core.randomizer import Randomizer
from hearthstone... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.