id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
482618 | import re
from netaddr import IPNetwork
try:
from stratosphere.utils import get_google_auth
except ImportError:
# Python2
from utils import get_google_auth
class ResourceValidators(object):
@classmethod
def regex_match(cls, regex, string):
RE = re.compile(regex)
if RE.match(string... |
482619 | import sys
sys.path.append("..")
#import tensorflow as tf
import numpy as np
import time
from Featurize import *
import glob
from multiprocessing import Pool
def GetNodeMask(graph_size, max_size=None):
if max_size == None:
max_size = np.max(graph_size)
return np.array([np.pad(np.ones([s, 1]), ((0, max... |
482629 | import sys
import random
def banner(info=None, banner_len=60, sym="-"):
print()
if not info:
print(sym * banner_len)
else:
info = sym * ((banner_len - len(info)) // 2 - 1) + " " + info
info = info + " " + sym * (banner_len - len(info) - 1)
print(info)
print()
def even... |
482659 | import uuid
import logging
from e2e_tests.aws_lambda.utils import (
send_test_data_to_endpoint,
run_lambda_create_or_update_command,
)
from e2e_tests.cli_operations import delete_deployment
logger = logging.getLogger('bentoml.test')
def test_aws_lambda_update_deployment(basic_bentoservice_v1, basic_bentoser... |
482692 | import numpy as np
import readsnap
import readsubf
import sys
import time
import random
###############################################################################
#this function returns an array containing the positions of the galaxies (kpc/h)
#in the catalogue according to the fiducial density, M1 and alpha
#CDM... |
482699 | from pybacktest.backtest import Backtest
from pybacktest.optimizer import Optimizer
from pybacktest import performance
from pybacktest.data import load_from_yahoo
from pybacktest.ami_funcs import *
from pybacktest.verification import iter_verify, verify
from pybacktest.production import check_position_change
|
482702 | import unittest
from katas.kyu_7.chessboard import chessboard
class ChessboardTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(chessboard('2 2'), '*.\n.*')
def test_equal_2(self):
self.assertEqual(chessboard('5 2'), '*.\n.*\n*.\n.*\n*.')
def test_equal_3(self):
... |
482761 | import Image
import numpy as np
import time
import numbers
class vec3():
def __init__(self, x, y, z):
(self.x, self.y, self.z) = (x, y, z)
def __mul__(self, other):
return vec3(self.x * other, self.y * other, self.z * other)
def __add__(self, other):
return vec3(self.x + other.x, se... |
482763 | import py
import pytest
from xprocess import XProcess
def getrootdir(config):
return config.cache.makedir(".xprocess")
def pytest_addoption(parser):
group = parser.getgroup(
"xprocess", "managing external processes across test-runs [xprocess]"
)
group.addoption("--xkill", action="store_true... |
482772 | import numpy as np
import pandas as pd
import pytest
from anndata import AnnData
from anndata.tests.helpers import assert_equal
def test_uns_color_subset():
# Tests for https://github.com/theislab/anndata/issues/257
obs = pd.DataFrame(
{
"cat1": pd.Categorical(list("aabcd")),
... |
482801 | import threading
import time
# create a mutable object that is shared among threads
class Shared:
val = 1
def func():
y = Shared.val
time.sleep(0.00001)
y += 1
Shared.val = y
threads = []
for i in range(99):
thread = threading.Thread(target=func)
threads.append(thread)
thread.start... |
482805 | from django.test import TestCase
class TestWebpackStatusLoader(TestCase):
def test_loader_output(self):
from .utils import get_clean_bundle
print(get_clean_bundle())
|
482908 | import os
# Try running on CPU
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import numpy as np
import cv2
from keras.models import load_model
R = 2 ** 4
MODEL_NAME = './model1.h5'
model = load_model(MODEL_NAME)
model.summary()
for root, dirs, files in os.walk('./input', topdown=False):
for name in files:
... |
482927 | from django.forms.models import BaseInlineFormSet, inlineformset_factory
from django.utils.translation import ugettext_lazy as _
from publishing.utils.forms import is_empty_form, is_form_persisted
from .models import Publisher, Book, BookImage
# The formset for editing the BookImages that belong to a Book.
BookImage... |
482929 | from youseedee import ucd_data
from .BaseShaper import BaseShaper
import re
from fontFeatures.shaperLib.Buffer import BufferItem
from fontFeatures.shaperLib.VowelConstraints import preprocess_text_vowel_constraints
from .IndicShaperData import script_config, syllabic_category_map, syllable_machine_indic, IndicPositiona... |
482961 | import tensorrt as trt
import torch
from ..torch2trt_dynamic import (get_arg, slice_shape_trt,
tensor_trt_get_shape_trt, tensorrt_converter,
trt_)
@tensorrt_converter('torch.flip')
@tensorrt_converter('torch.Tensor.flip')
def convert_flip(ctx):
in... |
482962 | from sip_parser.sdp_fields import (
FieldRaw,
MediaField,
OriginField,
TimingField,
RepeatTimesField,
TimeDescription,
MediaDescription,
ConnectionDataField,
)
from sip_parser.exceptions import SdpParseError
def parse_version(value):
if value != "0":
raise SdpParseError(
... |
482966 | class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
count = 0
for char in S:
if char in J:
count +=1
return count
if __name__ == '__main__':
J = "aA"
S = "aAAbbbb"
instance = Solution()
solution = instance.numJewelsInStones(J,S)
... |
482997 | def _sum_compose(losses):
loss = sum(v[0] for v in losses)
loss_value = sum(v[1] for v in losses)
loss_dict = {}
[loss_dict.update(v[2]) for v in losses]
return loss, loss_value, loss_dict
class MultiScaleLossComposer:
def __init__(self, compose_fn, single_scale_loss_composers):
self.s... |
483041 | from modeling import *
# def ar_for_ro(ro, N, Cap, k, D, S):
# return ro*N*Cap/k.mean()/D.mean()/S.mean()
def ar_for_ro(ro, N, Cap, k, R, L, S):
return ro*N*Cap/k.mean()/R.mean()/L.mean()/S.mean()
def EW_MMc(ar, EX, c):
ro = ar*EX/c
C = 1/(1 + (1-ro)*G(c+1)/(c*ro)**c * sum([(c*ro)**k/G(k+1) for k in range(c)... |
483045 | import os
import contextlib
import shutil
import gzip
import simplejson as json
import fastavro
from .base import BlobStorage, Blob
class LocalStorage(BlobStorage):
"""Local storage provider that utilizes the local file system.
Args:
root: the root directory, will be created if not exists.
"""
... |
483110 | import pandas as pd
import re
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
import mapping_career_causeways.text_cleaning_utils as text_cleaning_utils
def tfidf_keywords(p, dataframe, text_field, stopwords, N=10):
"""
Fast method to generate keywords characterising each cluster... |
483227 | import json
import os
import time
import requests
from PIL import Image
from StringIO import StringIO
from requests.exceptions import ConnectionError
def go(query, path):
"""Download full size images from Google image search.
Don't print or republish images without permission.
I used this to train a learning al... |
483236 | from collections import namedtuple
import torch as tr
from torch import nn
from torch.nn import functional as F
from configs import Config
from utils.tr_utils import ellipse_params, rotate
class NLinear(nn.Sequential):
def __init__(self, in_feat, units, act=nn.ELU):
layers = [nn.Linear(in_feat, units[0]... |
483253 | import numpy as np
import sklearn.linear_model as skl_linear_model
import sklearn.preprocessing as skl_preprocessing
from Orange.data import Variable, ContinuousVariable
from Orange.preprocess import Normalize
from Orange.preprocess.score import LearnerScorer
from Orange.regression import Learner, Model, SklLearner, ... |
483259 | from django.urls import reverse
from django.views.generic import RedirectView
from django.views.generic import TemplateView
from users.models import TenantUser
from tenant_users.tenants.tasks import provision_tenant
from tenant_users.tenants.utils import create_public_tenant
class TenantView(TemplateView):
temp... |
483285 | from dataclasses import dataclass
from typing import Any, Dict
@dataclass
class ServerConfig:
host: str
port: int
debug: bool
token: str
base_url: str
@dataclass
class PluginConfig:
enabled: bool
args: Dict[str, Any]
@dataclass
class Config:
version: int
server_config: ServerCo... |
483320 | from socket import inet_ntoa
from typing import Any, Iterable, List, Optional, Sequence, Tuple, TypedDict
from eth_enr import ENR
from eth_enr.abc import ENRAPI
from eth_enr.exceptions import OldSequenceNumber
from eth_typing import HexStr, NodeID
from eth_utils import (
ValidationError,
decode_hex,
encode... |
483430 | import pickle
from rdflib import Graph
from pyshacl.monkey import apply_patches
from pyshacl.monkey.memory2 import Memory2
apply_patches()
identifier = "http://datashapes.org/schema"
store = Memory2(identifier=identifier)
with open("./schema.ttl", "rb") as f:
g = Graph(store=store, identifier=identifier).parse(... |
483448 | import uuid, pytest, decimal, math, datetime
from app.extensions import db
from app.api.utils.models_mixins import SoftDeleteMixin, Base
from app.api.mines.mine.models.mine import Mine
from tests.factories import MineFactory
def test_column_existence(db_session):
assert issubclass(Mine, SoftDeleteMixin)
asse... |
483463 | import os
import pymongo
import random
import sys
from uuid import uuid4
from bson.objectid import ObjectId
from pymongo import ASCENDING
import math
from random import choice
from random import randint
from trueskill import trueskill
import numpy.random as rnd
# FIXME: We can't get away with silencing all errors in th... |
483486 | import os
import sys
import numpy as np
import torch
import h5py
from tqdm import tqdm
from torch.utils import data
from torch.utils.data import DataLoader, TensorDataset
import musdb
from yacs.config import CfgNode as CN
import SharedArray as sa
import random
def norm(arr, thres=None, max_=None):
arr -= np.me... |
483503 | import os
import subprocess
import sys
from distutils.version import LooseVersion
from glob import glob
from os.path import join
import numpy as np
import setuptools.command.build_py
import setuptools.command.develop
from setuptools import Extension, find_packages, setup
platform_is_windows = sys.platform == "win32"
... |
483532 | from island_backup import network
from island_backup.island_switcher import island_switcher
import aiohttp
import asyncio
import pytest
NO_NEXT_PAGE = object()
async def get_page(url):
network.session = aiohttp.ClientSession()
island_switcher.detect_by_url(url)
url = island_switcher.sanitize_url(url)
... |
483615 | import torch
import torch.nn as nn
from torch.nn import init
# Defines the PatchGAN discriminator with the specified arguments.
class NLayerDiscriminator(nn.Module):
def __init__(self, n_layers=3, use_sigmoid=False, gpu_ids=[]):
super(NLayerDiscriminator, self).__init__()
self.gpu_ids = gpu_ids
... |
483649 | from django.core.cache import cache, caches, InvalidCacheBackendError
from sorl.thumbnail.kvstores.base import KVStoreBase
from sorl.thumbnail.conf import settings
from sorl.thumbnail.models import KVStore as KVStoreModel
class EMPTY_VALUE:
pass
class KVStore(KVStoreBase):
def __init__(self):
super(... |
483707 | import os, requests
def solve() -> bool:
flag = "magpie{r1ch4rd_l0v35_t0_5w34t}"
challenge_host = "http://web01.magpiectf.ca:9949"
infile = open(os.path.join(os.path.dirname(__file__), "assets/latex-solve.txt"))
latex = infile.read()
r = requests.post(challenge_host + "/ajax.php", data={"cont... |
483722 | import os
import glob
from django.core.management import BaseCommand
from ...bootstrap import process_json_file
class Command(BaseCommand):
def add_arguments(self, parser):
# Positional arguments
parser.add_argument('data_file', nargs='+', type=str)
def handle(self, *args, **options):
... |
483724 | from hwt.interfaces.agents.handshaked import HandshakedAgent
from hwt.interfaces.std import VectSignal, HandshakeSync, Signal
from hwt.synthesizer.param import Param
from hwtSimApi.hdlSimulator import HdlSimulator
class AddrDataHs(HandshakeSync):
"""
Simple handshaked interface with address and data signal
... |
483770 | from typing import Tuple
import thop
import torch
import torch.nn as nn
import yacs.config
def count_op(config: yacs.config.CfgNode, model: nn.Module) -> Tuple[str, str]:
data = torch.zeros((1, config.dataset.n_channels,
config.dataset.image_size, config.dataset.image_size),
... |
483824 | import scipy as sp
from enum import Enum
from sklearn.metrics import pairwise_distances
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array, check_is_fitted, check_random_state
class HiddenLayerType(Enum):
RANDOM = 1 # Gaussian random projection
SPARSE ... |
483880 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
triggerFlagPSet = cms.PSet(
dcsInputTag = cms.InputTag('scalersRawToDigi'),
dcsPartitions = cms.vint32( 24, 25, 26, 27, 28, 29 ),
andOrDcs = cms.bool(False),
errorReplyDcs = cms.bool(True),
dbLabel = cms.string... |
483901 | from django.core.exceptions import ValidationError
from gcoin import is_address, b58check_to_hex
def validate_address(value):
if not is_address(value):
raise ValidationError(
"%(value)s is not a valid address",
params={'value': value},
)
try:
b58check_to_hex(v... |
483905 | import numpy as np
import numpy.random as npr
from sds.initial import SingleBayesianInitGaussianLatent
from sds.latents import SingleBayesianAutoRegressiveGaussianLatent
from sds.emissions import SingleBayesianLinearGaussianEmission
from sds.utils.decorate import ensure_args_are_viable
from sds.utils.general import S... |
483908 | from mirage.libs import ir,utils,io
from mirage.core import module
class ir_inject(module.WirelessModule):
def init(self):
self.technology = "ir"
self.type = "action"
self.description = "Injection module for IR signals"
self.args = {
"INTERFACE":"irma0",
"DATA":"",
"PROTOCOL":"",
"CODE":"",
... |
483925 | from django.urls import path, re_path
from .views import empty_view
urlpatterns = [
# No kwargs
path("conflict/cannot-go-here/", empty_view, name="name-conflict"),
path("conflict/", empty_view, name="name-conflict"),
# One kwarg
re_path(r"^conflict-first/(?P<first>\w+)/$", empty_view, name="name-c... |
483941 | from __future__ import annotations
from dataclasses import dataclass
from typing import Generic, Tuple, TypeVar, final
from pydantic import parse_obj_as
from expression import SingleCaseUnion, Tag, TaggedUnion, match, tag
_T = TypeVar("_T")
@dataclass
class Rectangle:
width: float
length: float
@datacla... |
483962 | from typing import List, Dict, Any, Optional
from abc import ABC
from objectiv_backend.schema.schema_utils import SchemaEntity
class AbstractContext(SchemaEntity, ABC):
"""
AbstractContext defines the bare minimum properties for every Context. All Contexts inherit from it.
Attributes:
id ... |
483978 | class setu:
def __init__(
self,
url='',
type=2,
info={},
pic_file=''
):
self.url=url
self.type=type
self.info=info
self.pic_file=pic_file |
484003 | import asyncio
from unittest import mock
def run(loop, coro_or_future):
return loop.run_until_complete(coro_or_future)
def run_until_complete(f):
def wrap(*args, **kwargs):
return run(asyncio.get_event_loop(), f(*args, **kwargs))
return wrap
def make_coro_mock():
coro = mock.Mock(name="Cor... |
484013 | name, age = "Sreelakshmi", 19
username = "Sreelakshmi-M.py"
print ('Hello!')
print("Name: {}\nAge: {}\nUsername: {}".format(name, age, username))
|
484124 | from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from enumfields import EnumField
from ..auth import is_authenticated_user, is_general_admin
from ..enums import UnitGroupAuthorizationLevel
from .base import ModifiableModel
from .unit import Unit
cl... |
484131 | import ipaddress
import itertools
import pynetbox
from config import NETBOX_URL, NETBOX_TOKEN
# Instantiate pynetbox.api class with URL of your NETBOX and your API TOKEN
nb = pynetbox.api(url=NETBOX_URL, token=NETBOX_TOKEN)
# Prepare tags we want to combine
mc_side = ["a_side", "b_side"]
mc_exchange = ["nasdaq", "n... |
484135 | nums = [1, 2, 3, 4, 5]
# iter, next 를 직접 호출해서
# 잘 동작하는지 실행해봅시다.
it = iter(nums)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
# 여기서 중단됨
print(next(it))
|
484226 | import os
import sys
import logging
import importlib
from collections import OrderedDict
from pathlib import Path
from functools import reduce
from common import utilities
from common.exceptions import ModuleLoadException
from common.module.module import Module
from .dependency_graph import DependencyGraph
from .modul... |
484240 | from __future__ import absolute_import, unicode_literals
import pytest
from case import skip
from kombu.utils.functional import lazy
from celery.five import nextfun, range
from celery.utils.functional import (DummyContext, first, firstmethod,
fun_accepts_kwargs, fun_takes_argument... |
484246 | from contextlib import contextmanager
import functools
import logging
import numpy as np
import pytest
import torch
from pymde import util
def assert_allclose(x, y, up_to_sign=False, rtol=1e-4, atol=1e-5):
if isinstance(x, torch.Tensor):
x = x.detach().cpu().numpy()
if isinstance(y, torch.Tensor):
... |
484265 | import os, sys, pytest, copy
from numpy import isclose
# import repo's tests utilities
cur_dir = os.path.dirname(__file__)
path = os.path.abspath(os.path.join(cur_dir, '..', 'tests'))
if not path in sys.path:
sys.path.insert(1, path)
del path
import test_util
# Set arguments used in all forest tests:
# Define all... |
484271 | from ..src.sim import FEM
import numpy as np
class simulate_fenics_rve(FEM):
"""
SIMULATION-Module wrap for FEniCS
"""
def __init__(self, in_data, model,**kwargs):
""" Initialize """
self.__name__ = 'FEniCS-RVE' # Name module
super().__init__(in_data=... |
484276 | import sys
from qam import Qam
from matplotlib import pyplot as plt
if len(sys.argv) != 2:
print "Usage: %s <data-bits>" % sys.argv[0]
exit(1)
modulation = {
'0' : (1,0),
'1' : (1,180),
}
q = Qam(baud_rate = 10,
bits_per_baud = 1,
carrier_freq = 50,
modulation = modulation)
s =... |
484289 | from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework import status
from rest_framework.permissions import AllowAny, IsAuthenticated
from app_test.serializers import LoginSerializer, TodoSerializer
from app_test.models... |
484312 | from buffpy.models.profile import PATHS, Profile
class Profiles(list):
"""
Manage profiles
+ all -> get all the profiles from buffer
+ filter -> wrapper for list filtering
"""
def __init__(self, api, *args, **kwargs):
super().__init__(*args, **kwargs)
... |
484336 | import torch.nn as nn
from models.backbone.alexnet import AlexNetBackbone
from models.backbone.linear import LinearBackbone
from models.backbone.resnet import ResNetBackbone
from models.backbone.swinvit import SwinTransformerBackbone
from models.backbone.vgg import VGGBackbone
from models.backbone.vit import ViTBackbo... |
484357 | from liblo import *
import sys
import time
class MyServer(ServerThread):
osc_msgs_recv = 0
def __init__(self):
ServerThread.__init__(self, 4000)
@make_method('/foo', 'ifs')
def foo_callback(self, path, args):
i, f, s = args
self.osc_msgs_recv += 1
#print "received m... |
484397 | from .frame_skip import frame_skip_v0 # NOQA
from .basic_wrappers import color_reduction_v0, resize_v0, dtype_v0, \
flatten_v0, reshape_v0, normalize_obs_v0, clip_actions_v0, clip_reward_v0, \
scale_actions_v0 # NOQA
from .nan_wrappers import nan_random_v0, nan_noop_v0, nan_zeros_v0 # NOQA
from .delay_observat... |
484401 | t = int(input())
for _ in range(t):
n,k,d = map(int, input().split())
# Taking n integers and storing it in list
arr = list(map(int, input().split()))
# Finding sum of all elements inside array
total = sum(arr)
# Floor division would give the answer but
# see to it that doesn't excede d, ... |
484403 | from datetime import date
from controls.models import FinancialYear, ModuleSettings, Period
from dateutil.relativedelta import relativedelta
from django.contrib.auth import get_user_model
from django.shortcuts import reverse
from django.test import TestCase
from nominals.models import Nominal, NominalTransaction
cla... |
484428 | import logging
from logging.handlers import WatchedFileHandler
from config import config
LOG_FORMAT = '%(asctime)s %(levelname)7s %(name)s [%(threadName)s] : %(message)s'
def logging_config():
level = logging.ERROR
if config.get('log', 'level') == 'DEBUG':
level = logging.DEBUG
elif config.get('... |
484435 | import abc
from dataclasses import dataclass
import math
import torch
from .basedist import ExponentialFamily
from .basedist import ConjugateLikelihood
__all__ = ['GammaLikelihood', 'Gamma', 'GammaStdParams']
EPS = 1e-6
@dataclass
class GammaLikelihood(ConjugateLikelihood):
dim: int
def sufficient_statisti... |
484447 | class Singleton:
_instance = None
def __init__(self):
# Singleton pattern must prevent normal instantiation
raise Exception("Cannot directly instantiate a Singleton. Access via get_instance()")
@classmethod
def get_instance(cls):
# This is the only way to access the one and onl... |
484484 | import numpy as np
def multi_to_one_dim(in_shape, in_index):
""" Convert an index from a multi-dimension into the corresponding index in flat array """
out_index = 0
for dim, index in zip(in_shape, in_index):
out_index = dim * out_index + index
return out_index
def one_to_multi_dim(out_shap... |
484492 | import numpy as np
import gnumpy as gp
import pickle
# gp.board_id_to_use = 1
class SGD:
def __init__(self,model,alpha=1e-2,minibatch=256,
optimizer='momentum',momentum=0.9):
self.model = model
assert self.model is not None, "Must define a function to optimize"
self.it = 0
... |
484502 | import click
import yaml
from ckan_cloud_operator import logs
from . import manager
@click.group()
def proxy():
"""Manage SOLR proxy for centralized unauthenticated access"""
pass
@proxy.command()
def initialize():
manager.deploy()
logs.exit_great_success()
|
484576 | from CSS3.completions import types as t
font_feature_types = [
("@annotation", "@annotation {\n\t${1}\n}"),
("@character-variant", "@character-variant {\n\t${1}\n}"),
("@ornaments", "@ornaments {\n\t${1}\n}"),
("@styleset", "@styleset {\n\t${1}\n}"),
("@stylistic", "@stylistic {\n\t${1}\n}"),
(... |
484581 | from django.conf.urls import url
from ocfweb.login.calnet import login as calnet_login
from ocfweb.login.calnet import logout as calnet_logout
from ocfweb.login.ocf import login
from ocfweb.login.ocf import logout
urlpatterns = [
url(r'^login/$', login, name='login'),
url(r'^logout/$', logout, name='logout')... |
484587 | import os
import tempfile
from resotolib.x509 import (
gen_rsa_key,
gen_csr,
bootstrap_ca,
sign_csr,
write_csr_to_file,
write_cert_to_file,
write_key_to_file,
load_csr_from_file,
load_cert_from_file,
load_key_from_file,
key_to_bytes,
cert_fingerprint,
)
def test_x509():... |
484642 | import torch
import torch.nn as nn
import torch.distributions as dist
from torch.distributions.kl import kl_divergence
from .gp_utils import vec2tril, mat2trilvec, cholesky, rev_cholesky, gp_cond, linear_joint, linear_marginal_diag
from .kernels import RBFKernel, DeepRBFKernel
from .likelihoods import MulticlassSoftma... |
484659 | import numpy as np
import colorsys
import matplotlib.colors as mc
def rgb2hex(r, g, b):
"""RGB to hexadecimal."""
return "#%02x%02x%02x" % (r, g, b)
# Ersilia colors
eos = {
"dark": "#50285a",
"gray": "#d2d2d0",
"green": "#bee6b4",
"white": "#ffffff",
"purple": "#aa96fa",
"pink": "#d... |
484670 | import logging
from .main import ItemProvider
from .views import Handler
logging.info('docker.__init__.py: docker loaded')
|
484685 | import tensorflow as tf
from tensorflow.python.ops import rnn_cell
from experiment.qa.model import QAModel
from experiment.qa.model.helper.pooling_helper import non_zero_tokens, maxpool
class BiLSTMModel(QAModel):
"""An LSTM model with 1-max pooling to learn the representation"""
def __init__(self, config, c... |
484689 | import pkgutil
import os
import importlib
# make sure all modules relying on MasterDataEntity are imported before the tests are run
# otherwise the utils tests for AssetcentralEntitySet relying on __subclasses__ will not include all subclasses,
# and will depend on execution order of tests
path = os.path.join(os.path.... |
484771 | import numpy as np
import neurolab as nl
# Input file
input_file = 'letter.data'
# Number of datapoints to load from the input file
num_datapoints = 20
# Distinct characters
orig_labels = 'omandig'
# Number of distinct characters
num_output = len(orig_labels)
# Training and testing parameters
num_train = int(0.9 *... |
484776 | import asyncio
from datetime import datetime
import aiohttp
from bs4 import BeautifulSoup
async def get_url(session, url):
headers = {
"accept-language": "en-US;q=0.8,en;q=0.7",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.9... |
484813 | import abc
from dataclasses import dataclass
from typing import Optional
from yarl import URL
from .parsing_utils import LocalImage, RemoteImage
# storage
@dataclass(frozen=True)
class StorageProgressStart:
src: URL
dst: URL
size: int
@dataclass(frozen=True)
class StorageProgressComplete:
src: UR... |
484880 | class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
这题要解决的问题是,必须有个地方记录判断结果,但又不能影响下一步的判断条件;
直接改为 0 的话,会影响下一步的判断条件;
因此,有一种思路是先改为 None,最后再将 None 改为 0;
从条件上看,如果可以将第一行、第二行作为记录空间,那么,用 None 应该也不算违背题目条件;
"""
rows = len(matrix)
cols = len(... |
484923 | from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
import unittest
import aaf2
import common
class TestCreateSequence(unittest.TestCase):
def test_create_sequence(self):
result_file = common.get_test_file('create_sequence.aaf')
mob_count = ... |
484943 | from collections import defaultdict
from queue import PriorityQueue
class Offer:
def __init__(self, item, quant, itemPrice, coffer=0):
self.item = item
self.quantLeft = quant
self.quantFulfilled = 0
self.itemPrice = itemPrice
self.coffer = coffer
@property
def complete(self):
... |
484952 | import sys
if sys.version_info.major == 2:
from future.standard_library import install_aliases
install_aliases()
import functools
from backports.functools_lru_cache import lru_cache
functools.lru_cache = lru_cache
from contentbase.resources import * # noqa
def includeme(config):
config.incl... |
484999 | import traceback
from util import callsback
import common.actions
action = common.actions.action
ObservableActionMeta = common.actions.ObservableActionMeta
from common import profile
from logging import getLogger; log = getLogger('Contact')
objget = object.__getattribute__
CONTACT_ATTRS = set(['id', 'budd... |
485011 | from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
import math, sys
def periodic (i, limit, add):
"""
Choose correct matrix index with periodic
boundary conditions
Input:
- i: Base index
- limit: Highest \"legal\" index
- add: Number to add or subtract... |
485034 | from Redy.Magic.Classic import singleton
from typing import Union
lit = Union[str, bytes]
@singleton
class ConstStrPool:
__slots__ = []
_pool: dict = {}
@classmethod
def cast_to_const(cls, string: lit):
if string not in cls._pool:
cls._pool[string] = string
return cls._poo... |
485056 | from django.test import TestCase
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
from attendance.models.Student import Student
from attendance.serializers.StudentSerializer import StudentSerializer
class StudentSerializerTest(TestCase):
def setUp(self):
facto... |
485083 | from pdb import set_trace as T
from forge.blade.action import action
from forge.blade.lib import utils, enums
import numpy as np
class Arg:
def __init__(self, val, discrete=True, set=False, min=-1, max=1):
self.val = val
self.discrete = discrete
self.continuous = not discrete
self.min = min
... |
485092 | import pandas as pd
import requests
import json
import base64
import logging
import os.path
from manubot import cite
headers = {} # For Development you can insert your GH api token here and up the rate limit {'Authorization': 'token %s' % "<apiToken>"}
if "GITHUB_TOKEN" in os.environ:
print("GITHUB_TOKEN env var... |
485093 | import os
import re
import threading
import sublime
from .preferences_filename import preferences_filename
from .thread_progress import ThreadProgress
from .package_manager import PackageManager
from .upgraders.git_upgrader import GitUpgrader
from .upgraders.hg_upgrader import HgUpgrader
from .versions import version... |
485094 | import unittest
from decorator import *
class DecoratorTest(unittest.TestCase):
def test_pagina_exitoso(self):
pagina_1 = PaginaWeb(
url = "https://instaprint.es/",
ruta = "/epages/",
formato = "HTML",
contenido = '<a href= "https://instaprint.es/epage... |
485127 | import binascii
import logging
import io
import struct
from pycoin.block import Block, BlockHeader
from pycoin.encoding import double_sha256
from pycoin.serialize import b2h_rev, bitcoin_streamer
from pycoin.tx.Tx import Tx
from pycoinnet.InvItem import InvItem
from pycoinnet.PeerAddress import PeerAddress
# definit... |
485150 | from collections import defaultdict
import json
import re
import sys
from bs4 import BeautifulSoup
import dateparser
from etaprogress.progress import ProgressBar
import requests
###################
# SCRAP FILM LIST #
###################
def parse_list_page(page_url):
r = requests.get(page_url)
soup = Beauti... |
485168 | VERSION = (0, 5, 3)
default_app_config = 'django_url_framework.apps.URLFrameworkAppConfig'
# Dynamically calculate the version based on VERSION tuple
if len(VERSION)>2 and VERSION[2] is not None:
str_version = "%d.%d.%s" % VERSION[:3]
else:
str_version = "%d.%d" % VERSION[:2]
__version__ = str_version
def r... |
485191 | from cleo.helpers import argument
from cleo.helpers import option
from poetry.app.relaxed_poetry import rp
from ..command import Command
class SelfUpdateCommand(Command):
name = "self update"
description = "Updates Relaxed-Poetry to the latest version."
arguments = [argument("version", "The version to u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.