id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9850194 | import hashlib
import json
from typing import List, Set
import numpy as np
import pandas as pd
import torch
from scipy import sparse as sp
import src.config as cfg
# since they are used for check
blacklisted_clients = set(
[
"000012768d",
"000036f903",
"00010925a5",
"0001f552b0",
... |
9850195 | from sef_dr.kernel import KernelSEF
import numpy as np
from sklearn.neighbors import NearestCentroid
def test_kernel_sef():
"""
Performs some basic testing using the KernelSEF
:return:
"""
np.random.seed(1)
train_data = np.random.randn(100, 50)
train_labels = np.random.randint(0, 2, 100)
... |
9850196 | name = 'MiscUtils'
version = ('X', 'Y', 0)
docs = [
{'name': "User's Guide", 'file': 'UsersGuide.html'},
]
status = 'stable'
requiredPyVersion = (2, 6, 0)
synopsis = """MiscUtils provides support classes and functions to Webware that aren't necessarily web-related and that don't fit into one of the other frame... |
9850205 | import dovado.vivado_interaction as v
vivado = None
available_parts = [
"xc7k70tfbv676-1",
"xc7k70tfbv676-2",
"xc7k70tfbv676-2L",
"xc7k70tfbv676-3",
"xc7k70tfbv484-1",
"xc7k70tfbv484-2",
"xc7k70tfbv484-2L",
"xc7k70tfbv484-3",
"xc7k70tfbg676-1",
"xc7k70tfbg676-2",
"xc7k70tfb... |
9850217 | import sys
import os
iters = int(sys.argv[1])
root_dir = sys.argv[2]
opt = sys.argv[3]
prefix = sys.argv[4]
if len(sys.argv) > 5:
suffix = sys.argv[5]
else:
suffix = "spm"
all_files = []
for fname in os.listdir(root_dir):
if fname.startswith(prefix) and fname.endswith(suffix):
all_files.append(fn... |
9850222 | import requests
from . import FeedSource, _request_headers
class CoinEgg(FeedSource):
def _fetch(self):
feed = {}
for base in self.bases:
for quote in self.quotes:
if quote == base:
continue
url = "https://api.coinegg.im/api/v1/ticker... |
9850242 | from pytube import YouTube
from pytube import Playlist
import re
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s')
class YouTubePlaylistDownloader():
def __init__(self, playlist_url='', skip=False):
if not skip:
playlist = Playlist(playl... |
9850247 | from easydict import EasyDict
from ding.config import parallel_transform
fake_cpong_dqn_config = dict(
exp_name='fake_cpong_dqn',
env=dict(
collector_env_num=16,
collector_episode_num=2,
evaluator_env_num=8,
evaluator_episode_num=2,
stop_value=20,
),
policy=dict(... |
9850284 | def test_pose(transform):
import numpy as np
import zivid.calibration
pose = zivid.calibration.Pose(transform)
assert pose is not None
assert isinstance(pose, zivid.calibration.Pose)
assert str(pose)
np.testing.assert_array_equal(transform, pose.to_matrix())
def test_detect_feature_point... |
9850331 | from abc import ABC, abstractmethod
import threading
from typing import Dict, List
import pandas as pd
import numpy as np
from exception import RewardInvalidException
from exec import load_module_from_code, somewhat_safe_exec
from metrics import Metrics
from proto.common.v1 import common_pb2
from proto.aiengine.v1 im... |
9850339 | from twisted.plugin import IPlugin
from txircd.config import ConfigValidationError
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ChannelLevel(ModuleData):
implements(IPlugin, IModuleData)
name = "ChannelLevel"
core = True
def actions(self):
return [ (... |
9850364 | from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
_accessstrings = {0: "", 1: "readonly", 2: "executeonly", 3: "noaccess"}
class ps_object(object):
literal = 1
access = 0
value = None
def __init__(self, value):
self.value = value
self.type = self.__class__._... |
9850372 | import torch as th
import torch.nn as nn
import numpy as np
from utilities.util import select_action
from models.model import Model
from critics.mlp_critic import MLPCritic
from critics.qmix import QMixer
class FACMADDPG(Model):
def __init__(self, args, target_net=None):
super(FACMADDPG, self).__init__(a... |
9850425 | import torch
import matplotlib.pyplot as plt
def data4pred(model, dataset, dataloader, device):
preds, targets = [], []
hidden = None
with torch.no_grad():
model.eval()
for inputs, target in dataloader:
inputs = inputs.to(device)
output, hidden =... |
9850432 | from mongoengine import *
from core.observables.tag import ObservableTag, Tag
from core.observables.observable import Observable
from core.observables.ip import Ip, AutonomousSystem
from core.observables.url import Url
from core.observables.hostname import Hostname
from core.observables.hash import Hash
from core.obse... |
9850453 | import cv2
import imagezmq
from object_detection import detect_object
image_hub = imagezmq.ImageHub(open_port = 'tcp://*:5556')
sender = imagezmq.ImageSender(connect_to = 'tcp://host.docker.internal:5555')
while True:
name, image = image_hub.recv_image()
image = detect_object(image)
sender.send_image(name... |
9850495 | import pytest
import torch
from torch_complex import ComplexTensor
from espnet2.enh.decoder.stft_decoder import STFTDecoder
@pytest.mark.parametrize("n_fft", [512])
@pytest.mark.parametrize("win_length", [512])
@pytest.mark.parametrize("hop_length", [128])
@pytest.mark.parametrize("window", ["hann"])
@pytest.mark.p... |
9850514 | from fastapi import FastAPI, Depends
from fastapi_cloudauth.firebase import FirebaseCurrentUser, FirebaseClaims
tags_metadata = [
{
"name": "Firebase",
"description": "Operations with access/ID token, provided by Firebase Authentication.",
}
]
app = FastAPI(
title="FastAPI CloudAuth Projec... |
9850519 | try:
import argparse
import json
import selenium
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from sel... |
9850542 | import argparse
import textwrap
from collections import defaultdict
from copy import deepcopy
from traceback import print_exc
from typing import Sequence
import sys
def group_arguments(args, group_names):
"""Group arguments into given groups + None group for all others"""
groups = defaultdict(list)
group... |
9850566 | from LightPipes import *
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('bessel_axicon.png')
plt.imshow(img); plt.axis('off');plt.title('Bessel beam with axicon')
plt.show()
wavelength=1000.0*nm
size=10*mm
N=1000
N2=int(N/2)
ZoomFactor=10
NZ=N2/ZoomFactor
phi=179.7/180*3.1415; n1=... |
9850580 | from PIL import Image
import numpy as np
def rotate(img,angle):
rotatedArray = np.empty((Image.fromarray(img[:,:,0]).rotate(angle,Image.NEAREST,True).size)+(img.shape[-1],))
for i in range(img.shape[-1]):
rotatedArray[:,:,i] = Image.fromarray(img[:,:,i]).rotate(angle,Image.NEAREST,True)
return rota... |
9850583 | from ._base import _rule
class InsertStmt:
@_rule('insert_stmt : TABLE')
def p_insert_table(self, p):
p.lexer.append('TABLE', p[1], 1)
@_rule('insert_stmt : INSERT')
def p_insert_insert(self, p):
p.lexer.append('INSERT', p[1])
@_rule('insert_stmt : RETURNING')
def p_insert_re... |
9850596 | from copy import deepcopy
import torch
from torch.autograd import Variable
from HyperSphere.GP.inference.inference import Inference
from HyperSphere.feature_map.functionals import id_transform
class ShadowInference(Inference):
def __init__(self, train_data, model):
super(ShadowInference, self).__init__(train_dat... |
9850611 | import argparse
import sys
from .const import HELP
def args() -> None:
parser = argparse.ArgumentParser(description="Modern python project builder")
parser.add_argument("-v", "--version", action="store_true", help="Show version")
args = parser.parse_args()
if args.version:
print(HELP)
... |
9850620 | import os
from datetime import datetime
_OUTPUT_DIR = 'data'
def ensure_path(path):
if not os.path.exists(path):
os.makedirs(path)
def ensure_output_path(mod):
p = _OUTPUT_DIR + '/' + mod
ensure_path(p)
def get_output_dir(mod):
return _OUTPUT_DIR + '/' + mod
def get_output_path(mod, file):
return get... |
9850623 | from .assign_role import AssignRoleBulkAction
from .delete import DeleteBulkAction
from .set_active_state import SetActiveStateBulkAction
__all__ = ['AssignRoleBulkAction', 'DeleteBulkAction', 'SetActiveStateBulkAction']
|
9850650 | from .base import BaseRealToCplx
from .base import BaseCplxToReal
from ... import cplx
class InterleavedRealToCplx(BaseRealToCplx):
r"""Reinterpret the last dimension as interleaved real and imaginary
components of a complex tensor. The input tensor must have even number
in the last dimension, and the ou... |
9850659 | from __future__ import print_function
import numpy as np
import theano
import theano.tensor as T
import lasagne
import cPickle
import os
import sys
import random
from bisect import bisect
from time import time
import rnn_base as rnn
from sparse_lstm import *
from helpers import evaluation
from theano.sandbox.rng_mrg i... |
9850727 | import imp
import json
import codecs
import traceback
from pathlib import Path
from lyrebird import application
from lyrebird import get_logger
from lyrebird import get_plugin_storage
class AndroidTemplateIllegal(Exception):
pass
class AndroidTemplateNotFound(Exception):
pass
logger = get_logger()
def in... |
9850829 | from open_weather_api.constants import CURRENT
from open_weather_api.options.coordinates import Coordinates
config = dict(
key='194f66064a427d3f0bcca212ab703736',
units='metric',
lang='es',
type=CURRENT
)
karakate_weather = Coordinates(config, 43.1994987,-2.2879428)
print('-------------------------')... |
9850846 | from hamcrest import assert_that, equal_to
@when(u'I select the First check box')
def step_impl(context):
context.page.check_cb_id()
@when(u'I unselect the First check box')
def step_impl(context):
context.page.uncheck_cb_id()
@when(u'I search for the check box by "{how}"')
def step_impl(context, how):
... |
9850871 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas as pd
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pickle
import os
from sklearn.preprocessing import MinMaxScaler, QuantileTransformer
from sklearn.model_sele... |
9850901 | from __future__ import division, print_function, unicode_literals, absolute_import
import numpy as np
from pandas.plotting._tools import (_subplots, _flatten)
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
mpl.use('Agg', warn=False)
from matplotlib import pyplot as plt
from pandas import... |
9850908 | import git
import os
import requests
import datetime
from functools import lru_cache
import shutil
END_POINT = "https://api.github.com/repos/"
SEARCH_END_POINT = "https://api.github.com/search/"
BASE_URL = "https://github.com/"
class Github:
"""Github stats class"""
def __init__(self, token, git_url):
... |
9850913 | import logging
from .. import files
from .component import Component
logger = logging.getLogger(__name__)
class StepFunction(Component):
definition = files.StepFunctionDefinition()
# TODO: Readme should be required once we have one per task
readme = files.Readme(optional=True)
def load_config(self... |
9850930 | import numpy as np
import scipy as sp
import warnings
import scipy.sparse.linalg
from ..kernels.high_level.laplace import Laplace_Layer_Apply, \
Laplace_Layer_Singular_Apply, Laplace_Layer_Form, \
Laplace_Layer_Singular_Form
from ..misc.gmres_counter import Gmres_Counter
from ..pairing import Pairing
c... |
9850946 | from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from torch_sparse import SparseTensor
# Types for accessing data ####################################################
# Node-types are denoted by a single string, e.g.: `data['paper']`:
NodeType = str
# Ed... |
9850972 | from gino import Gino
db = Gino(
naming_convention={
"ix": "%(column_0_label)s_idx",
"uq": "%(table_name)s_%(column_0_name)s_key",
"ck": "%(table_name)s_%(constraint_name)s_check",
"fk": "%(table_name)s_%(column_0_name)s_%(referred_table_name)s_fkey",
"pk": "%(table_name)s_p... |
9851010 | import i2c_bus
class Calc:
def __init__(self, addr=0x08):
self.i2c = i2c_bus.get(i2c_bus.M_BUS)
self.addr = addr
self._available()
self.key = b''
self.string = ''
def _available(self):
if self.i2c.is_ready(self.addr) or self.i2c.is_ready(self.addr):
... |
9851017 | import os
import numpy as np
import importlib
from photogrammetry_importer.types.point import Point
from photogrammetry_importer.blender_utility.logging_utility import log_report
from photogrammetry_importer.utility.type_utility import is_float, is_int
class _DataSemantics:
def __init__(self):
self.x_idx... |
9851028 | from rpython.rlib.rarithmetic import LONG_BIT, r_longlong, r_uint
from rpython.rlib.mutbuffer import MutableStringBuffer
from rpython.rlib.rstruct import ieee
from rpython.rlib.unroll import unrolling_iterable
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.special import Ellipsis
from p... |
9851038 | from textwrap import dedent
import geopandas
import numpy as np
import pandas as pd
import pytest
from shapely import wkt
from shapely.geometry import LineString, Point
import swn
from swn.spatial import force_2d, round_coords, wkt_to_geoseries
from .conftest import matplotlib, plt
# a few static objects (not fixtu... |
9851095 | def test_fibonacci():
from eschool21_demo import fibonacci
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(5) == 5
assert fibonacci(6) == 8
assert fibonacci(7) == 13
|
9851111 | from paver.easy import * # for sh()
import os
@task
def test():
"""Run unit tests."""
import unittest
import tests
suite = unittest.defaultTestLoader.loadTestsFromModule(tests)
unittest.TextTestRunner().run(suite)
@task
def revbuild():
"""Increment the build number."""
import procgame
version_info = procgam... |
9851119 | try:
from urlparse import parse_qsl, unquote, urlparse
except ImportError:
from urllib.parse import parse_qsl, unquote, urlparse
from peewee import *
from playhouse.cockroachdb import CockroachDatabase
from playhouse.cockroachdb import PooledCockroachDatabase
from playhouse.pool import PooledMySQLDatabase
from... |
9851149 | import pytest
import util
@pytest.fixture
def train_skl():
# Example BDT creation from: https://scikit-learn.org/stable/modules/ensemble.html
from sklearn.datasets import make_hastie_10_2
from sklearn.ensemble import GradientBoostingClassifier
# Make a random dataset from sklearn 'hastie'
X, y = m... |
9851169 | import sys
import os
import platform
import configparser
from application import Application
def main():
"""
main function to launch the program
"""
# By default path if Linux user path
config_path = os.path.join(os.path.expanduser('~'), '.config', 'AirbnbScanner')
if platform.system() == "Wi... |
9851191 | import sublime
import sublime_plugin
class LtxTikzLivePreviewCommand(sublime_plugin.TextCommand):
def is_enabled(self):
return self.view.match_selector(0, "text.tex.latex.tikz")
def run(self, edit):
settings = self.view.settings()
value = settings.get("ltx_live_preview", False)
... |
9851215 | import os
import pandas as pd
from viadot.sources.base import SQL, Source
from .test_credentials import get_credentials
CREDENTIALS = get_credentials("SQL_SOURCE_TEST")
TABLE = "test"
PATH = "t.csv"
class EmptySource(Source):
def to_df(self, if_empty):
df = pd.DataFrame()
if df.empty:
... |
9851313 | from __future__ import print_function
import os
import subprocess
import glob
from unittest import TestCase
class TestAFL(TestCase):
def setUp(self):
os.chdir("examples/AVL")
def tearDown(self):
os.chdir("../..")
def test_AFL(self):
if (os.getenv("TRAVIS") == "TRUE") and (os.gete... |
9851340 | import pytest
from xrviz.describe import Describe
from . import data
def test_describe_initial(data):
describer = Describe(data)
assert describer.panel.object == "Description Section"
|
9851357 | import threading
import websockets
import asyncio
import json
class Remote(threading.Thread):
def __init__(self, host, port):
super().__init__(daemon=True)
self.endpoint = "ws://{}:{}".format(host, port)
self.lock = threading.Lock()
self.cv = threading.Condition()
self.data = None
self.sem =... |
9851368 | import logging
from django.core.management.base import BaseCommand
from couchdbkit.exceptions import BulkSaveError
from dimagi.utils.couch.database import get_db
from corehq.util.couch import categorize_bulk_save_errors
logger = logging.getLogger(__name__)
def bulk_delete(db, docs):
if not docs:
retu... |
9851391 | from fabric import task
from invoke import run as local
from patchwork.transfers import rsync
exclude_dirs = [".git", "node_modules", ".cache", ".github", "db.sqlite3"]
@task
def deploy(ctx):
local("yarn build", echo=True)
local("python manage.py collectstatic --noinput --clear", echo=True)
rsync(ctx, "... |
9851398 | import datetime
from unittest.mock import patch
from raindropio import *
raindrop = {
"_id": 2000,
"collection": {"$db": "", "$id": -1, "$ref": "collections"},
"collectionId": -1,
"cover": "",
"created": "2020-01-01T00:00:00.000Z",
"creatorRef": {"_id": 3000, "fullName": "user name"},
"dom... |
9851416 | import find_mxnet
import mxnet as mx
import numpy as np
import logging
logging.basicConfig(level=logging.DEBUG)
import argparse
from collections import namedtuple
from skimage import io, transform
from skimage.restoration import denoise_tv_chambolle
parser = argparse.ArgumentParser(description='neural style')
parser.... |
9851420 | from django.views.generic import ListView
from multigtfs.models import (
Block, Fare, FareRule, Feed, Frequency, Route, Service, ServiceDate, Shape,
ShapePoint, Stop, StopTime, Trip)
class ByFeedListView(ListView):
by_col = 'feed_id'
by_kwarg = 'feed_id'
by_class = Feed
by_classname = 'feed'
... |
9851447 | import re, pathlib
from ast import literal_eval
from setuptools import setup
HERE = pathlib.Path(__file__).parent
# Lookup version
version_search_pattern = re.compile('^__version__[ ]*=[ ]*((?:\'[^\']+\')|(?:\"[^\"]+\"))[ ]*$', re.M)
parsed = version_search_pattern.search((HERE / 'hata' / '__init__.py').read_text())
... |
9851457 | from bibliopixel.project import importer
import contextlib
@contextlib.contextmanager
def patch(object, name, value):
saved_value = getattr(object, name)
setattr(object, name, value)
try:
yield
finally:
setattr(object, name, saved_value)
|
9851479 | import numpy as np
import theano
import theano.tensor as tt
from collections.abc import Iterable, ByteString
from warnings import warn
from copy import copy
from theano.tensor.raw_random import RandomStateType
def param_supp_shape_fn(ndim_supp, ndims_params, dist_params, rep_param_idx=0, param_shapes=None):
"""... |
9851480 | import glob
import os
from loguru import logger
from df.enhance import init_df, save_audio, setup_df_argument_parser
from df.evaluation_utils import evaluation_loop
from df.model import ModelParams
def main(args):
model, df_state, suffix = init_df(
args.model_base_dir,
post_filter=args.pf,
... |
9851483 | from django.core.urlresolvers import reverse
from django.test import TestCase
from wagtail.wagtailimages.views.serve import generate_signature
from images.factories import ImageFactory
from images.views import ServeView
class ServeViewTestCase(TestCase):
def setUp(self):
self.image = ImageFactory(title="... |
9851491 | from unittest import mock
from django.contrib import messages
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from .. import exceptions
from . import factories
class SupplierAdminTest(TestCase):
TESTUSER_NAME = 'the_baconator'
TESTUSE... |
9851527 | from .sandbox import * # noqa
class DisableMigrations(object):
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
MIGRATION_MODULES = DisableMigrations()
|
9851563 | def GetNode(head, pst):
n = []
now = head
while crn != None:
n.append(crn.data)
crn = crn.next
return n[ len( n ) - pst - 1 ]
|
9851588 | from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import View, ListView, DetailView, CreateView, UpdateView
from .forms import ItemForm
from .models import Item
class HomeView(View):
def get(self, request, *args, **kwargs):
if not reque... |
9851605 | r"""
Brusselator - Using custom class
================================
This example implements the `Brusselator
<https://en.wikipedia.org/wiki/Brusselator>`_ with spatial coupling,
.. math::
\partial_t u &= D_0 \nabla^2 u + a - (1 + b) u + v u^2 \\
\partial_t v &= D_1 \nabla^2 v + b u - v u^2
Here, :ma... |
9851615 | from fontParts.base.base import (
BaseObject,
InterpolationMixin,
SelectionMixin,
dynamicProperty,
reference
)
from fontParts.base import normalizers
from fontParts.base.compatibility import LayerCompatibilityReporter
from fontParts.base.color import Color
from fontParts.base.deprecated import Depre... |
9851626 | import os
import json
import tornado.web
from pyfbi.fbi_stat import FBIStat
class IndexHandler(tornado.web.RequestHandler):
def initialize(self, stat_dir):
self.stat_dir = stat_dir
def get(self):
stats = {}
for f in os.listdir(self.stat_dir):
if f.startswith("."):
... |
9851637 | import pytest
import dowhy.datasets
from dowhy import CausalModel
class TestCausalModel(object):
@pytest.mark.parametrize(["beta", "num_instruments", "num_samples", "num_treatments"],
[(10, 1, 100, 1),])
def test_graph_input(self, beta, num_instruments, num_samples, num_treatment... |
9851688 | from mesh.generic.cmds import TDMACmds
from mesh.generic.commandType import CommandType
from struct import pack
from mesh.generic.nodeHeader import headers
from mesh.generic.nodeConfig import configHashSize
# Serialize methods
def serialize_TDMACmds_MeshStatus(cmdData, timestamp):
return pack(TDMACmdDict[TDMA... |
9851693 | import os
import sys
import shutil
import tempfile
from typing import List, Type, Optional
from io import StringIO
from unittest.mock import MagicMock
from django.dispatch import receiver # type: ignore
from django.test import SimpleTestCase, override_settings # type: ignore
import sms
from sms import send_sms
fr... |
9851718 | from Optimizer import Optimizer, has_parameter
from Epochable import Epochable
from SGD import SGD
from MomentumSGD import MomentumSGD
|
9851723 | from PIL import ImageOps
from dauphin.image.transforms.transform import DauphinTransform
class Invert(DauphinTransform):
def __init__(self, name=None, prob=1.0, level=0):
super().__init__(name, prob, level)
def transform(self, pil_img, label, **kwargs):
return ImageOps.invert(pil_img), label... |
9851724 | import sys
import argparse
import numpy as np
import logging
sys.path.append("../")
sys.path.append("../../")
sys.path.append("../../../")
sys.path.append("../../../../")
sys.path.append("../../../../../")
from experiments.utils import DISTORTIONS, LEVELS
import src.utils as utils
from src.data import get_test_load... |
9851853 | import torch
import torch.optim as optim
from iflow.dataset import drums_dataset
from torch.utils.data import DataLoader
from iflow import model
from iflow.trainers import cycle_dynamics_train
from iflow.utils.generic import to_torch
import matplotlib.pyplot as plt
import numpy as np
from iflow.visualization import v... |
9851872 | from .utils import get_X_y, evaluate_binary_classifier, load_img, ColumnSelector
try:
from inspect import signature
except ImportError:
from funcsigs import signature
__all__ = [
'get_X_y',
'evaluate_binary_classifier',
'load_img',
'ColumnSelector',
'signature'
]
|
9851931 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class FrequencyDelayedStack(nn.Module):
def __init__(self, dims):
super().__init__()
self.rnn = nn.GRU(dims, dims, batch_first=True)
def forward(self, x_time, x_freq):
# sum the inputs
x = x_... |
9851969 | from orchestra.models import WorkerCertification
from orchestra.tests.helpers import OrchestraTestCase
from orchestra.tests.helpers.fixtures import CertificationFactory
from orchestra.tests.helpers.fixtures import UserFactory
from orchestra.tests.helpers.fixtures import WorkerCertificationFactory
from orchestra.tests.h... |
9851988 | from figcli.commands.factory import Factory
from figcli.commands.figgy_context import FiggyContext
from figcli.commands.help.configure import Configure
from figcli.commands.help.login import Login
from figcli.commands.help_context import HelpContext
from figcli.config import *
from figcli.svcs.setup import FiggySetup
f... |
9852026 | r"""
Module containing the `~halotools.mock_observables.tpcf` function used to
calculate the two-point correlation function in 3d (aka galaxy clustering).
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from math import gamma
from warnings import warn
from .cl... |
9852030 | from hls4ml.model.optimizer import OptimizerPass
class EliminateLinearActivation(OptimizerPass):
def match(self, node):
cast = False
if node.__class__.__name__ == 'Activation':
cast = node.get_input_variable().type.precision != node.get_output_variable().type.precision
return no... |
9852037 | from os.path import getmtime, exists
from datetime import datetime
from matplotlib import pyplot as plt
import seaborn as sns
tt = []
for i in range(100):
path = "{:02}.py".format(i)
if not exists(path):
path = "{:02}.jl".format(i)
assert exists(path)
dt = datetime.fromtimestamp(getmtime(path))... |
9852045 | from pbhhg_py.abstract_syntax import *
from pbhhg_py.utils import *
def build_tbl(proc_functional):
def _listed_equals(seqs):
"""Check equality for lists of pbhhg values."""
seqs = list(seqs)
if not all_equal(len(l) for l in seqs):
return False
for tiers in zip(*seqs):
... |
9852122 | def print_somthing(my_name, your_name):
print("Hello {0}, My name is {1}".format(your_name, my_name))
print_somthing("Sungchul", "TEAMLAB")
print_somthing(your_name="TEAMLAB", my_name="Sungchul")
def print_somthing_2(my_name, your_name="TEAMLAB"):
print("Hello {0}, My name is {1}".format(your_name, my_name))
... |
9852133 | from prisma import validate, types
class Foo:
pass
def validator() -> None:
# case: return type instance of type passed
validated = validate(types.PostCreateInput, {})
reveal_type(validated) # T: PostCreateInput
# case: non-typeddict type
# these are allowed as we cannot type the TypeVar p... |
9852137 | from datetime import datetime, timedelta, date
import pytest
import json
from server.api.blueprints import user
from server.api.database.models import (
Appointment,
AppointmentType,
Student,
User,
WorkDay,
Payment,
Teacher,
PaymentType,
Report,
Place,
PlaceType,
Car,
... |
9852140 | from django.apps import AppConfig
class RoomConfig(AppConfig):
name = "anwesende.room"
verbose_name = "Room"
def ready(self):
try:
import anwesende.room.signals # noqa F401
except ImportError:
pass
|
9852165 | import unittest, time, sys, json, re
sys.path.extend(['.','..','../..','py'])
import h2o
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
h2o.init(3)
@classmethod
def tearDownClass(cls):
h2o.tear_down_clou... |
9852174 | import abc
import threading
from idempotency_key import utils
class IdempotencyKeyLock(abc.ABC):
@abc.abstractmethod
def acquire(self, *args, **kwargs) -> bool:
raise NotImplementedError()
@abc.abstractmethod
def release(self):
raise NotImplementedError()
class ThreadLock(Idempoten... |
9852185 | import os
import numpy as np
import matplotlib.pyplot as plt
def spec(x, curve):
x = max(-1, min(x, 1))
x = (x + 1) * 0.5
ix = x * (len(curve) - 1)
i0 = int(ix)
i1 = i0 + 1
if len(curve) <= i1:
return curve[-1]
y0, y1 = curve[i0:i1+1]
a = ix % 1.0
return y0 + a * (y1 - y... |
9852188 | import time
from threading import Event, Thread
from donkey_gym.envs.vae_env import DonkeyVAEEnv
from stable_baselines.common.vec_env import DummyVecEnv, VecNormalize, \
VecFrameStack
from stable_baselines.bench import Monitor
from donkeycar.parts.controller import PS3JoystickController
from config import ... |
9852204 | import modules
def test_currency():
assert ('currency' == modules.process_query('HKD to USD')[0])
assert ('currency' == modules.process_query('USD to INR')[0])
assert ('currency' == modules.process_query('how much is USD in EUR')[0])
intent, entities = modules.process_query('convert 5 HKD to USD')
... |
9852263 | import argparse
from train import trainIters
from evaluate import runTest
def parse():
parser = argparse.ArgumentParser(description='Attention Seq2Seq Chatbot')
parser.add_argument('-tr', '--train', help='Train the model with corpus')
parser.add_argument('-te', '--test', help='Test the saved model')
pa... |
9852284 | from lxml.builder import E
from sciencebeam_parser.utils.xml import get_text_content
class TestGetTextContent:
def test_should_return_text_of_simple_element(self):
assert get_text_content(E.parent('text 1')) == 'text 1'
|
9852362 | from library.python.envoy_requests.common.engine import Engine
from library.python.envoy_requests import get
API_LISTENER_TYPE = "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.EnvoyMobileHttpConnectionManager"
ASSERTION_FILTER_TYPE = "type.googleapis.com/envoymobile.extensions.filter... |
9852383 | from typing import Optional
from autofit.mapper.prior_model.abstract import AbstractPriorModel
from autofit.non_linear.samples import Sample
from autofit.non_linear.samples.nest import NestSamples
class UltraNestSamples(NestSamples):
def __init__(
self,
model: AbstractPriorMod... |
9852394 | from numpy import *
from scipy.special import *
def koornwinder1d(x,n):
x = 2.0*array(x)-1
np = len(x)
x = reshape(x,(np,1))
f = zeros((np,n+1))
fx = zeros((np,n+1))
for ii in range(0,n+1):
P = jacobi(ii,0,0)
P = P*sqrt(2*ii+1)
D = polyder(P)
f[:,ii] = polyval(... |
9852437 | class StopCondition(object):
def is_stop(self, train_object):
raise NotImplementedError()
def __add__(self, other):
return Or(self, other)
def __or__(self, other):
return Or(self, other)
def __mul__(self, other):
return And(self, other)
def __and__(self, other):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.