id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
475799 | import pytest
from ceph_deploy.cli import get_parser
from ceph_deploy.tests.util import assert_too_few_arguments
class TestParserRepo(object):
def setup(self):
self.parser = get_parser()
def test_repo_help(self, capsys):
with pytest.raises(SystemExit):
self.parser.parse_args('re... |
475816 | import glob
import os
def _path(*args):
return os.path.join(os.path.dirname(__file__), *args)
# pyxbld for pyximport (from cython):
pyxbld = open(_path('template.pyxbld')).read()
# Sundials:
sundials_templates_dir = _path('sundials_templates')
sundials = {
os.path.basename(pth): open(pth).read() for pth in ... |
475846 | import graphics as gfx
import common
import vector
import apple as appleFuncs
SPEED = 12
def testForAppleProjectileCollision(projectile, apples):
for apple in apples[:]:
appleCenter = apple.getCenter()
projCenter = projectile.getCenter()
if vector.distanceBetween(appleCenter, projCente... |
475857 | from django.urls import path
from users import views as users_views
from django.contrib.auth import views as auth_views
from django.conf.urls import url
urlpatterns = [
path('', users_views.profile, name='profile'),
path('home/', users_views.home, name='home'),
path('register/', users_views.register, name=... |
475871 | from utils_io_folder import get_immediate_childfile_paths
from utils_json import read_json_from_file, write_json_to_file
def merge_posetrack_jsons():
posetrack_annotation_folder = "../data/Data_2017/posetrack_data/annotations/train"
save_json_path = "posetrack_merged_train.json"
gt_json_paths = get_immedi... |
475872 | import os
import glob
from flask import Flask
from flask import jsonify
from flask import request, render_template
from webapp import app
#from model.util import *
from SigNet import main1, getpredictions
valid_mimetypes = ['image/jpeg', 'image/png', 'image/tiff']
global model
# def get_predictions(img_name):
# ... |
475888 | from pathlib import Path
import pytest
from sqlalchemy import Column, String
from flask_filealchemy.loaders import (
BaseLoader,
loader_for,
MarkdownFrontmatterDirectoryLoader,
YAMLDirectoryLoader,
YAMLFileLoader,
)
def test_base_loader_does_not_validate():
with pytest.raises(NotImplementedE... |
475910 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
class SVDEmbedding(nn.Module):
def __init__(
self,
num,
rank,
output_dim,
padding_idx=None,
... |
475931 | class Winratio:
def __init__(self, **kwargs):
self.losses = kwargs.get("Losses", kwargs.get("losses", 0)) or 0
self.wins = kwargs.get("Wins", kwargs.get("wins", 0)) or 0
@property
def winratio(self):
_w = self.wins /(self.matches_played if self.matches_played > 1 else 1) * 100.0
return int(_w) if _w % 2 == 0... |
475961 | from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('validator', '0003_celery_task_20190402_1445'),
]
operations = [
migrations.CreateModel(
name='DatasetConfiguration',
fields=[
... |
475983 | data = (
'Ruo ', # 0x00
'Bei ', # 0x01
'E ', # 0x02
'Yu ', # 0x03
'Juan ', # 0x04
'Yu ', # 0x05
'Yun ', # 0x06
'Hou ', # 0x07
'Kui ', # 0x08
'Xiang ', # 0x09
'Xiang ', # 0x0a
'Sou ', # 0x0b
'Tang ', # 0x0c
'Ming ', # 0x0d
'Xi ', # 0x0e
'Ru ', # 0x0f
'Chu ', # 0x10
'Zi ... |
475996 | import pkg_resources
import warnings
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import torch
from .. import setting
from . import activation
from . import concatenator
from . import array2diagmat
from . import array2symmat
from . import deepsets
from . import gcn
from . import grad_gcn
f... |
476080 | import pytest
from data.test_data import generate_unstructured_test_data
from lofo import Dataset
def test_dataset():
df = generate_unstructured_test_data(1000, text=True)
features = ["A", "B", "C", "D", "D2", "E"]
# Exception: feature group row count is not equal to the features' row count
feature_g... |
476140 | from Utils import Attribute
class View:
def View(self,name):
self.mName = name
self.attributes = []
self.mChildren = []
@classmethod
def fromELement(cls,element):
mName = element.tag
viewCls = cls(mName)
attributeslist = []
mChildre... |
476141 | import os
dataset_path = r"D:\free_corpus\base"
transformed_path = r"D:\free_corpus\processed"
packed_path = r"D:\free_corpus\packed"
# Containing metadata.csv and mels/, in dir of each dataset
# and lang_to_id.json and spk_id.json in transformed_path and packed_path
include_corpus = ['caito_de_de', 'caito_en_uk', 'c... |
476173 | import socket
import threading
import docker
import time
import iptc
from enum import Enum
from src.logger import logger
from src.OneWayThread import OneWayThread
class ContainerThread(threading.Thread):
def __init__(self, source, connection, config):
super().__init__()
self.source = source
... |
476199 | from zipf import make_zipf, is_zipf
generated = make_zipf(5)
print('generated distribution: {}'.format(generated))
generated[-1] *= 2
print('passes test with default tolerance: {}'.format(is_zipf(generated)))
print('passes test with tolerance of 1.0: {}'.format(is_zipf(generated, rel=1.0)))
|
476223 | from numpy import arcsin, exp
def _comp_point_coordinate(self):
"""Compute the point coordinates needed to plot the Slot.
Parameters
----------
self : SlotW29
A SlotW29 object
Returns
-------
point_dict: dict
A dict of the slot point coordinates
"""
Rbo = self.get... |
476225 | import torchvision.ops # noqa: F401
from torch2trt_dynamic.plugins import create_roipool_plugin
from torch2trt_dynamic.torch2trt_dynamic import (get_arg, tensorrt_converter,
trt_)
@tensorrt_converter('torchvision.ops.roi_pool')
def convert_roi_pool(ctx):
input = g... |
476269 | import pyaudio
import socket
import select
from pynput.keyboard import Key, Listener, Controller
import threading
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096
HOST = socket.gethostname()
PORT = 8082
streaming = True
audio = pyaudio.PyAudio()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s... |
476282 | import re
def get_errors(query: str, offset_field: str):
errors = []
if not is_valid_timestamp(query, offset_field):
errors.append(f'The query should have ascending ordering by {offset_field}')
if not is_valid_offset(query):
errors.append('Please use ${OFFSET} with a gt condition (not gte)... |
476296 | from .variables import get_variable, set_variable, delete_variable, Attributes
from .variables import GLOBAL_NAMESPACE, DEFAULT_ATTRIBUTES
from .privileges import privileges, patch_current_process_privileges
from .boot import get_boot_order, get_boot_entry, set_boot_entry, set_boot_order
from .boot import get_parsed_... |
476299 | import geoip2.database
import geoip2.webservice
import os
from pydantic import BaseModel
from tracardi.domain.named_entity import NamedEntity
from tracardi.service.singleton import Singleton
class PluginConfiguration(BaseModel):
source: NamedEntity
ip: str
class GeoLiteCredentials(BaseModel):
accountId... |
476309 | import os
import sys
from distutils.core import setup
from pathlib import Path
import numpy as np
from transonic.dist import make_backend_files, init_transonic_extensions
path_here = Path(__file__).parent.absolute()
include_dirs = [np.get_include()]
pack_name = "future"
paths = tuple((path_here / pack_name).glob("... |
476384 | import dash_bootstrap_components as dbc
from dash import html
from .util import make_subheading
badge = html.Div(
[
dbc.Badge("Primary", color="primary", className="me-1"),
dbc.Badge("Secondary", color="secondary", className="me-1"),
dbc.Badge("Success", color="success", className="me-1"),... |
476400 | import random
import asyncio
import sc2
from sc2 import Race, Difficulty
from sc2.constants import *
from sc2.player import Bot, Computer
from proxy_rax import ProxyRaxBot
class SlowBot(ProxyRaxBot):
async def on_step(self, iteration):
await asyncio.sleep(random.random())
await super().on_step(it... |
476434 | import numpy as np
import matplotlib.pyplot as plt
RANDOM_SEED = 42
NUM_VIDEOS = 1000
MAX_NUM_BITRATES = 10
MIN_NUM_BITRATES = 3
MAX_NUM_CHUNKS = 100
MIN_NUM_CHUNKS = 20
# bit rate candidates
# [200, 300, 450, 750, 1200, 1850, 2850, 4300, 6000, 8000] # Kbps
MEAN_VIDEO_SIZE = [0.1, 0.15, 0.38, 0.6, 0.93, 1.43, 2.15, ... |
476439 | class UserModel(Tower):
@model_property
def inference(self):
assert self.input_shape[0]==224, 'Input shape should be 224 pixels'
assert self.input_shape[1]==224, 'Input shape should be 224 pixels'
# Create some wrappers for simplicity
def conv2d(x, W, b, s, padding='SAME'):
... |
476466 | from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPool2D, ZeroPadding2D, Flatten
from tensorflow import keras
import tensorflow as tf
import numpy as np
class BaseModel():
"""
Base class used to implement a model.
This class itself should not instantiated.
"""
def __init__(self, comm, ... |
476485 | from flask_socketio import SocketIO
socketio = SocketIO(cors_allowed_origins='*')
def initSocket(app):
socketio.init_app(app)
|
476515 | from __future__ import absolute_import
import os
from django.conf import settings
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'troupon.settings')
app = Celery('troupon')
app.config_from_object('django.conf:settings')
app.... |
476529 | from ctypes import c_int, c_size_t, c_void_p
from .dll import _bind, SDLFunc, AttributeDict
from .stdinc import SDL_bool
__all__ = [
# Defines
"SDL_CACHELINE_SIZE",
]
# Constants & enums
SDL_CACHELINE_SIZE = 128
# Raw ctypes function definitions
_funcdefs = [
SDLFunc("SDL_GetCPUCount", None, c_int),
... |
476530 | import argparse
import os
import math
import ruamel.yaml as yaml
import numpy as np
import random
import time
import datetime
import json
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from models.model_captioning import XVLM
import utils
from utils.checkp... |
476566 | from .scp_policy_resource import ScpPolicyResource
from .scp_attachment_resource import ScpAttachmentResource
|
476618 | import numpy as np
import pytest
from pytest_lazyfixture import lazy_fixture
# Fixtures must be visible for lazy_fixture() calls.
from .fixtures import * # noqa
@pytest.fixture(
params=(
lazy_fixture('cof1'),
lazy_fixture('cof2'),
lazy_fixture('cof3'),
),
)
def case_data(request):
... |
476625 | import os
import sys
from typing import Dict, Set
import setuptools
is_py37_or_newer = sys.version_info >= (3, 7)
package_metadata: dict = {}
with open("./src/datahub_airflow_plugin/__init__.py") as fp:
exec(fp.read(), package_metadata)
def get_long_description():
root = os.path.dirname(__file__)
with... |
476626 | from typing import TYPE_CHECKING
from PySide2.QtGui import QKeySequence, Qt
from .menu import Menu, MenuEntry, MenuSeparator
if TYPE_CHECKING:
from angrmanagement.ui.widgets.qlog_widget import QLogWidget
class LogMenu(Menu):
def __init__(self, log_widget: 'QLogWidget'):
super().__init__("", parent=... |
476635 | from decimal import Decimal as D
from django.test import TestCase
from parameterized import parameterized
from capone.api.actions import create_transaction
from capone.api.actions import credit
from capone.api.actions import debit
from capone.models import LedgerEntry
from capone.models import MatchType
from capone.m... |
476637 | import pickle
import numpy as np
import pytest
import tensorflow as tf
from garage.envs import GymEnv
from garage.tf.q_functions import ContinuousMLPQFunction
from tests.fixtures import TfGraphTestCase
from tests.fixtures.envs.dummy import DummyBoxEnv
class TestContinuousMLPQFunction(TfGraphTestCase):
@pytest... |
476642 | import pytest
import torch
from utils import seq_len_to_mask
from module import DotAttention, MultiHeadAttention
torch.manual_seed(1)
q = torch.randn(4, 6, 20) # [B, L, H]
k = v = torch.randn(4, 5, 20) # [B, S, H]
key_padding_mask = seq_len_to_mask([5, 4, 3, 2], max_len=5)
attention_mask = torch.tensor([1, 0, 0, 1, ... |
476661 | import torch
class Net(torch.jit.ScriptModule):
def __init__(self, n: int):
super().__init__()
self._conv1 = torch.nn.Conv2d(
1, 10, 4, stride=1, padding=0, dilation=1, groups=1, bias=True
)
self._conv2 = torch.nn.Conv2d(
10, 10, 3, stride=1, padding=0, dilat... |
476675 | from abc import ABC, abstractmethod
from typing import Dict, Callable, Any, Optional, List
from dataclasses import dataclass
@dataclass
class BaseParams:
cpus_per_worker: int = 1
use_gpu: bool = False
gpus_per_worker: Optional[int] = None
def __post_init__(self):
if self.gpus_per_worker and not... |
476711 | from __future__ import unicode_literals
import six
import abc
import logging
from jsonpointer import resolve_pointer, JsonPointerException
logger = logging.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta)
class BaseTransformer(object):
@abc.abstractmethod
def _transform_string(self, string, doc):
... |
476727 | import time
from datetime import datetime
from smtplib import SMTPRecipientsRefused
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import password_reset, password_reset_confirm
from django.... |
476729 | import numpy as np
import argparse
import json
import os
# Function copy from video2tfrecords.py
def split_equal(ids: list, duration: list, num: int, min_duration: int = 256):
sort = sorted(zip(duration, ids))[::-1]
ids_split = [[] for i in range(num)]
duration_spit = [[] for i in range(num)]
durati... |
476779 | import sj
import sys
status = 0
def test(prefix, file, rest):
sj.create_and_cd_jalangi_tmp()
ana = sj.execute_return_np(sj.JALANGI_SCRIPT+' --inlineIID --inlineSource --analysis ../src/js/sample_analyses/ChainedAnalyses.js --analysis ../src/js/runtime/SMemory.js --analysis ../src/js/sample_analyses/pldi16/Tra... |
476840 | from tests.utils import W3CTestCase
class TestFlexbox_Inline(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'flexbox_inline'))
|
476896 | def omp_sections_private():
sum = 7
sum0 = 0
if 'omp parallel':
if 'omp sections private(sum0)':
if 'omp section':
sum0 = 0
for i in range(0, 400):
sum0 += i
if 'omp critical':
sum += sum0
... |
476903 | import logging
import unittest
from clarifai.rest import ApiError, ClarifaiApp
class TestAuth(unittest.TestCase):
"""
unit test for api auth
"""
def test_auth_with_invalid_key(self):
""" instantiate with key """
api_preset_key = 'abc'
with self.assertRaises(ApiError):
ClarifaiApp(api_key=... |
476967 | import numpy as np
import matplotlib.pyplot as plt # For plotting
import pdb
import pandas as pd
import seaborn as sns
from scipy import stats
data1 = np.load("train_nu.npz")
#data1 = np.load('pipe_test_1dnu.npz')
nu = data1['nu_1d']
#nu = np.sort(nu)
print('nu is',nu)
############################
#profile viscosity
... |
476970 | class StorageNotFound(Exception):
pass
class StorageSettedError(Exception):
pass
class MismatchedVersionError(Exception):
pass
class InvalidPassword(Exception):
pass
|
476980 | from pymtl import *
from lizard.util.rtl.interface import UseInterface
from lizard.util.rtl.method import MethodSpec
from lizard.util.rtl.drop_unit import DropUnit, DropUnitInterface
from lizard.util.rtl.register import Register, RegisterInterface
from lizard.mem.rtl.memory_bus import MemMsgType, MemMsgStatus
from liza... |
476985 | import FWCore.ParameterSet.Config as cms
source = cms.Source("EmptySource")
from GeneratorInterface.Hydjet2Interface.hydjet2DefaultParameters_cff import *
generator = cms.EDFilter("Hydjet2GeneratorFilter",
collisionParameters5020GeV,
qgpParameters,
hydjet2Parameters,
fNhsel = cms.int32(2), # Flag to include je... |
477004 | import urllib.request as request
import os, datetime, json
url = 'https://ladsweb.modaps.eosdis.nasa.gov/archive/allData'
def get_lev_pro_year(level, product, year):
ref = url + '/%s/%s/%s.json'%(level, product, year)
req = request.Request(ref)
response = request.urlopen(req)
return json.loads(respons... |
477027 | from followthemoney.rdf import URIRef, Identifier
from followthemoney.types.common import PropertyType
from followthemoney.util import defer as _
class ChecksumType(PropertyType):
"""Content hashes calculated using SHA1. Checksum references are used by
document-typed entities in Aleph to refer to raw data in ... |
477050 | def palin_perm(str):
bitvec = [0] * 26
str = str.lower()
for char in str:
charCode = ord(char) - ord("a")
if charCode >= 0 and charCode < 26:
if bitvec[charCode] == 0:
bitvec[charCode] = 1
else:
bitvec[charCode] = 0
one = False
... |
477057 | class RhinoDeselectAllObjectsEventArgs(EventArgs):
# no doc
Document=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Document(self: RhinoDeselectAllObjectsEventArgs) -> RhinoDoc
"""
ObjectCount=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get:... |
477085 | from __future__ import print_function,division
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
class Evaluator(object):
def __init__(self,loss=nn.MSELoss(),batch_size=64,delay=36):
self.loss=loss
self.batch_size=batch_size
self.delay=delay
def evaluate(self,m... |
477099 | import string # forced import by CodeWars kata
from string import ascii_uppercase as up, ascii_lowercase as low, \
ascii_letters as az, maketrans
ROT13 = maketrans(low[13:] + low[:13] + up[13:] + up[:13], az)
def rot13(message):
return message.translate(ROT13)
|
477127 | class TestCRUD:
def test_add_one(self, db):
result = db.add_one(
{'name': 'alice', 'url': 'alice.com', 'method': 'get'})
errors = result.get('errors')
success = result.get('success')
assert errors is None
assert success is True
def test_fetch_one(self, db, ... |
477154 | import json
import unittest
import mock
from src.access_token_common import AccessTokenCommon
class AccessTokenCommonTest(unittest.TestCase):
mock_os_environ_access_token = {"ACCESS_TOKEN_FROM_ENV": "access token 42"}
@mock.patch.dict("os.environ", mock_os_environ_access_token, clear=True)
def test_ac... |
477181 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.nonparametric.smoothers_lowess import lowess as smlowess
from statsmodels.sandbox.regression.predstd import wls_prediction_std... |
477193 | import torch
from torch import nn
class LiteConv3x3(nn.Module):
"""Lite 3x3 convolution"""
def __init__(self):
super(LiteConv3x3, self).__init__()
def forward(self, input):
return input
class AG(nn.Module):
"""Aggregation gate"""
def __init__(self):
super(AG, self).__i... |
477196 | import os
import copy
import click
import uuid
from zipfile import ZipFile, ZIP_DEFLATED
from io import BytesIO
from tcfcli.libs.utils.yaml_parser import yaml_dump
from tcfcli.common.template import Template
from tcfcli.libs.utils.cos_client import CosClient
from tcfcli.common.user_exceptions import TemplateNotFoundExc... |
477230 | import pytest
import time
from common.exceptions import PlenumTypeError, PlenumValueError
from stp_core.ratchet import Ratchet
from plenum.common.throttler import Throttler
def test_throttler_init_invalid_args():
for windowSize in (None, '5', [4]):
with pytest.raises(PlenumTypeError):
Throttl... |
477234 | import sys
from bisect import bisect_left
def bin_number(n, size=4):
return bin(n)[2:].zfill(size)
def iar():
return list(map(int, input().split()))
def ini():
return int(input())
def isp():
return map(int, input().split())
def sti():
return str(input())
def par(a):
print(" ".join(li... |
477237 | import os
from abc import ABC
import datetime
import logging
from typing import Callable, Iterator, Union, Optional, List, Type
from enum import Enum, IntEnum
import numpy
import h5py
from s100py.s1xx import s1xx_sequence, S1xxObject, S1xxCollection, S1xxDatasetBase, S1xxGridsBase, S1XXFile, h5py_string_dtype... |
477285 | import torch
import torch.nn as nn
from torch.nn import init
from torch.optim import lr_scheduler
import torchvision.models as torch_models
'''
Helper functions for model
Borrow tons of code from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
'''
def get_scheduler(optimizer, ... |
477320 | import torch
import os
import sys
import numpy as np
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from ..utils import tqdm, HiddenPrints
class Evaluator():
"""
Evaluation class.
Performs evalution on a given model and DataHandler.
Two main functions can be used:... |
477323 | import numpy as np
import cv2
import string
import math
import os
import uuid
wd, _ = os.path.split(os.path.abspath(__file__))
class Captcha:
def __init__(self, width, high, ls=None, lc=4, fs=None,
folder=os.path.join(wd, 'samples'), debug=False):
"""
:param ls: letter set, all
... |
477349 | class Solution:
def canConvert(self, s1: str, s2: str) -> bool:
if s1 == s2: return True
dp = {}
for i, j in zip(s1, s2):
if dp.setdefault(i, j) != j:
return False
return len(set(s2)) < 26 |
477355 | import json
import seaborn as sns
import re
import sys
import os
import os.path
import pandas as pd
import tinydb
from matplotlib import pyplot as plt
import pprint
DEFAULT_STYLE = {
'secondary': 'style'
}
pp = pprint.PrettyPrinter()
class ExperimentPlotter(object):
def __init__(self, base_path, data, confi... |
477423 | import sys
import decouple
try:
from .base import * # noqa
except decouple.UndefinedValueError as exp:
print('ERROR:', exp.message)
sys.exit(1)
|
477429 | import torch
from torch import nn
import math
from typing import Optional
from torch import Tensor
eps=1e-5
################################################################
# DGL's implementation of FeedForwardNet (MLP) for SIGN
class FeedForwardNet(nn.Module):
def __init__(self, in_feats, hidden, out_feats, n_la... |
477473 | from pymclevel.infiniteworld import MCInfdevOldLevel
from pymclevel import mclevel
from timeit import timeit
import templevel
#import logging
#logging.basicConfig(level=logging.INFO)
def natural_relight():
world = mclevel.fromFile("testfiles/AnvilWorld")
t = timeit(lambda: world.generateLights(world.allChunk... |
477491 | import re
from core.msfActionModule import msfActionModule
from core.keystore import KeyStore as kb
from core.utils import Utils
class scan_msf_jboss_vulnscan(msfActionModule):
def __init__(self, config, display, lock):
super(scan_msf_jboss_vulnscan, self).__init__(config, display, lock)
self.tri... |
477500 | import threading
from lemoncheesecake.helpers.threading import ThreadedFactory
def test_threaded_factory():
class TestFactory(ThreadedFactory):
def setup_object(self):
return object()
factory = TestFactory()
objects = []
class TestThread(threading.Thread):
def run(self):... |
477509 | from collections import defaultdict
from data_util.global_var import *
class UnimorphSchema:
# schema in unimorph-schema.tsv automatically extracted from https://unimorph.github.io/doc/unimorph-schema.pdf
# using tabula https://github.com/tabulapdf/tabula
def __init__(self, src=UNIMORPH_SCHEMA_SRC, ignor... |
477511 | import deep_architect.search_logging as sl
import deep_architect.visualization as vi
import deep_architect.utils as ut
from deep_architect.searchers.random import RandomSearcher
import deep_architect.modules as mo
import deep_architect.contrib.misc.search_spaces.tensorflow.dnn as css_dnn
import search_space as ss
de... |
477512 | import math
import bisect
import copy
import os.path as osp
import json
from functools import partial
import numpy as np
from PIL import Image
import cv2
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision.transforms.functional import normalize as tf_norm, to_tensor
from .. import cfg as g... |
477633 | import os
matlab_src_dir = os.path.abspath('.')
extensions = ['sphinx.ext.autodoc', 'sphinxcontrib.matlab']
primary_domain = 'mat'
master_doc = 'contents'
# The suffix of source filenames.
source_suffix = '.rst'
nitpicky = True
|
477659 | import json
import mongodb_consistent_backup
import sys
from datetime import datetime
from argparse import Action
from pkgutil import walk_packages
from yconf import BaseConfiguration
from yconf.util import NestedDict
def parse_config_bool(item):
try:
if isinstance(item, bool):
return item
... |
477662 | from joblib import load as jl_load
from pathlib import Path
from os.path import dirname
def load_model(model_name: str):
pipeline = jl_load(Path(dirname(__file__)) / 'model' / f"{model_name}.joblib")
pipeline.steps[0][1].init()
return pipeline
|
477671 | import dramatiq
from account.models import User
from submission.models import Submission
from judge.dispatcher import JudgeDispatcher
from judge.ide import IDEDispatcher
from utils.shortcuts import DRAMATIQ_WORKER_ARGS
@dramatiq.actor(**DRAMATIQ_WORKER_ARGS())
def judge_task(submission_id, problem_id):
uid = Sub... |
477713 | import random
import os
import shutil
from bench import resources
from audiomate.corpus import io
def run(corpus, base_path):
target_path = os.path.join(base_path, 'out')
shutil.rmtree(target_path, ignore_errors=True)
os.makedirs(target_path)
writer = io.KaldiWriter()
writer.save(corpus, target... |
477717 | from gi.repository import Gtk, GObject, Gio
from core.engine import GameEngine
from gui.controllers.main_window_controller import MainWindowController
from gui.controllers.theme_selection_controller import ThemeSelectionController
from os import path
from gui.controllers import gmenu_controller, about_controller
from g... |
477741 | from django.contrib import admin
from reversion.admin import VersionAdmin
from .models import Municipality, Suministro, Tag
@admin.register(Tag)
class TagAdmin(VersionAdmin):
list_display = ["name", "slug"]
@admin.register(Municipality)
class MunicipalityAdmin(VersionAdmin):
list_display = ["get_name", "sl... |
477792 | import collections
def jewels(J,S):
c=collections.Counter(S)
count =0
for js in J:
count+=c[js]
return count
J='aA'
S='aAAd'
print(jewels(J, S ))
|
477834 | import os
from openl3.cli import run
import tempfile
import numpy as np
import shutil
import pytest
TEST_DIR = os.path.dirname(__file__)
TEST_AUDIO_DIR = os.path.join(TEST_DIR, 'data', 'audio')
TEST_IMAGE_DIR = os.path.join(TEST_DIR, 'data', 'image')
TEST_VIDEO_DIR = os.path.join(TEST_DIR, 'data', 'video')
# Test au... |
477852 | import pytest
import leaguepedia_parser
@pytest.mark.parametrize("team_tuple", [("tsm", "TSM"), ("IG", "Invictus Gaming")])
def test_get_long_team_name(team_tuple):
assert (
leaguepedia_parser.get_long_team_name_from_trigram(team_tuple[0])
== team_tuple[1]
)
@pytest.mark.parametrize(
"te... |
477874 | from __future__ import unicode_literals
from django.db import migrations
from django.utils import translation
from django.utils.translation import gettext_lazy as _
def insert_modules(apps, schema):
from django.conf import settings
translation.activate(settings.LANGUAGE_CODE)
ModuleGroup = apps.get_mode... |
477885 | import random
"""
A helper module for making rolls.
"""
def d20_check_roll(difficulty_class, modifiers=0, advantage=None):
"""
:param difficulty_class: Target for Success
:param modifiers: Total amount of modifiers
:param advantage: If is applicable, True if advantage, False if disadvantage.
:retu... |
477934 | import altair as alt
def rapids_theme():
font = "Open Sans"
text_color = "#666666"
main_palette = ["#7400ff", "#36c9dd", "#d216d2", "#ffb500"]
secondary_palette = ["#bababc", "#666666", "#8824ff", "#9942ff", "#a785e7"]
return {
"config": {
"axis": {
"labelFontS... |
478013 | from .import_ai import *
class TimedPickle:
def __init__(self, data, name, enabled=True):
self.data = data
self.name = name
self.enabled = enabled
def __getstate__(self):
return (time.time(), self.data, self.name, self.enabled)
def __setstate__(self, s):
tstart, se... |
478025 | from __future__ import division
import math
import collections
import six
import tensorflow as tf
from neupy import init
from neupy.utils import as_tuple
from neupy.exceptions import LayerConnectionError
from neupy.core.properties import (
TypedListProperty, Property,
ParameterProperty,
)
from .base import B... |
478027 | from .converters import (
BIGINTEGER, BINARY, BOOLEAN, BOOLEAN_ARRAY, BYTES, Binary, CHAR,
CHAR_ARRAY, DATE, DATETIME, DECIMAL, DECIMAL_ARRAY, Date, DateFromTicks,
FLOAT, FLOAT_ARRAY, INET, INT2VECTOR, INTEGER, INTEGER_ARRAY, INTERVAL,
JSON, JSONB, MACADDR, NAME, NAME_ARRAY, NULLTYPE, NUMBER, OID, PGEnu... |
478041 | from base import pipeline, clean_db
import random
def test_null_groups(pipeline, clean_db):
"""
Verify that null group columns are considered equal
"""
pipeline.create_stream('s', x='int', y='int', z='int')
q = """
SELECT x::integer, y::integer, z::integer, COUNT(*) FROM s
GROUP BY x, y, z;
"""
desc... |
478073 | import os
import numpy as np
import pandas as pd
import torch.utils.data as td
from csl_common.vis import vis
from csl_common.utils import geometry
from datasets import facedataset
class AFLW(facedataset.FaceDataset):
NUM_LANDMARKS = 19
ALL_LANDMARKS = list(range(NUM_LANDMARKS))
LANDMARKS_NO_OUTLINE = AL... |
478161 | import unittest
from nlpmodels.utils.elt import dataset
class TestAbstractDataset(unittest.TestCase):
def test_cannot_instantiate_abstract_class(self):
with self.assertRaises(TypeError):
dataset.AbstractNLPDataset()
|
478205 | import pygame, sys
import numpy as np
from random import randint
ON = 1
OFF = 0
class GameOfLife:
def __init__(self, width=100, height=100):
self.width = width
self.height = height
self.state_new = np.zeros((height, width))
self.state_old = np.zeros((height, width))
def get_wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.