id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
117934 | from config import Config
class inputConfig():
NUM_CLASSES = 4
CLASS_DICT = {1: 'waterways', 2: 'fieldborders', 3: 'terraces', 4: 'wsb'}
CATEGORIES = list(CLASS_DICT.values())
CATEGORIES_VALUES = list(CLASS_DICT.keys())
NUM_EPOCHES = 1
# TRAIN_LAYERS = 'all'
# SAVE_TRAIN = 'logs'
IMAGE_... |
117950 | import pytest
def test_create_meshed_flow(api):
"""Demonstrates a fully meshed configuration
"""
config = api.config()
for i in range(1, 33):
config.ports.port(name='Port %s' % i, location='localhost/%s' % i)
device = config.devices.device(name='Device %s' % i)[-1]
device.ethe... |
117971 | import torch
from torch import nn
from torch.nn import functional as F
from torch.distributions.uniform import Uniform
from networks.layers.non_linear import NonLinear, NonLinearType
from networks.layers.conv_bn import ConvBN
class DropConnect(nn.Module):
def __init__(self, survival_prob):
"""
A m... |
117978 | import os
import json
import numpy as np
import scipy.sparse as sp
from src.model.linear_svm import LinearSVM
from src.model.random_forest import RandomForest
from src.metric.uar import get_UAR, get_post_probability, get_late_fusion_UAR
from src.utils.io import load_proc_baseline_feature, save_UAR_results
from src.uti... |
117984 | import ctds
from .base import TestExternalDatabase
class TestCursor(TestExternalDatabase):
def test___doc__(self):
self.assertEqual(
ctds.Cursor.__doc__,
'''\
A database cursor used to manage the context of a fetch operation.
:pep:`0249#cursor-objects`
'''
)
def test... |
118000 | import sys
import os
import torch
import unittest
import numpy as np
from TorchProteinLibrary import FullAtomModel
class TestCoords2TypedCoordsBackward(unittest.TestCase):
def setUp(self):
self.a2c = FullAtomModel.Angles2Coords()
self.c2tc = FullAtomModel.Coords2TypedCoords()
self.c2cc = FullAtomModel.CoordsTra... |
118080 | from attr import attrs, attrib
from aioalice.types import AliceObject, BaseSession, Response
from aioalice.utils import ensure_cls
@attrs
class AliceResponse(AliceObject):
"""AliceResponse is a response to Alice API"""
response = attrib(converter=ensure_cls(Response))
session = attrib(converter=ensure_c... |
118117 | import datetime
from thingsboard_gateway.tb_utility.tb_utility import TBUtility
try:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography import x509
from cryptog... |
118123 | from __future__ import absolute_import
from __future__ import print_function
import argparse
import os
import sys
import string
import subprocess, logging
from threading import Thread
import time
import socket
import commands
def get_mpi_env(envs):
"""get the mpirun command for setting the envornment
support... |
118156 | import requests
import json
from tokens.settings import BLOCKCYPHER_API_KEY
def register_new_token(email, new_token, first=None, last=None):
assert new_token and email
post_params = {
"first": "MichaelFlaxman",
"last": "TestingOkToToss",
"email": "<EMAIL>",
"token": new_token... |
118165 | import datetime
import io
from openpyxl import load_workbook
from ftc.management.commands._base_scraper import HTMLScraper
from ftc.models import Organisation, OrganisationLocation
class Command(HTMLScraper):
"""
Spider for scraping details of Registered Social Landlords in England
"""
name = "rsl"... |
118188 | import datetime as dt
import json
import logging
import os
import shutil
from typing import Any, Dict, List, Optional, Tuple, Union
import pandas as pd
from extra_model._adjectives import adjective_info
from extra_model._aspects import generate_aspects
from extra_model._filter import filter
from extra_model._summariz... |
118222 | import geopandas as gpd
import pandas as pd
from ..utils import csv_string_to_df, get_api_response
class MergeBoundaryStats:
"""境界データと統計データをマージするためのクラス"""
def __init__(
self,
app_id,
stats_table_id,
boundary_gdf,
area,
class_code,
... |
118264 | from vol import Vol
from net import Net
from trainers import Trainer
training_data = []
testing_data = []
network = None
sgd = None
N_TRAIN = 800
def load_data():
global training_data, testing_data
train = [ line.split(',') for line in
file('./data/titanic-kaggle/train.csv').read().split('... |
118274 | from __future__ import unicode_literals, absolute_import
from .alphatrade import AlphaTrade, TransactionType, OrderType, ProductType, LiveFeedType, Instrument
from alphatrade import exceptions
__all__ = ['AlphaTrade', 'TransactionType', 'OrderType',
'ProductType', 'LiveFeedType', 'Instrument', 'exceptions'... |
118292 | class Solution:
def Rob(self, nums, m, n) -> int:
prev, curr = nums[m], max(nums[m], nums[m + 1])
for i in range(m + 2, n):
prev, curr = curr, max(prev + nums[i], curr)
return curr
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
... |
118310 | from unittest import TestCase
import numpy as np
import toolkit.metrics as metrics
class TestMotion(TestCase):
def test_true_positives(self):
y_true = np.array([[1, 1, 1, 1],
[1, 0, 1, 1],
[0, 0, 0, 1]])
y_pred = np.array([[0, 1, 1, 1],
... |
118315 | import os, sys
import unittest, psutil
current_path = os.path.dirname(os.path.realpath(__file__))
project_root = os.path.abspath(os.path.join(current_path, '..'))
sys.path.insert(0, project_root)
from steamworks import STEAMWORKS
_steam_running = False
for process in psutil.process_iter():
if process.name() == '... |
118349 | from PySide2.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QPlainTextEdit, QShortcut, QMessageBox, QGroupBox, \
QScrollArea, QCheckBox, QLabel
class CodeGenDialog(QDialog):
def __init__(self, modules: dict, parent=None):
super(CodeGenDialog, self).__init__(parent)
self.modules = mo... |
118370 | from typing import Mapping
import meerkat as mk
from dcbench.common import Problem, Solution
from dcbench.common.artifact import (
DataPanelArtifact,
ModelArtifact,
VisionDatasetArtifact,
)
from dcbench.common.artifact_container import ArtifactSpec
from dcbench.common.table import AttributeSpec
class S... |
118379 | N=int(input("Enter the number of test cases:"))
for i in range(0,N):
L,D,S,C=map(int,input().split())
for i in range(1,D):
if(S>=L):
S+=C*S
break
if L<= S:
print("ALIVE AND KICKING")
else:
print("DEAD AND ROTTING") |
118381 | from typing import Optional, List, Callable, Tuple
import torch
import random
import sys
import torch.nn.functional as F
import torch.multiprocessing as mp
import torch.nn.parallel as paralle
import unittest
import torchshard as ts
from testing import IdentityLayer
from testing import dist_worker, assertEqual, set_s... |
118402 | DynamoTable # unused import (dynamo_query/__init__.py:8)
DynamoRecord # unused variable (dynamo_query/__init__.py:12)
create # unused function (dynamo_query/data_table.py:119)
memo # unused variable (dynamo_query/data_table.py:137)
filter_keys # unused function (dynamo_query/data_table.py:299)
get_column # unused... |
118411 | import logging
import asyncio
import weakref
import functools
L = logging.getLogger(__name__)
class PubSub(object):
def __init__(self, app):
self.Subscribers = {}
self.Loop = app.Loop
def subscribe(self, message_type, callback):
"""
Subscribe a subscriber to the an message type.
It could be even pla... |
118426 | from cauldron.session import projects
from cauldron.session.writing.components import bokeh_component
from cauldron.session.writing.components import definitions
from cauldron.session.writing.components import plotly_component
from cauldron.session.writing.components import project_component
from cauldron.session.writi... |
118429 | import os
from glob import glob
import numpy as np
import dlib
import cv2
from PIL import Image
def remove_undetected(directory ,detector ='hog'):
'''
Removes the undetected images in data
Args:
-----------------------------------------
directory: path to the data folder
detector: type o... |
118470 | s = 'xyzABC'
print(f'{s} is a valid identifier = {s.isidentifier()}')
s = '0xyz' # identifier can't start with digits 0-9
print(f'{s} is a valid identifier = {s.isidentifier()}')
s = '' # identifier can't be empty string
print(f'{s} is a valid identifier = {s.isidentifier()}')
s = '_xyz'
print(f'{s} is a valid id... |
118488 | import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torchvision import models
from linear_attention_transformer import ImageLinearAttention
class ResnetGenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, n_blocks=6, img_size=256):
assert(n_blocks >= 0)... |
118511 | import os
# 数据库配置
MYSQL_HOST = os.getenv('MYSQL_HOST', 'localhost')
MYSQL_PORT = os.getenv('MYSQL_PORT', '3306')
MYSQL_DATABASE = os.getenv('MYSQL_DATABASE', 'my-site')
MYSQL_USER = os.getenv('MYSQL_USER', 'admin')
MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD', '<PASSWORD>')
# redis配置
REDIS_HOST = os.getenv('REDIS_HOS... |
118514 | import pandas as pd
def resample_and_merge(df_blocks: pd.DataFrame,
df_prices: pd.DataFrame,
dict_params: dict,
freq: str = "5T"):
df = resample(df_blocks, freq, dict_params)
df_prices = resample(df_prices, freq, dict_params)
# we add ... |
118522 | from mango.relations import base
from mango.relations.constants import CASCADE
__all__ = [
"Collection",
]
class Collection(base.Relation):
def __init__(
self,
cls=None,
name=None,
multi=True,
hidden=False,
persist=True,
typ... |
118534 | import aiounittest
import copy
import pydantic
from app.github.webhook_model import Webhook
data = {
"action": 'renamed',
"pull_request": {
"merged": True
},
"repository": {
"full_name": "organization/project",
"lastName": "p",
"age": 71
},
"changes": {
... |
118562 | import argparse
import os
import re
import yaml
_ENV_EXPAND = {}
def nested_set(dic, keys, value, existed=False):
for key in keys[:-1]:
dic = dic[key]
if existed:
if keys[-1] not in dic:
raise RuntimeError('{} does not exist in the dict'.format(keys[-1]))
value = type(dic[... |
118566 | import argparse
import os
from util import util
from ipdb import set_trace as st
# for gray scal : input_nc, output_nc, ngf, ndf, gpu_ids, batchSize, norm
class BaseOptions():
def __init__(self):
self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
self.init... |
118578 | import tensorflow as tf
import numpy as np
class TFPositionalEncoding2D(tf.keras.layers.Layer):
def __init__(self, channels:int, return_format:str="pos", dtype=tf.float32):
"""
Args:
channels int: The last dimension of the tensor you want to apply pos emb to.
Keyword Args:
... |
118663 | import time
import pickle
import os
path = os.path.dirname(os.path.realpath(__file__))
path ="F:/learnning/ai/data"
def backupSave(data,fname):
now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
fullName=path+"/trainData/"+fname+"_"+now+".data"
f= open(fullName, 'wb')
pic... |
118684 | import torch
from Utils import *
import torchvision
import math
import numpy as np
import faiss
from Utils import LogText
import clustering
from scipy.optimize import linear_sum_assignment
import imgaug.augmenters as iaa
import imgaug.augmentables.kps
class SuperPoint():
def __init__(self, number_of_clusters, co... |
118714 | import json
import os
import io
import re
from collections import defaultdict
import flask
from flask import Flask
app = Flask(__name__)
#ndcg_eval_dir = "data/ndcg_eval_dir"
origs = {}
needed_judgements = defaultdict(list)
# From http://stackoverflow.com/questions/273192/how-to-check-if-a-directory-exists-and-cre... |
118736 | import urllib
image = urllib.URLopener()
for k in xrange(300,400):
try:
image.retrieve("http://olympicshub.stats.com/flags/48x48/"+str(k)+".png",str(k)+".png")
except:
print k |
118739 | from __future__ import print_function
import argparse
import torch
import torch.utils.data
from torch import nn, optim
from torch.autograd import Variable
from torchvision import datasets, transforms
from torchvision.utils import save_image
from torch.nn import functional as F
import numpy as np
import collections
from... |
118767 | from typing import List, Tuple, Union
from io import StringIO
from nltk.corpus import stopwords
import torch
from torch import Tensor
import torch.nn.functional as F
from transformers import BertTokenizer, BertForMaskedLM
from transformers.tokenization_utils import PreTrainedTokenizer
class MaskedStego:
def __in... |
118777 | import torch.autograd as autograd
import torch.nn.functional as F
from torch.autograd import Variable
def linear(inputs, weight, bias, meta_step_size=0.001, meta_loss=None, stop_gradient=False):
if meta_loss is not None:
if not stop_gradient:
grad_weight = autograd.grad(meta_loss, weight, cre... |
118815 | import torch
import numpy as np
from elf.io import open_file
from elf.wrapper import RoiWrapper
from ..util import ensure_tensor_with_channels
class RawDataset(torch.utils.data.Dataset):
"""
"""
max_sampling_attempts = 500
@staticmethod
def compute_len(path, key, patch_shape, with_channels):
... |
118821 | from b_rabbit import BRabbit
def event_listener(msg):
print('Event received')
print("Message body is: " + msg.body)
print("Message properties are: " + str(msg.properties))
rabbit = BRabbit(host='localhost', port=5672)
subscriber = rabbit.EventSubscriber(
b_rabbit=rabb... |
118834 | from src.platform.tomcat.interfaces import AppInterface
class FPrint(AppInterface):
def __init__(self):
super(FPrint, self).__init__()
self.version = "3.3"
self.uri = "/doc/readme"
|
118835 | import sqlalchemy as db
from sqlalchemy.orm import relationship
from src.db import helper
from src.db.sqlalchemy import Base
from src.model.category import Category
class Local(Base):
__tablename__ = 'compra_local_local'
id = db.Column(db.Integer, helper.get_sequence(__tablename__), primary_key=True)
... |
118861 | from .acting_interface import ActingInterface
class ActorWrapper(ActingInterface):
"""Wrapper for a created actor
Allows overriding only specific actor methods while passing through the
rest, similar to gym wrappers
"""
def __init__(self, actor):
super().__init__(*actor.get_spaces())
... |
118870 | from pyradioconfig.parts.jumbo.calculators.calc_synth import CALC_Synth_jumbo
class CALC_Synth_nixi(CALC_Synth_jumbo):
pass |
118884 | from __future__ import absolute_import
_F='\ufeff'
_E='\x00'
_D=False
_C='ascii'
_B='\n'
_A=None
import codecs
from .error import YAMLError,FileMark,StringMark,YAMLStreamError
from .compat import text_type,binary_type,PY3,UNICODE_SIZE
from .util import RegExp
if _D:from typing import Any,Dict,Optional,List,Union,Text,T... |
118904 | import argparse
from src.utils.logger import Logger
class CustomFormatter(
argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter
):
pass
class CustomArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
super().__init__(
formatter_class... |
118906 | import string
def arcade_int_to_string(key: int, mod: int) -> str:
if 97 <= key <= 122:
if (mod & 1) == 1:
return string.ascii_uppercase[key-97]
else:
return string.ascii_lowercase[key-97]
elif 48 <= key <= 57:
return str(key - 48)
elif 65456 <= key <= 65465... |
118933 | import os
import sys
import unittest
relative_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
if relative_path not in sys.path:
sys.path.insert(0, relative_path)
from onesaitplatform.auth.token import Token
from onesaitplatform.auth.authclient import AuthClient
class AuthClientTest(unittest.Te... |
118948 | import lzma
def lzma_compress(data):
# https://svn.python.org/projects/external/xz-5.0.3/doc/lzma-file-format.txt
compressed_data = lzma.compress(
data,
format=lzma.FORMAT_ALONE,
filters=[
{
"id": lzma.FILTER_LZMA1,
"preset": 6,
... |
118987 | import sys
import os
from pathlib import Path
# parameter handling
path = 0
if len(sys.argv)>1:
path = sys.argv[1]
else:
raise RuntimeError("missing argument")
src = Path(path)
if not src.exists():
raise RuntimeError("path does not exist")
if src.parts[0] != "pycqed":
raise RuntimeError("path should ... |
118990 | from Bio import AlignIO
def get_id_from_tag(alignment,tag):
"""return the index of an alignment given the alignment tag"""
for index in range(len(alignment)):
if(alignment[index].id == tag):
return index
raise LookupError("invalid tag specified")
def find_gaps(alignment,tag):
"""re... |
119003 | import logging
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
from wouso.core.common import Item, CachedItem
from wouso.core.decorators import cached_method, drop_cache
from wouso.core.game import get_games
from wouso.core.game.models import Game
class Coin(Cach... |
119004 | from .flow.models import _META_ARCHITECTURES as _FLOW_META_ARCHITECTURES
from .stereo.models import _META_ARCHITECTURES as _STEREO_META_ARCHITECTURES
_META_ARCHITECTURES = dict()
_META_ARCHITECTURES.update(_FLOW_META_ARCHITECTURES)
_META_ARCHITECTURES.update(_STEREO_META_ARCHITECTURES)
def build_model(cfg):
met... |
119026 | import torch
def kl_divergence(mu, sigma, mu_prior, sigma_prior):
kl = 0.5 * (2 * torch.log(sigma_prior / sigma) - 1 + (sigma / sigma_prior).pow(2) + ((mu_prior - mu) / sigma_prior).pow(2)).sum()
return kl
def softplusinv(x):
return torch.log(torch.exp(x)-1.) |
119038 | def create_model(opt):
model = None
print(opt.model)
#Set dataset mode and load models based on the selected model (pGAN or cGAN)
if opt.model == 'cGAN':
opt.dataset_mode = 'unaligned_mat'
from .cgan_model import cGAN
model = cGAN()
elif opt.model == 'pGAN':
opt.datas... |
119053 | from IPython.display import HTML
from jupyter_client import find_connection_file
from tornado.escape import url_escape
from tornado.httpclient import HTTPClient
import collections
import intrusion
import json
import ndstore
import neuroglancer
# volumes of all viewer instances
volumes = {}
class Viewer(neuroglancer.B... |
119083 | import gym
from tf_rl.common.wrappers import CartPole_Pixel
env = CartPole_Pixel(gym.make('CartPole-v0'))
for ep in range(2):
env.reset()
for t in range(100):
o, r, done, _ = env.step(env.action_space.sample())
print(o.shape, o.min(), o.max())
if done:
break
env.close()
|
119088 | from __future__ import annotations
from typing import Optional, TypeVar, Union
import numpy as np
from typing_extensions import Final
from ...representation import FData
from ...representation._typing import NDArrayFloat
from .._math import cosine_similarity, cosine_similarity_matrix
from ._utils import pairwise_met... |
119111 | import os
import sqlite3
import json
import datetime
from shutil import copyfile
from werkzeug._compat import iteritems, to_bytes, to_unicode
from jam.third_party.filelock import FileLock
import jam
LANG_FIELDS = ['id', 'f_name', 'f_language', 'f_country', 'f_abr', 'f_rtl']
LOCALE_FIELDS = [
'f_decimal_point', 'f... |
119221 | from speculator.features.RSI import RSI
import unittest
class RSITest(unittest.TestCase):
def test_eval_rs(self):
gains = [0.07, 0.73, 0.51, 0.28, 0.34, 0.43, 0.25, 0.15, 0.68, 0.24]
losses = [0.23, 0.53, 0.18, 0.40]
self.assertAlmostEqual(RSI.eval_rs(gains, losses), 2.746, places=3)
d... |
119260 | import laurelin
def test_1_brackets():
output = laurelin.balanced_brackets("[[]]({}[])")
assert output == True
def test_2_brackets():
output = laurelin.balanced_brackets("[[({}[])")
assert output == False
def test_3_brackets():
output = laurelin.balanced_brackets("")
assert output == True
... |
119274 | import torch
import numpy as np
from bc.dataset.dataset_lmdb import DatasetReader
from sim2real.augmentation import Augmentation
from sim2real.transformations import ImageTransform
CHANNEL2SPAN = {'depth': 1, 'rgb': 3, 'mask': 1}
class Frames:
def __init__(self,
path,
channels=... |
119295 | from blesuite.pybt.gap import GAP
import blesuite.pybt.att as att
import logging
log = logging.getLogger(__name__)
# log.addHandler(logging.NullHandler())
class BTEventHandler(object):
"""
BTEventHandler is a event handling class passed to the BLEConnectionManager in order to
have user-controlled callbac... |
119302 | config = {
# --------------------------------------------------------------------------
# Database Connections
# --------------------------------------------------------------------------
'database': {
'default': 'auth',
'connections': {
# SQLite
# 'auth': {
... |
119313 | from machine.utils.collections import CaseInsensitiveDict
from machine.utils import sizeof_fmt
from tests.singletons import FakeSingleton
def test_Singleton():
c = FakeSingleton()
c2 = FakeSingleton()
assert c == c2
def test_CaseInsensitiveDict():
d = CaseInsensitiveDict({'foo': 'bar'})
assert '... |
119371 | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("rf_classify_parallel", ["rf_classify_parallel.pyx"])],
extra_compile_args=['/openmp'],
include_dirs ... |
119372 | import unittest
from mygrations.formats.mysql.file_reader.database import database as database_reader
class test_table_1215_regressions(unittest.TestCase):
def test_foreign_key_without_index(self):
""" Discovered that the system was not raising an error for a foreign key that didn't have an index for the t... |
119382 | from remote.remote_util import RemoteMachineShellConnection
from .tuq import QueryTests
import time
from deepdiff import DeepDiff
from membase.api.exception import CBQError
class QueryWindowClauseTests(QueryTests):
def setUp(self):
super(QueryWindowClauseTests, self).setUp()
self.log.info("=======... |
119449 | from os import path as osp
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import lstsq
from scipy.ndimage import gaussian_filter
from scipy import interpolate
import argparse
import sys
sys.path.append("..")
import Basics.params as pr
import Basics.sensorParams as psp
from Basics.Geome... |
119453 | from sklearn.metrics import classification_report
from metrics import conlleval
# label_test_file = 'output/MSRA/crf/result.txt'
# eval_file = 'output/MSRA/crf/eval_crf.txt'
# label_test_file = 'output/ywevents/crf/result.txt'
# eval_file = 'output/ywevents/crf/eval_crf.txt'
label_test_file = 'output/ywevents/char... |
119502 | from tgt_grease.core.Types import Command
from tgt_grease.core import ImportTool
import importlib
class Help(Command):
"""The Help Command for GREASE
Meant to provide a rich CLI Experience to users to enable quick help
"""
purpose = "Provide Help Information"
help = """
Provide help informa... |
119508 | import arcade
def test_point_in_rectangle():
polygon = [
(0, 0),
(0, 50),
(50, 50),
(50, 0),
]
result = arcade.is_point_in_polygon(25, 25, polygon)
assert result is True
def test_point_not_in_empty_polygon():
polygon = []
result = arcade.is_point_in_polygon(25... |
119515 | import pandas as pd
from pathlib import Path
def process_files(input_dir, output_dir, record_name):
img_dir = output_dir / 'images'
labels_dir = output_dir / 'labels'
record_path = output_dir / record_name
class_path = output_dir / 'classes.names'
img_dir.mkdir(exist_ok=True)
labels_dir.mkdi... |
119544 | import subprocess
import sys
import eventlet.queue
import eventlet.tpool
import eventlet.green.subprocess
from eventlet import green
from eventlet.greenpool import GreenPool
from .BaseTerminal import BaseTerminal
import logging
logger = logging.getLogger(__name__)
class SubprocessTerminal(BaseTerminal):
def __... |
119547 | import torch.nn as nn
from Models.PathEncoder import PathEncoder
from Models.SequenceEncoder import SequenceEncoder
from Models.Transformer import Transformer
from Models.OperationMix import OperationMix
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence, pack_sequence
import torch
class Encoder... |
119569 | import os
from os.path import abspath, dirname, join
from setuptools import setup, find_packages
INIT_FILE = join(dirname(abspath(__file__)), 'pydux', '__init__.py')
def long_description():
if os.path.exists('README.txt'):
return open('README.txt').read()
else:
return 'Python implementation of... |
119629 | from aiohttp import web
from redbull import Manager
mg = Manager(web.Application())
@mg.api()
async def say_hi(name: str, please: bool):
"Says hi if you say please"
if please:
return 'hi ' + name
return 'um hmm'
mg.run()
|
119648 | from haro.plugins.alias_models import UserAliasName
from haro.slack import get_slack_id_by_name
def get_slack_id(session, user_name):
"""指定したユーザー名のSlackのuser_idを返す
Slackのユーザー名として存在すればAPIからuser_idを取得
取得できない場合、user_alias_nameにエイリアス名として登録されたユーザー名であれば、
それに紐づくSlackのuser_idを返す
:params session: sqlalch... |
119679 | def get_version_from_win32_pe(file):
# http://windowssdk.msdn.microsoft.com/en-us/library/ms646997.aspx
sig = struct.pack("32s", u"VS_VERSION_INFO".encode("utf-16-le"))
# This pulls the whole file into memory, so not very feasible for
# large binaries.
try:
filedata = open(file).read()
e... |
119689 | class NodeConfig:
def __init__(self, node_name: str, ws_url: str) -> None:
self.node_name = node_name
self.ws_url = ws_url
|
119693 | import inspect
import torch.optim.lr_scheduler as lr_scheduler
from ocpmodels.common.utils import warmup_lr_lambda
class LRScheduler:
"""
Learning rate scheduler class for torch.optim learning rate schedulers
Notes:
If no learning rate scheduler is specified in the config the default
sc... |
119740 | from __future__ import absolute_import
from typing import List, Dict, Any, Optional
from tinydb import TinyDB, Query
from tinydb.operations import add, decrement, set
import logging
import random
db = TinyDB('../data/list.json', indent=4)
teamdata = Query()
file = '../teams/2020ICPCJinan'
f = open(file, 'r')
ranklist ... |
119793 | from typing import List
import datasets
# Citation, taken from https://github.com/microsoft/CodeXGLUE
_DEFAULT_CITATION = """@article{CodeXGLUE,
title={CodeXGLUE: A Benchmark Dataset and Open Challenge for Code Intelligence},
year={2020},}"""
class Child:
_DESCRIPTION = None
_FEATURES = N... |
119798 | from tkinter import Tk
from pyDEA.core.gui_modules.custom_canvas_gui import StyledCanvas
from pyDEA.core.utils.dea_utils import bg_color
def test_bg_color():
parent = Tk()
canvas = StyledCanvas(parent)
assert canvas.cget('background') == bg_color
parent.destroy()
|
119812 | from nose.tools import assert_equal, assert_raises
class TestProdThree(object):
def test_prod_three(self):
solution = Solution()
assert_raises(TypeError, solution.max_prod_three, None)
assert_raises(ValueError, solution.max_prod_three, [1, 2])
assert_equal(solution.max_prod_three(... |
119841 | import ChromaPy32 as Chroma # Import the Chroma Module
from time import sleep # Import the sleep-function
Headset = Chroma.Headset() # Initialize a new Headset Instance
RED = (255, 0, 0) # Initialize a new color by RGB (RED,GREEN,BLUE)
for x in range(0, Headset.MaxLED): # for-loop with Headset.MaxLED as iterati... |
119890 | import re
def soundex(name):
return ' '.join(process_word(word).upper()
for word in
name.split(' ')
)
def process_word(word):
fl = word[0]
word = word.lower()
word = word[0] + re.sub('[hw]', '', word[1:])
word = word.tr... |
119908 | from typing import List
from boa3.builtin import public
@public
def main(string: str, sep: str, maxsplit: int) -> List[str]:
return string.split(sep, maxsplit)
|
119926 | from twindb_backup.configuration import TwinDBBackupConfig
def test_gcs(config_file):
tbc = TwinDBBackupConfig(config_file=str(config_file))
assert tbc.gcs.gc_credentials_file == 'XXXXX'
assert tbc.gcs.gc_encryption_key == ''
assert tbc.gcs.bucket == 'twindb-backups'
def test_no_gcs_section(tmpdir):... |
119977 | import os
import argparse
from sentivi import Pipeline
from sentivi.data import DataLoader, TextEncoder
from sentivi.classifier import *
from sentivi.text_processor import TextProcessor
CLASSIFIER = SVMClassifier
ENCODING_TYPE = ['one-hot', 'bow', 'tf-idf', 'word2vec']
if __name__ == '__main__':
argument_parser... |
119978 | import abc
from typing import Union
import lunzi.nn as nn
class BasePolicy(abc.ABC):
@abc.abstractmethod
def get_actions(self, states):
pass
BaseNNPolicy = Union[BasePolicy, nn.Module] # should be Intersection, see PEP544
|
119998 | import os
import pytest
@pytest.fixture
def test_data():
import numpy as np
test_data_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'data', 'laserembeddings-test-data.npz')
return np.load(test_data_file) if os.path.isfile(test_data_file) else None
|
120023 | from typing import Iterable, Optional
class Professor:
"""
A professor is one or many people in charge of a given academical event.
:param name: the name(s)
:type name: str
:param email: the email(s)
:type email: Optional[str]
"""
def __init__(self, name: str, email: Optional[str] = ... |
120063 | import itertools
import numpy as np
import matplotlib.pyplot as plt
import pdb
import ad3.factor_graph as fg
num_nodes = 5 #30
max_num_states = 2 #5
lower_bound = 3 #5 # Minimum number of zeros.
upper_bound = 4 #10 # Maximum number of zeros.
# Create a random tree.
max_num_children = 5
parents = [-1] * num_nodes
ava... |
120075 | import math
from rlbot.agents.base_agent import BaseAgent, SimpleControllerState
from rlbot.utils.structures.game_data_struct import GameTickPacket
class Vector3:
def __init__(self,a,b,c):
self.data = [a,b,c]
def __getitem__(self,key):
return self.data[key]
def __str__(self):
retur... |
120109 | import sys
from webob import Request
from pydap.responses.error import ErrorResponse
from pydap.lib import __version__
import unittest
class TestErrorResponse(unittest.TestCase):
def setUp(self):
# create an exception that would happen in runtime
try:
1/0
except Exception:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.