id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1614524 | import numpy as np
import pandas as pd
import pytest
import tabmat as tm
@pytest.fixture()
def X():
df = pd.read_pickle("tests/real_matrix.pkl")
X_split = tm.from_pandas(df, np.float64)
wts = np.ones(df.shape[0]) / df.shape[0]
X_std = X_split.standardize(wts, True, True)[0]
return X_std
def tes... |
1614545 | class Attr:
COURSES = "courses"
DEPT = "dept"
INSTRUCTORS = "instructors"
NAME = "name"
NUMBER = "number"
PATH = "path"
PAGES = "pages"
COURSE_SURVEY_TRANSPARENCY_PAGE_PATHS = [
"course_surveys_authentication",
"course_surveys_infrastructure",
"course_surveys_upload",
"cour... |
1614557 | import inspect
import re
from hashlib import sha256
from typing import List
from .csv import csv
from .json import json
from .pandas import pandas
from .parquet import parquet
from .text import text
def hash_python_lines(lines: List[str]) -> str:
filtered_lines = []
for line in lines:
line = re.sub(r... |
1614559 | from itertools import count
import logging
import os
def iter_files(compilation_unit):
'''Yield all file paths in the given compilation unit.
Yield absolute paths if possible. Paths are not guaranteed to be unique.'''
topdie = compilation_unit.get_top_DIE()
def iter_files_raw():
# Yiel... |
1614560 | from .sink import AvroSink
from .source import AvroSource
from .serializer import AvroSerializer
from .deserializer import AvroDeserializer
__all__ = (
'AvroSink',
'AvroSource',
'AvroSerializer',
'AvroDeserializer',
)
|
1614583 | import numpy as np
import scipy.linalg as spla
import __builtin__
try:
profile = __builtin__.profile
except AttributeError:
# No line profiler, provide a pass-through version
def profile(func): return func
def chol2inv(chol):
return spla.cho_solve((chol, False), np.eye(chol.shape[0]))
def matrixIn... |
1614603 | from tests.utils import logging
from airflow_kubernetes_job_operator.kube_api import KubeResourceKind
from airflow_kubernetes_job_operator.kube_api import KubeApiRestClient
from airflow_kubernetes_job_operator.kube_api import GetPodLogs
from airflow_kubernetes_job_operator.kube_api import kube_logger
KubeResourceKind.... |
1614635 | from objective_functions.recon import elbo_loss, sigmloss1dcentercrop
from unimodals.MVAE import LeNetEncoder, DeLeNet
from training_structures.MVAE_mixed import train_MVAE, test_MVAE
from datasets.avmnist.get_data import get_dataloader
import torch
from torch import nn
from unimodals.common_models import MLP
from fusi... |
1614658 | from .gradient_descent_2d import GradientDescent2D
class Momentum2D(GradientDescent2D):
def __init__(self, alpha=3e-2, max_iterations=150, start_point=1.0,
epsilon=1e-3, momentum=0.3, random=False):
self.momentum = momentum
super().__init__(alpha=alpha, max_iterations=max_itera... |
1614665 | import sys
if sys.version_info >= (3, 0):
from .diff_match_patch import __author__, __doc__, diff_match_patch, patch_obj
else:
from .diff_match_patch_py2 import __author__, __doc__, diff_match_patch, patch_obj
__version__ = "20200713"
__packager__ = "<NAME> (<EMAIL>)"
|
1614671 | import argparse
import os
from functools import partial
from multiprocessing.pool import Pool
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
from tqdm import tqdm
import cv2
cv2.ocl.setUseOpenCL(False)
cv2.setNumThreads(0)
from preprocessing.utils ... |
1614672 | from __future__ import annotations
from typing import Dict, List, Optional, Tuple, Union
import warp.yul.ast as ast
from warp.yul.AstMapper import AstMapper
Scope = Dict[str, Optional[ast.Literal]]
class VariableInliner(AstMapper):
"""This class inlines the value of variables by tracking their values
acros... |
1614715 | import pytest
from spacy.cli.project.run import project_run
from spacy.cli.project.assets import project_assets
from pathlib import Path
@pytest.mark.skip(reason="Import currently fails")
def test_fastapi_project():
root = Path(__file__).parent
project_assets(root)
project_run(root, "install", capture=Tru... |
1614719 | import numpy as np
import pandas as pd
class CellDischargeData:
"""
Battery cell data from discharge test.
"""
def __init__(self, path):
"""
Initialize with path to discharge data file.
Parameters
----------
path : str
Path to discharge data file.
... |
1614749 | import unittest
import pubsub
class TestPubSub(unittest.TestCase):
def test_subscribe(self):
sub = pubsub.subscribe('test')
pubsub.publish('test', 'hello world')
self.assertEqual(next(sub.listen())['data'], 'hello world')
def test_unsubscribe(self):
sub = pubsub.subscribe('tes... |
1614766 | import densecap.util
def test_IoU_overlap():
box0 = (0, 0, 100, 100)
box1 = (50, 50, 100, 100)
box2 = (0, 50, 100, 100)
box3 = (50, 0, 100, 100)
assert densecap.util.iou(box0, box1) == 50 ** 2 / (2 * 100 ** 2 - 50 ** 2)
assert densecap.util.iou(box0, box2) == (50 * 100) / (2 * 100 ** 2 - 50 *... |
1614787 | import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_m... |
1614799 | import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import i2c, sensor
from esphome.const import (
CONF_ID,
CONF_TEMPERATURE,
DEVICE_CLASS_TEMPERATURE,
ICON_BRIEFCASE_DOWNLOAD,
STATE_CLASS_MEASUREMENT,
UNIT_METER_PER_SECOND_SQUARED,
ICON_SCREEN_ROTATIO... |
1614804 | from .organizations import ActionBatchOrganizations
from .networks import ActionBatchNetworks
from .devices import ActionBatchDevices
from .appliance import ActionBatchAppliance
from .camera import ActionBatchCamera
from .cellularGateway import ActionBatchCellularGateway
from .insight import ActionBatchInsight
f... |
1614813 | from retrieval.elastic_reranking_retriever import ElasticRerankingRetriever
import click
@click.command()
@click.option('--delete/--no-delete', type=bool, help='')
@click.option('--load/--no-load', type=bool, help='')
@click.option('--search', default='', type=str, help='')
def run(delete, load, search):
ret = El... |
1614827 | from conans import ConanFile, CMake, tools
import os
class OverpeekEngineConan(ConanFile):
name = "overpeek-engine"
version = "0.1"
license = "MIT"
author = "<NAME>"
url = "https://github.com/Overpeek/overpeek-engine"
description = "A minimal 2D game engine/library."
topics = ("game-engine... |
1614891 | from solver import *
from armatures import *
from models import *
import numpy as np
import config
np.random.seed(20160923)
pose_glb = np.zeros([1, 3]) # global rotation
########################## mano settings #########################
n_pose = 12 # number of pose pca coefficients, in mano the maximum is 45
n_shap... |
1614927 | import unittest
from tda.orders.common import *
from tda.orders.equities import *
from .utils import has_diff, no_duplicates
import imp
from unittest.mock import patch
class EquityOrderBuilderLegacy(unittest.TestCase):
def test_import_EquityOrderBuilder(self):
import sys
assert sys.version_info... |
1614934 | import re
import logging
from python_terraform import Terraform, IsFlagged
from terrestrial.errors import TerrestrialFatalError
from .tfconfig import TerraformConfig
KWARGS_MAPPING = {
'plan': {
'input': False
},
'apply': {
'input': False,
'auto_approve': True
},
'destroy... |
1614984 | import os
from os import listdir
from os.path import isfile, join
import logging
import numpy as np
from ase import Atoms
import mff
from mff import models, calculators, utility
from mff import configurations as cfg
def get_potential(confs):
pot = 0
for conf in confs:
el1 = conf[:, 3]
el2 = co... |
1614985 | from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import inspect
import re
import numpy as np
import os
import collections
import pickle
# Converts a Tensor into a Numpy array
# |imtype|: the desired type of the converted numpy array
def tensor2im(image_tensor, imtype=np.uint... |
1615045 | import random
import string
import json
import requests
from . import logger
from ..engine.decorators import Plugin
from ..engine.download import DownloadBase
@Plugin.download(regexp=r'(?:https?://)?(?:(?:www|m|live)\.)?acfun\.cn')
class Acfun(DownloadBase):
def __init__(self, fname, url, suffix='flv')... |
1615073 | import timeit, functools
def dist_test():
pp_sketchlib.queryDatabase("listeria", "listeria", names, names, kmers, 1)
setup = """
import sys
sys.path.insert(0, "build/lib.macosx-10.9-x86_64-3.7")
import pp_sketchlib
"""
#import numpy as np
#
#from __main__ import dist_test
#
#kmers = np.arange(15, 30, 3)
#
#name... |
1615079 | def test(name, input0, input1, input2, output0, input0_data, input1_data, input2_data, output_data):
model = Model().Operation("SELECT_V2_EX", input0, input1, input2).To(output0)
example = Example({
input0: input0_data,
input1: input1_data,
input2: input2_data,
output0: output_data,
}, mod... |
1615090 | import sys, re, os
file = sys.argv[1]
ver = sys.argv[2]
pattern = re.compile("(SikuliVersion = )\".*\"(;)")
#print file, ver
f = open(file, 'r')
output = open(file+".tmp", 'w')
for line in f.xreadlines():
output.write(pattern.sub(r'\1"'+ver+r'"\2', line))
output.close()
f.close()
os.remove(file)
os.rename(file+".... |
1615113 | import numpy as np
import matplotlib.pyplot as plt
img = plt.imread('../data/elephant.png')
print img.shape, img.dtype
# (200, 300, 3) dtype('float32')
plt.imshow(img)
plt.savefig('plot.png')
plt.show()
plt.imsave('red_elephant', img[:,:,0], cmap=plt.cm.gray)
# This saved only one channel (of RGB)
plt.imshow(plt.... |
1615137 | import argparse
import codecs
import csv
import datetime
import errno
import importlib
import json
import logging
import os
import shutil
import subprocess
import sys
import traceback
from functools import singledispatch
from pathlib import Path
from typing import (
Any,
Iterable,
List,
Tuple,
Union... |
1615143 | from .. import config
from .. import serializers
from ..repositories.common import CreateResource, ListResources, DeleteResource, GetResource
from ..sdk_exceptions import ResourceFetchingError
class GetBaseProjectsApiUrlMixin(object):
def _get_api_url(self, **_):
return config.config.CONFIG_HOST
class C... |
1615195 | import numpy
from numpy.testing import assert_raises, assert_equal, assert_allclose
from fuel.datasets import Iris
from tests import skip_if_not_available
def test_iris_all():
skip_if_not_available(datasets=['iris.hdf5'])
dataset = Iris(('all',), load_in_memory=False)
handle = dataset.open()
data, ... |
1615209 | from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
import re
register = template.Library()
rx = re.compile(r'(%(\([^\s\)]*\))?[sd])')
def format_message(message):
return mark_safe(rx.sub('<code>\\1</code>', escape(message).replace(r'\n','<br />\n')))
for... |
1615254 | from boa3.builtin import public
@public
def Main(*a: int) -> int:
c, *b = a # not implemented, won't compile
return c
|
1615282 | import os
# toolchains options
ARCH ='risc-v'
CPU ='e906'
CPUNAME ='e906f'
VENDOR ='t-head'
CROSS_TOOL ='gcc'
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
if CROSS_TOOL == 'gcc':
PLATFORM = 'gcc'
EXEC_PATH = r'/home/xinge/tools/riscv64-elf-x86_64-20200616-1.9.6/... |
1615286 | import pyspark
from pyspark.sql import SparkSession
from pyspark.ml.feature import OneHotEncoder, StringIndexer, IndexToString, VectorAssembler
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.ml import Pipeline, Model
from pyspark.ml.classification import RandomForestClassifier
import json
... |
1615320 | import cv2
import torch
import scipy.special
import numpy as np
import torchvision
import torchvision.transforms as transforms
from PIL import Image
from enum import Enum
from scipy.spatial.distance import cdist
from ultrafastLaneDetector.model import parsingNet
lane_colors = [(0,0,255),(0,255,0),(255,0,0),(0,255,255... |
1615323 | from tests.hypergol_test_case import DataClass1
from tests.hypergol_test_case import HypergolTestCase
class TestDatasetDefFile(HypergolTestCase):
def __init__(self, methodName='runTest'):
super(TestDatasetDefFile, self).__init__(
location='test_dataset_def_file_location',
projectN... |
1615325 | from unittest import TestCase
from app.fila import Fila
class TestFila(TestCase):
@classmethod
def setUpClass(cls):
cls.arquivo = 'arquivo.txt'
print('setUpClass')
@classmethod
def tearDownClass(cls):
print('tearDownClass')
from os import remove
remove(cls.arqu... |
1615353 | import numpy as np
import numba as nb
_signatures = [
(nb.float32[:], nb.float32[:], nb.float32[:]),
(nb.float64[:], nb.float64[:], nb.float64[:]),
]
@nb.njit(_signatures, cache=True)
def _de_castlejau(z, beta, res):
# De Casteljau algorithm, numerically stable
n = len(beta)
if n == 0:
r... |
1615368 | from xendit.models._base_model import BaseModel
from xendit._api_requestor import _APIRequestor
from xendit._extract_params import _extract_params
from xendit.xendit_error import XenditError
class RecurringPayment(BaseModel):
"""RecurringPayment class (API Reference: RecurringPayment)
Static Methods:
... |
1615372 | from nose import tools as nt
from tests.base import AdminTestCase
from tests.test_conferences import ConferenceFactory
from admin.meetings.serializers import serialize_meeting
class TestsSerializeMeeting(AdminTestCase):
def setUp(self):
super(TestsSerializeMeeting, self).setUp()
self.conf = Conf... |
1615392 | from girder import plugin
from .views import RabbitUserQueue
class GirderPlugin(plugin.GirderPlugin):
def load(self, info):
info["apiRoot"].rabbit_user_queues = RabbitUserQueue()
|
1615425 | import os
import sys
import glob
import html
import fnmatch
from os import path
import coverage
OUTPUT_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Spec Coverage</title>
<link rel="stylesheet" href="style.css" type="text/css">
... |
1615446 | UNKNOWN = "Unknown"
MANUAL = "Manual"
TESTDRAFT = "TestDraft"
SCHEDULED = "Scheduled"
WEBHOOK = "Webhook"
INTERNAL = "Internal"
WATCHER = "Watcher"
UNKNOWN_ENUM_INDEX = 0
MANUAL_ENUM_INDEX = 1
TESTDRAFT_ENUM_INDEX = 2
SCHEDULED_ENUM_INDEX = 3
WEBHOOK_ENUM_INDEX = 4
INTERNAL_ENUM_INDEX = 5
WATCHER_ENUM_INDEX = 6
mappin... |
1615486 | import os
import sys
import argparse
import tensorflow as tf
from misc.helpers import *
from misc.digits import Digits
###################################################################
# Model #
################################################################... |
1615491 | import torch
import torch.nn as nn
from torch.cuda.amp import GradScaler, autocast
from torchattacks.attack import Attack
class FastBIM(Attack):
def __init__(self, model, eps=4/255, alpha=1/255, steps=0):
super().__init__("FastBIM", model)
self.eps = eps
self.alpha = alpha
... |
1615535 | import logging
import multiprocessing as mp
from argparse import Namespace
from typing import Optional, List
from arango import ArangoClient
from cklib.args import ArgumentParser
from cklib.jwt import add_args as jwt_add_args
from core import async_extensions
from core.db.arangodb_extensions import ArangoHTTPClient
f... |
1615557 | from bip import *
import idc
import pytest
"""
Test for all classes used for representing ast nodes are tested by this
file, this is also used for testing the visitors.
Are tested in this file the following:
* :class:`AbstractCItem` from ``bip/hexrays/astnode.py``
* :class:`CNode`, :class:`CNod... |
1615564 | import os
from pathlib import Path
import shutil
from ament_index_python.packages import get_package_share_directory, get_package_prefix
import launch
import launch_ros.actions
def generate_launch_description():
if not "tesseract_collision" in os.environ["AMENT_PREFIX_PATH"]:
# workaround for pluginlib C... |
1615568 | import math
from time import time as now
from collections import deque
#from sorted_value_dict import SortedValueDict
SortedValueDict=dict #temp debug
from processors.properties.property import Property
class BlockchainState(Property):
def __init__(self):
super().__init__()
self.requires = ['trace']#, 'tx', '... |
1615597 | from adobe_analytics import Client, ReportDefinition
client = Client.from_json("my_credentials.json")
suites = client.suites()
suite = suites["my_report_suite_id"]
# for classifications a simple string for the dimension_id isn't sufficient anymore
# you need to specify the id and the classification name in a dictiona... |
1615600 | def merge(output_dir, scan_name, threshold, motion_f, power_f, flag):
"""
Method to merge power parameters and motion
parameters file
"""
import os
import re
if threshold == None:
filename = scan_name + "_all_params.csv"
filename = filename.lstrip("_")
outfile = os.p... |
1615622 | import argparse
class Config():
def __init__(self):
pass
def parse(self):
parser = argparse.ArgumentParser(description='GAN generation')
###parsing
parser.add_argument('--input_nc_G_parsing', type=int, default=36, help='# of input image channels: 3 for RGB and 1 for g... |
1615624 | import os
import torch
from torchvision.datasets import CelebA, CIFAR10, LSUN, ImageFolder
from torch.utils.data import Dataset, DataLoader, random_split, Subset
from utils import CropTransform
import torchvision.transforms as transforms
import numpy as np
from tqdm import tqdm
import cv2
from PIL import Image
# Chang... |
1615636 | import logging.config
from kombu import Queue
from celery import Celery
from celery.result import AsyncResult
from celery.signals import setup_logging, task_postrun
from functools import partial
from lightflow.queue.const import DefaultJobQueueName
from lightflow.queue.pickle import patch_celery
from lightflow.models.... |
1615662 | import logging
import traceback
from unittest import mock
from .common import BuiltinTest
from bfg9000.builtins import core # noqa
from bfg9000 import exceptions
from bfg9000.path import Path, Root
from bfg9000.safe_str import safe_str, safe_format
class TestCore(BuiltinTest):
def test_warning(self):
wi... |
1615670 | from itertools import groupby
class AmoebaDivTwo:
def count(self, table, K):
def count(r):
return sum(max(len(list(g)) - K + 1, 0) for k, g in groupby(r) if k == "A")
return sum(count(r) for r in table) + (
sum(count(r) for r in zip(*table)) if K > 1 else 0
)
|
1615684 | from django.urls import re_path, include, path
from .views import Classify, ClassifyTags, classify_stats
urlpatterns = [
re_path('^classify/$', Classify.as_view(), name='classify'),
re_path('^tags/$', ClassifyTags.as_view(), name='tags'),
re_path('^classify_stats/$', classify_stats),
]
|
1615740 | import numpy as np
import os, pylab
import itertools as itl
from PIL import Image, ImageDraw, ImageFont
import util as ut
import scipy.misc, scipy.misc.pilutil # not sure if this is necessary
import scipy.ndimage
from StringIO import StringIO
#import cv
def show(*args, **kwargs):
import imtable
return imtable.show... |
1615745 | import tensorflow as tf
import numpy as np
import input_data
def sample_prob(probs):
return tf.floor(probs + tf.random_uniform(tf.shape(probs), 0, 1))
# return tf.select((tf.random_uniform(tf.shape(probs), 0, 1) - probs) > 0.5, tf.ones(tf.shape(probs)), tf.zeros(tf.shape(probs)))
learning_rate = 0.1
momentum ... |
1615750 | import numpy as np
import pandas as pd
from copy import deepcopy
def super_str(x):
if isinstance(x,np.int64):
x=float(x)
if isinstance(x,int):
x=float(x)
ans=str(x)
return ans
def convert_to_array(x):
if isinstance(x, np.ndarray):
return x
else:
return np.a... |
1615755 | from running_modes.reinforcement_learning.configurations.learning_strategy_configuration import LearningStrategyConfiguration
from running_modes.reinforcement_learning.learning_strategy import BaseLearningStrategy
from running_modes.reinforcement_learning.learning_strategy import DAPStrategy
from running_modes.reinforc... |
1615769 | from PSpeedChatQuestTerminal import decodeSCQuestMsg
from PSpeedChatQuestTerminal import decodeSCQuestMsgInt
from otp.speedchat.SCDecoders import * |
1615780 | import numpy as np
import pandas as pd
from main.data import SETTINGS, IN_PAPER_NAMES, VAD, BE5, SHORT_COLUMNS
from framework.util import get_average_result_from_df, save_tsv, no_zeros_formatter, load_tsv
import datetime
import framework.util as util
directions=['be2vad', 'vad2be']
models=['baseline', 'reference_LM'... |
1615783 | from hyperparams import Hyperparams as hp
import codecs
import os
import regex
from collections import Counter
def make_vocab(fpath, fname):
"""Constructs vocabulary.
Args:
fpath: A string. Input file path.
fname: A string. Output file name.
Writes vocabulary line by line to `preproc... |
1615801 | import unittest
import geoio
import dgsamples
class TestDownsample(unittest.TestCase):
"""Test accuracy of downsampling routines.
"""
def setUp(self):
# Setup test gdal object
self.test_img = dgsamples.wv2_longmont_1k.ms
self.img = geoio.GeoImage(self.test_img)
def tearDown(se... |
1615805 | from scipy.optimize import minimize
import numpy as np
import pylab as pl
from mpl_toolkits.mplot3d import Axes3D
import math
def f(x):
""" Function that returns x_0^2 + e^{0.5*x_0} + 10*sin(x_1) + x_1^2. """
return x[0] ** 2 + math.exp(0.5 * x[0]) + 10 * math.sin(x[1]) + x[1] ** 2
def fprime(x):
""" The deri... |
1615828 | import time
import ppp4py.hdlc
import sys
import serial
import select
import binascii
import struct
surf_dev = '/dev/ttyUSB0'
surf = serial.Serial(surf_dev, baudrate=115200, timeout=5)
poller = select.poll()
poller.register(surf.fileno())
compress_ac = True
print 'Reading boot status (one line):'
while True:
t =... |
1615839 | import sys
sys.path.append("../../")
from duckietown_rl.gym_duckietown.simulator import Simulator
from keras.models import load_model
import cv2
env = Simulator(seed=123, map_name="zigzag_dists", max_steps=5000001, domain_rand=True, camera_width=640,
camera_height=480, accept_start_angle_deg=4, full_tr... |
1615849 | import pytest
pytestmark = [pytest.mark.django_db]
@pytest.fixture
def course(mixer):
return mixer.blend('products.Course')
@pytest.fixture
def order(factory, course, user):
order = factory.order(user=user, item=course)
order.set_paid()
return order
@pytest.fixture
def another_order(factory, use... |
1615855 | import numpy as np
import infotheory
class bcolors:
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKGREEN = "\033[92m"
TEST_HEADER = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
SUCCESS = bcolors.OKGREEN + "SUCCESS" + bcolors.ENDC
FAILED = bcolors.FA... |
1615893 | import numpy as np
from skimage.io import imread
# import pdb
def add_patch(img,trigger):
flag=False
if img.max()>1.:
img=img/255.
flag=True
if trigger.max()>1.:
trigger=trigger/255.
# x,y=np.random.randint(10,20,size=(2,))
x,y = np.random.choice([3, 28]), np.random.choice(... |
1615902 | import torch
import torch.nn as nn
from torch import optim
import numpy as np
import nltk
class TreeRecursiveEduNN(nn.Module):
def __init__(self, embed_dict, glove, embed_size, glove_size, hidden_size, use_relations=True):
super(TreeRecursiveEduNN, self).__init__()
self.glove = glove
self.e... |
1615928 | import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
datapath = '../util/stock_dfs/'
def get_ticker(x):
return x.split('/')[-1].split('.')[0]
def ret(x, y):
return np.log(y/x)
def get_zscore(x):
return (x -x.mean())/x.std()
def make_inputs(filepath):
D = pd.read_cs... |
1615940 | import argparse
import os
import shlex
import unittest
from gooey.gui import formatters
class TestFormatters(unittest.TestCase):
def test_counter_formatter(self):
"""
Should return the first option repeated N times
None if N is unspecified
Issue #316 - using lon... |
1615966 | import torch.nn as nn
from timm.models.layers import trunc_normal_
class Mlp(nn.Module):
""" Multilayer perceptron."""
def __init__(self, in_features, hidden_features=None, out_features=None,
num_layers=2,
act_layer=nn.GELU, drop=0.):
super().__init__()
out_fe... |
1615974 | import argparse
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.datasets import cifar10
import numpy as np
import os
parser = argparse.ArgumentParser(description='DeepJudge Seed Selection Process')
parser.add_argument('--model', required=True, type=str, help='victim model ... |
1616007 | from __future__ import annotations
import asyncio
import typing
from ctc import spec
from ... import management
from ... import connect_utils
from ... import intake_utils
from . import blocks_statements
from ..block_timestamps import block_timestamps_statements
async def async_intake_block(
block: spec.Block,
... |
1616044 | import os.path
from datetime import datetime
from unittest import mock
from unittest.mock import MagicMock
import chardet
import tablib
from core.admin import (
AuthorAdmin,
BookAdmin,
BookResource,
CustomBookAdmin,
ImportMixin,
)
from core.models import Author, Book, Category, EBook, Parent
from d... |
1616066 | class DocumentType(Enum,IComparable,IFormattable,IConvertible):
"""
Types of Revit documents.
enum DocumentType,values: BuildingComponent (4),Family (1),IFC (3),Other (100),Project (0),Template (2)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
... |
1616069 | A = set(input().split())
N = int(input())
is_strict_superset = True
for x in range(N):
S = set(input().split())
# (A > S)
is_strict_superset &= (A.issuperset(S) and A.isdisjoint(S))
print (is_strict_superset) |
1616108 | from __future__ import absolute_import, print_function
import glob
import json
import os
import pickle
from typing import Dict
import numpy as np
from loguru import logger
from tqdm import tqdm
_VALID_SUBSETS = ['train', 'test']
class LaSOT(object):
r"""`LaSOT <https://cis.temple.edu/lasot/>`_ Datasets.
P... |
1616113 | import itertools
import os
from typing import Dict, List
import dask
import fsspec
import pandas as pd
import xarray as xr
import zarr
awc_fill = 50 # mm
hist_time = slice("1950", "2014")
future_time = slice("2015", "2120")
chunks = {"time": -1, "x": 50, "y": 50}
skip_unmatched = True
# xy_region = {'x': slice(0, 10... |
1616140 | import re
import sys
import warnings
from typing import Any, Callable, Generic, TypeVar, Union
import wrapt
from ..utils import misc
from ..utils.translations import trans
_T = TypeVar("_T")
class ReadOnlyWrapper(wrapt.ObjectProxy):
"""
Disable item and attribute setting with the exception of ``__wrapped_... |
1616149 | import os
import sys
import json
import torch
import logging
from tqdm import tqdm
from . import loader_utils
from ..constant import BOS_WORD, EOS_WORD, Tag2Idx
logger = logging.getLogger()
# -------------------------------------------------------------------------------------------
# preprocess label
# ------------... |
1616162 | import json
import httpretty
import pytest
from instagram_api.client import Client
from instagram_api.request.request import ApiRequest
from instagram_api.constants import Constants
from instagram_api.utils.http import ClientCookieJar
@httpretty.activate
def test_send_request(instagram):
url = f'{Constants.API_U... |
1616173 | from data import DoomImage
import numpy as np
import time
from torch.utils.data import DataLoader
import tensorflow as tf
from tqdm import tqdm
from imageio import imwrite as imsave
from data import Places, PlacesRoom, PlacesOutdoor
from habitat_baselines.rl.models.resnet import ResNetEncoder
import habitat_baselines.r... |
1616273 | import cadquery
from copy import copy
import logging
from cqparts.utils import CoordSystem
from cqparts.utils.misc import property_buffered
from . import _casting
log = logging.getLogger(__name__)
# --------------------- Effect ----------------------
class Effect(object):
pass
class VectorEffect(Effect):
... |
1616329 | import configparser
import os
from warnings import warn
from .constants import globalconfigfile, localconfigfile
from . import backends
defaults = {
'DEFAULT': {
'header': '',
'footer': '',
},
'slurm': {},
'gridengine': {},
}
def ensure_initialized():
settings = configparser.Confi... |
1616342 | import threading
import time
import httplib
import json
import os
import datetime
# TODO put this in a properties file
mem_url = "/cat?href=/device/mem/"
cpu_url = "/cat?href=/device/cpu/"
meta_url = "/cat?href=/device/meta/"
ip_url = "/cat?href=/device/ip/"
# Till here
class resource_updater:
registry_url = ""... |
1616354 | from django import template
register = template.Library()
@register.filter
def diff(value, arg):
"""subtract arg from value
:param value: origin value
:type value: int
:param arg: value to be subtracted
:type arg: int
:return: result of subtraction
:rtype: int
"""
return value - ... |
1616357 | import re
import bs4
import requests
class Basic:
def parse(self, link):
if link['type'] == 'stickers':
return self.parse_stickers(link['link'])
if link['type'] == 'user':
return self.parse_user(link['link'])
if link['type'] == 'bot':
return self.parse_... |
1616409 | import json
import os
import shutil
import subprocess
from conftest import edl
def test_write_chapters_to_file(intro_file, tmpdir, monkeypatch):
def check_chapter(cmd):
text = subprocess.check_output(cmd)
chapter_info = json.loads(text)
if chapter_info.get('chapters'):
return ... |
1616411 | import sys
import argparse
import os
from video_classification.generator.attention_cnn_lstm_classifer import BidirectionalLSTMVideoClassifier
def check_args(args):
if not os.path.exists(args.model_path):
print('Model path {} does not exist, please check.')
exit(1)
if not os.path.exists(args.v... |
1616427 | from tbparser.events_reader import EventsFileReader, EventReadingError
from tbparser.summary_reader import SummaryReader
from tbparser.version import __version__
__all__ = [
'EventsFileReader',
'EventReadingError',
'SummaryReader',
'__version__',
]
|
1616433 | from gazette.spiders.base.fecam import FecamGazetteSpider
class ScLagunaSpider(FecamGazetteSpider):
name = "sc_laguna"
FECAM_QUERY = "cod_entidade:146"
TERRITORY_ID = "4209409"
|
1616453 | import json
import logging
import os
import re
import requests
import retrying
import shakedown
from dcos import marathon
log = logging.getLogger(__name__)
logging.basicConfig(format='[%(levelname)s] %(message)s', level='INFO')
def get_json(file_name):
""" Retrieves json app definitions for Docker and UCR backe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.