id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1745682 | import array
import copy
import pickle
import numpy as np
import pytest
from mspasspy.ccore.seismic import (_CoreSeismogram,
_CoreTimeSeries,
Seismogram,
SeismogramEnsemble,
... |
1745689 | import csv
class Parser:
def __init__(self):
self.profiles = {}
self.conditions = []
self.probe_list = {}
def read_plot(self, plotfile, conversion):
"""
Reads a plot file and a converts the probe IDs to plots
:param plotfile: path to the Plot File
:par... |
1745769 | from django.contrib import admin
from django.template.defaultfilters import filesizeformat
from django.utils.formats import date_format
from django.utils.html import format_html, format_html_join, mark_safe
from django.utils.translation import gettext_lazy as _
from cabinet.base_admin import FileAdminBase
from cabinet... |
1745853 | from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import argparse
import torch
from utils.names_match_torch import methods
import os
import numpy as np
from utils.common import create_code_snapshot
def main(args):
# print args recap
print(args, end="\... |
1745857 | import os
import shutil
import numpy as np
from collections import namedtuple
import glob
import time
import datetime
import pickle
import torch
import matplotlib.pyplot as plt
from termcolor import cprint
from navpy import lla2ned
from collections import OrderedDict
from dataset import BaseDataset
from utils_torch_fil... |
1745866 | import numpy as np
def side_speedmatch_foottraj_reward(self):
qpos = np.copy(self.sim.qpos())
qvel = np.copy(self.sim.qvel())
forward_diff = np.abs(qvel[0] -self.speed)
orient_diff = np.linalg.norm(qpos[3:7] - np.array([1, 0, 0, 0]))
side_diff = np.abs(qvel[1] - self.side_speed)
if forward... |
1745873 | from crits.core.crits_mongoengine import EmbeddedCampaign
from crits.vocabulary.indicators import (
IndicatorThreatTypes,
IndicatorAttackTypes
)
def migrate_indicator(self):
"""
Migrate to the latest schema version.
"""
migrate_4_to_5(self)
def migrate_4_to_5(self):
"""
Migrate from s... |
1745913 | import typing as t
import jwt
from starlette import authentication
from starlette.requests import Request
from backend import constants
# We must import user such way here to avoid circular imports
from .user import User
class JWTAuthenticationBackend(authentication.AuthenticationBackend):
"""Custom Starlette a... |
1745942 | import unittest
import mock
from scream.monorepo import Monorepo, version_counter
from scream.package import Package
class MockPackage(Package):
"""Override Package constructor so we can test the individual methods.
"""
def __init__(self):
pass
class MockScream():
def __init__(self, packa... |
1745948 | import csv
import cv2
import os
import numpy as np
import glob
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from ..base import BaseDataset
from ..utils import image_loader
from .schemas import SegmentationDatasetSchema
#"Background": 0
#"Buildings": 1
LABELS = ["Background", "Buildings"]
# Co... |
1745978 | from __future__ import print_function
import json
print('Loading function')
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
print("value1 = " + event['key1'])
print("value2 = " + event['key2'])
print("value3 = " + event['key3'])
return "Hello W... |
1745983 | import unittest
from unittest import mock
from dataprofiler.labelers import base_model
class TestBaseModel(unittest.TestCase):
@mock.patch('dataprofiler.labelers.base_model.BaseModel.'
'_BaseModel__subclasses',
new_callable=mock.PropertyMock)
def test_register_subclass(self, ... |
1745991 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.internal_gains import ComfortViewFactorAngles
log = logging.getLogger(__name__)
class TestComfortViewFactorAngles(unittest.TestCase):
def setUp(self):
self.fd, self... |
1746038 | import unittest
import numpy as np
from scipy import sparse as sp
from linearSVM import *
class PrimalSVMTests(unittest.TestCase):
def setUp(self):
self.X = np.array([[0.5, 0.3], [1, 0.8], [1, 1.4], [0.6, 0.9]])
self.Y = np.array([-1, -1, 1, 1])
self.svm = PrimalSVM()
self.svm._X ... |
1746048 | import atexit
import asyncio
from weakref import WeakSet
from contextlib import contextmanager
_toplevel_registered = WeakSet()
_toplevel_managers = WeakSet()
_toplevel_registrable = set()
_toplevel_managers_temp = set()
mountmanager = None # import later
def register_toplevel(ctx):
global mountmanager
from ... |
1746062 | import os, sys
os.system("cd .. && rm -rf IISUS && git clone https://github.com/batyarimskiy/IISUS && cd IISUS && clear")
print('обновление завершено!')
|
1746085 | from mfr.core.exceptions import RendererError
class InvalidFormatError(RendererError):
__TYPE = 'ipynb_invalid_format'
def __init__(self, message, *args, code: int=400, download_url: str='',
original_exception: Exception=None, **kwargs):
super().__init__(message, *args, code=code, r... |
1746145 | import unittest
import numpy as np
from spartan import expr, util
from spartan.util import Assert
import test_common
ARRAY_SIZE = (10, 10)
class TestReduce(test_common.ClusterTest):
def test_sparse_create(self):
x = expr.sparse_rand(ARRAY_SIZE, density=0.001)
x.evaluate()
def test_sparse_glom(self):
... |
1746279 | import os
import csv
import json
import torch
import random
import signal
import numpy as np
from itertools import groupby
from typing import List, Dict
def read_conll(filename, columns, delimiter='\t'):
def is_empty_line(line_pack):
return all(field.strip() == '' for field in line_pack)
data = []
... |
1746317 | import tensorflow as tf
import tensorflow_hub as hub
from models.sml.sml import SML
from networks.maml_umtra_networks import MiniImagenetModel, VoxCelebModel
from databases import VoxCelebDatabase
def run_celeba():
vox_celeb_database = VoxCelebDatabase()
feature_model = hub.Module("https://tfhub.dev/google/s... |
1746325 | from __future__ import absolute_import
import warnings
import six
from ..backward_layers.utils import backward_relu_, backward_softplus_
from .utils import V_slope
from tensorflow.keras.layers import Layer
from ..layers import F_FORWARD, F_IBP, F_HYBRID
from ..layers.utils import (
sigmoid_prime,
get_linear_hul... |
1746329 | from .chamfer import chamfer_loss, ChamferLoss
from .emd import earth_mover_distance, EarthMoverDistance
|
1746332 | import functools
import os
import subprocess
import sys
PYTHON_INTERPRETER = os.path.abspath(sys.executable)
_PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
_ENV_DIR = os.environ.get("VIRTUALENV_PATH", os.path.join(_PROJECT_ROOT, ".env"))
from_project_root = functools.partial(os.path... |
1746359 | import sys
import paramiko
import re
from basetestcase import BaseTestCase
import json
import os
import zipfile
import pprint
import queue
import json
from membase.helper.cluster_helper import ClusterOperationHelper
import mc_bin_client
import threading
from memcached.helper.data_helper import VBucketAwareMemcached
fr... |
1746389 | import random
import string
from django.db import models
from django_mysql.models import JSONField
class DailyAttendance(models.Model):
"""
attendance = { "2016": {"user_id": [1, s_time, e_time], "user_id": [0, s_time, e_time]} }
"""
date = models.DateField()
attendance = JSONField()
def __... |
1746426 | from open3d.io import read_point_cloud # even if import * works, this line could fail
from open3d import *
|
1746483 | import abc
from datetime import datetime
from typing import Generic, Iterable, Tuple, TypeVar
from tinkoff.invest.caching.instrument_date_range_market_data import (
InstrumentDateRangeData,
)
TInstrumentData = TypeVar("TInstrumentData")
class IInstrumentMarketDataStorage(abc.ABC, Generic[TInstrumentData]):
... |
1746515 | import logging
from curio import sleep, Queue
from bricknil import attach, start
from bricknil.hub import PoweredUpRemote, BoostHub
from bricknil.sensor import InternalMotor, RemoteButtons, LED, Button, ExternalMotor
from bricknil.process import Process
from bricknil.const import Color
from random import randint
@at... |
1746535 | from __future__ import absolute_import
import sys
from datetime import datetime
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.sax.saxutils import escape
from .helpers import datetime_to_api_timezone
from .constants import (AUTOTASK_API_QUERY_ID_LIMIT,
AUTOTASK_API_QUER... |
1746568 | from __future__ import absolute_import
from builtins import str
from builtins import range
from builtins import object
try:
from collections import OrderedDict # 2.7
except ImportError:
from sqlalchemy.util import OrderedDict
from ckan.lib import helpers as h
from logging import getLogger
import re
from . im... |
1746590 | import hetu as ht
from hetu import init
import numpy as np
def layer_norm(
input_tensor,
feature_size,
eps=1e-8
):
scale = init.ones(name='layer_norm_scale', shape=(feature_size, ))
bias = init.zeros(name='layer_norm_biad', shape=(feature_size, ))
return ht.layer_normalization_op(input_tensor,... |
1746627 | from app import db
from datetime import datetime, date, time
from sqlalchemy import func
class Offer(db.Model):
__tablename__ = "offer"
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey(
"app_user.id"), nullable=False)
event_id = db.Column(db.Int... |
1746647 | import os
import stat
import tempfile
import unittest
from unittest.mock import MagicMock
import test_utils
from concourse.client.model import BuildStatus
from concourse.steps import step_def
from concourse.model.base import ScriptType
from concourse.model.job import JobVariant
from concourse.model.resources import ... |
1746678 | import paddle.fluid as fluid
import paddle.fluid.dygraph.nn as nn
import paddle.fluid.layers as L
from utils import ConvModule, model_size
from models.resnet import ResNet, BasicBlock, make_res_layer
from models.triple_loss import TripletLoss
class DeCoder(fluid.dygraph.Layer):
def __init__(self,
... |
1746680 | from spotdl.encode import EncoderBase
from spotdl.encode.exceptions import EncoderNotFoundError
import pytest
class TestAbstractBaseClass:
def test_error_abstract_base_class_encoderbase(self):
encoder_path = "ffmpeg"
_loglevel = "-hide_banner -nostats -v panic"
_additional_arguments = ["-b... |
1746683 | import django.dispatch
saved_file = django.dispatch.Signal(providing_args=['fieldfile'])
"""
A signal sent for each ``FileField`` saved when a model is saved.
* The ``sender`` argument will be the model class.
* The ``fieldfile`` argument will be the instance of the field's file that was
saved.
"""
thumbnail_creat... |
1746707 | import torch
import torch.nn as nn
from torchvision.ops import nms
import numpy as np
class DecodeBox():
def __init__(self, anchors, num_classes, input_shape, anchors_mask = [[6,7,8], [3,4,5], [0,1,2]]):
super(DecodeBox, self).__init__()
self.anchors = anchors
self.num_class... |
1746711 | import torch
import torch.nn as nn
# from torch.autograd import Variable
import src.utils.init as my_init
from .basic import BottleSoftmax
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, d_model, attn_dropout=0.1):
super(ScaledDotProductAttention, se... |
1746721 | from telegraph import Telegraph
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from userbot.cmdhelp import CmdHelp
from userbot.utils import admin_cmd
telegraph = Telegraph()
mee = telegraph.create_account(short_name="yohohehe")
@borg.on(admin_cmd(pattern="recognized ?(.*)"... |
1746722 | from pathlib import Path
import numpy as np
import torch
from utils.utils import load_pickle, logger
class ModelCheckpoint(object):
"""Save the model after every epoch.
# Arguments
checkpoint_dir: string, path to save the model file.
monitor: quantity to monitor.
verbose: ve... |
1746728 | from json import dumps as json_dumps
from inoft_vocal_framework.platforms_handlers.handler_input import HandlerInput
class LambdaResponseWrapper:
def __init__(self, response_dict: dict):
if not isinstance(response_dict, dict):
raise Exception(f"The response_dict must be of type dict and is of ... |
1746843 | load("@npm_bazel_karma//:defs.bzl", _ts_web_test_suite = "ts_web_test_suite")
def ts_web_test_suite(name, browsers = [], tags = [], **kwargs):
_ts_web_test_suite(
name = name,
tags = tags + ["native", "no-bazelci"],
browsers = browsers,
**kwargs
)
# BazelCI docker images ar... |
1746852 | import cv2
import pandas as pd
def extract_color_data(inputpath, outputpath):
image = cv2.imread(inputpath)
B, G, R = cv2.split(image)
# 数组展平
b = B.ravel()
g = G.ravel()
r = R.ravel()
# 矩阵转置
channels = list(zip(b, g, r))
colors = ['b', 'g', 'r']
dt = pd.DataFrame(channels, colu... |
1746897 | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from data.util import is_wav_file, find_files_of_type
from models.audio_resnet import resnet34, resnet50
from models.tacotron2.taco_utils import load_wav_to_torch
from scripts.byol.byol_extract_wrapped_model import extract_byol_model_from_st... |
1746917 | import sys
import os
sys.path.append(os.path.dirname(__file__)+'/'+'..')
import parseHelper.LuaType as lt
import parseHelper.RuleType as rt
RULES=rt.NormalRule({
"战斗名" :{"to" : "key" , "type" : lt.LuaStr },
"战斗场景图" :{"to" : "mapkey" , "type" : lt.LuaStr },
"音乐" :{"to" : "music" , "type" : lt.LuaStr },
... |
1746960 | import logging
from e2e.utils.cognito_bootstrap import common
from e2e.utils.aws.acm import AcmCertificate
from e2e.utils.aws.cognito import CustomDomainCognitoUserPool
from e2e.utils.aws.route53 import Route53HostedZone
from e2e.utils.utils import print_banner, load_yaml_file
from e2e.utils.load_balancer.lb_resources... |
1747002 | from collections.abc import Mapping
from typing import Type
from django.db.migrations.state import ModelState
from django.db.models import Model
from psqlextra.models import PostgresModel
class PostgresModelState(ModelState):
"""Base for custom model states.
We need this base class to create some hooks int... |
1747105 | import numpy as np
import matplotlib.pyplot as plt
import mir3.modules.tool.wav2spectrogram as wav2spec
eps = np.finfo(float).eps
def inDb(a):
return 20 * np.log10(a + eps)
def saveBMP(data, filename):
pass
def remove_random_noise(spectrogram, plot=False, outputPngName=None, filter_compensation='log10', pas... |
1747113 | import torch as th
from torch.nn.functional import relu
def intensity_at_t(mu, alpha, sequences_padded, mask, t):
"""Finds the hawkes intensity:
mu + alpha * sum( np.exp(-(t-s)) for s in points if s<=t )
Args:
mu: float
alpha: float
sequences_padded: 2d numpy array
mask: ... |
1747116 | import csv
from datetime import datetime
from decimal import Decimal
from time import sleep
from selenium.common.exceptions import TimeoutException, WebDriverException
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by... |
1747137 | import threading, logging
from typing import Callable
logger = logging.getLogger(__name__)
class LoopingTimer(threading.Thread):
"""
Thread that will continuously run `target(*args, **kwargs)`
every `interval` seconds, until program termination.
"""
def __init__(self, interval: int, target: Callab... |
1747157 | from __future__ import print_function
from __future__ import absolute_import
from ..base import PageGrabber
from ...colors.default_colors import DefaultBodyColors as bc
import re
import logging
try:
import __builtin__ as bi
except BaseException:
import builtins as bi
class FourOneOneGrabber(PageGrabber):
... |
1747159 | from easydict import EasyDict as edict
import torch
config = edict()
config.device = torch.device('cuda')
# model setting
config.model_head = {'hm':2,'reg':2,'wh':2}
config.model_layer = 10
config.down_ratio = 4
config.head_conv = 64
# basic setting
config.mean = [0.485, 0.456, 0.406]
config.std = [0.229, 0.224, 0... |
1747203 | from datetime import datetime, date
from sqlalchemy import Integer, UnicodeText, Float, BigInteger
from sqlalchemy import String, Boolean, Date, DateTime, Unicode, JSON
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.types import TypeEngine, _Binary
MYSQL_LENGTH_TYPES = (String, _Binary)
class Type... |
1747219 | import torch.utils.data
import os
import rasterio
import torch
import numpy as np
import torch.nn.functional as F
import random
from utils.progressbar import ProgressBar
LABEL_FILENAME="y.tif"
def read(file):
with rasterio.open(file) as src:
return src.read(), src.profile
class RandomDataset(torch.utils.... |
1747258 | import functools
import time
import weakref
def timethis(func):
"""Report execution time of function."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, f'took {end-start:3.2f}s')... |
1747292 | from __future__ import unicode_literals
import napalm_yang
import pytest
import json
import os
import sys
import logging
logger = logging.getLogger("napalm-yang")
def config_logging():
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter("%(name)s - %(... |
1747342 | import numpy as np
import torch
import torch.nn as nn
import torchtestcase
import unittest
from survae.transforms.bijections.conditional.autoregressive import *
from survae.nn.layers.autoregressive import SpatialMaskedConv2d, MaskedConv2d
from survae.nn.layers import ElementwiseParams, ElementwiseParams2d
from survae.t... |
1747375 | from typing import Any, Dict, Tuple, Union, Callable, Optional, Sequence
from typing_extensions import Literal
from copy import deepcopy
from types import MappingProxyType
from pathlib import Path
from anndata import AnnData
from cellrank import logging as logg
from cellrank._key import Key
from cellrank.ul._docs imp... |
1747417 | from sympy.core.rules import Transform
from sympy.testing.pytest import raises
def test_Transform():
add1 = Transform(lambda x: x + 1, lambda x: x % 2 == 1)
assert add1[1] == 2
assert (1 in add1) is True
assert add1.get(1) == 2
raises(KeyError, lambda: add1[2])
assert (2 in add1) is False
... |
1747425 | import argparse
import ray
from ray import tune
from ray.rllib.examples.env.stateless_cartpole import StatelessCartPole
from ray.rllib.examples.models.trajectory_view_utilizing_models import \
FrameStackingCartPoleModel, TorchFrameStackingCartPoleModel
from ray.rllib.models.catalog import ModelCatalog
from ray.rll... |
1747454 | from alembic_utils.testbase import run_alembic_command
def test_current(engine) -> None:
"""Test that the alembic current command does not erorr"""
# Runs with no error
output = run_alembic_command(engine, "current", {})
assert output == ""
|
1747540 | import numpy as np
from ...colors import Color
from ...io import MouseEvent, MouseEventType
from ..text_widget import TextWidget, SizeHint, Anchor, Size
from ..scroll_view import ScrollView
from ._legend import _Legend
from ._traces import _Traces, TICK_WIDTH, TICK_HALF
PLOT_SIZES = [SizeHint(x, x) for x in (1.0, 1.2... |
1747550 | import numpy as np
import torch
from torch import nn
from torch.nn import init
from collections import OrderedDict
class SKAttention(nn.Module):
def __init__(self, channel=512,kernels=[1,3,5,7],reduction=16,group=1,L=32):
super().__init__()
self.d=max(L,channel//reduction)
self.convs=nn.... |
1747557 | import cv2
from tracker import KCFTracker
def tracker(cam, frame, bbox):
tracker = KCFTracker(True, True, True) # (hog, fixed_Window, multi_scale)
tracker.init(bbox, frame)
while True:
ok, frame = cam.read()
timer = cv2.getTickCount()
bbox = tracker.update(frame)
bbox ... |
1747596 | import logging
from datetime import datetime, timedelta
import homeassistant.core as ha
from custom_components.irrigation_unlimited.irrigation_unlimited import (
IUCoordinator,
)
_LOGGER = logging.getLogger(__name__)
test_config_dir = "tests/configs/"
NO_CHECK: bool = False
# Shh, quiet now.
def quiet_mode() -... |
1747612 | import gzip
import lzma
import bz2
import io
import builtins
WRITE_MODE = "wt"
class ReusableFile(object):
"""
Class which emulates the builtin file except that calling iter() on it will return separate
iterators on different file handlers (which are automatically closed when iteration stops). This
... |
1747655 | import logging
from typing import Any, Dict, List, Optional, TypedDict, Union
from utility import Utility
log: logging.Logger = logging.getLogger(__name__)
class ElderChallenges(TypedDict):
"""Structure of elder_challenges.csv"""
id: int
ref: str
name: str
desc: str
amount: int
loot: in... |
1747665 | import magma as m
from mantle import Counter
from mantle.util.lfsr import DefineLFSR
from loam.boards.icestick import IceStick
icestick = IceStick()
icestick.Clock.on()
for i in range(8):
icestick.J3[i].output().on()
LFSR = DefineLFSR(8, has_ce=True)
main = icestick.main()
clock = Counter(22)
lfsr = LFSR()
m.... |
1747670 | import copy
import datetime
import unittest
from unittest import mock
from unittest.mock import Mock, MagicMock
from freezegun import freeze_time
from airflow.models import TaskInstance
from airflow.models import Connection
from airflow.settings import Session
from airflow.utils import timezone
from airflow.utils.stat... |
1747679 | import rich_click as click
# Show the positional arguments
click.rich_click.SHOW_ARGUMENTS = True
# Uncomment this line to group the arguments together with the options
# click.rich_click.GROUP_ARGUMENTS_OPTIONS = True
@click.command()
@click.argument("input", type=click.Path(), required=True)
@click.option(
"--... |
1747695 | from torch.utils.data import Dataset, IterableDataset, DataLoader
from itertools import cycle, islice
from . import AuthInfo, Range, Configuration, ZookeeperInstance, AccumuloConnector, Authorizations, Key, AccumuloBase
class AccumuloCluster(AccumuloBase, IterableDataset):
def __init__(self, instance: str , zooke... |
1747697 | import time
from SX127x.LoRa import *
from SX127x.board_config import BOARD
BOARD.setup()
BOARD.reset()
class mylora(LoRa):
def __init__(self, verbose=False):
super(mylora, self).__init__(verbose)
self.set_mode(MODE.SLEEP)
self.set_dio_mapping([0] * 6)
self.var=0
self.coun... |
1747709 | import torch
import torch.nn as nn
class CostVolume(nn.Module):
def __init__(self, max_disp, feature_similarity='correlation'):
"""Construct cost volume based on different
similarity measures
Args:
max_disp: max disparity candidate
feature_similarity: type of simil... |
1747719 | from django import forms
from django_measurement.forms import MeasurementField
from tests.custom_measure_base import DegreePerTime, Temperature, Time
from tests.models import MeasurementTestModel
class MeasurementTestForm(forms.ModelForm):
class Meta:
model = MeasurementTestModel
exclude = []
c... |
1747721 | import numpy as np
import scipy
from scipy.spatial.transform import Rotation as Rot
import cv2
import json
from tqdm import tqdm
DEBUG = False
def get_distance(p4, p6, cam_proj_4, cam_proj_6):
'''
calculate minimum distance with epipolar constraint
Args:
p4: key point on camera 4 -- shape: (3,)
... |
1747725 | from .base import BaseBenchmark # noqa
from .text_classification import TextClassificationBenchmark # noqa
from .token_classification import TokenClassificationBenchmark # noqa
from .dep import DepBenchmark # noqa
from .pos import PosBenchmark # noqa
from .ner import NerBenchmark # noqa
|
1747832 | import pytest
import itertools
from signs import named_chars, build_index
@pytest.fixture
def first_5():
return [(' ', 'SPACE'),
('!', 'EXCLAMATION MARK'),
('"', 'QUOTATION MARK'),
('#', 'NUMBER SIGN'),
('$', 'DOLLAR SIGN')]
def test_first_5_named(... |
1747833 | for f in AllFonts():
for g in f:
l = g.getLayer("background")
l.clear()
f.save() |
1747843 | from typing import List, Set
class Segger(object):
def __init__(self, words: Set[str], max_len: int=5):
super(Segger).__init__()
self.words: Set[str] = words
self.max_len: int = max_len
def cut(self, sent: str)-> List[str]:
index = 0
segments = []
w... |
1747866 | import os
import gdown
def check_dir(dir_name: str) -> bool:
if os.path.isdir(dir_name):
return True
return False
def download_data(dir_name="data") -> None:
if not check_dir(dir_name):
os.mkdir(dir_name)
os.chdir(dir_name)
gdown.download(
"https://drive.google.com/uc?id... |
1747877 | import math
import numpy as np
import visualization.panda.world as wd
import modeling.geometric_model as gm
import modeling.collision_model as cm
import basis.robot_math as rm
if __name__ == '__main__':
base = wd.World(cam_pos=np.array([-.8, .3, .4]),lookat_pos=np.array([0, 0, .1]))
# マグカップの生成
object1 = cm... |
1747879 | import argparse
import os
import cv2
import torch
import torch.nn.parallel
import numpy as np
import math
import valid
import sys
import common.config as config
import common.TBLogger as TBLogger
from common.utils import makedir_if_not_exist, StoreDictKeyPair, save_obj, load_obj
from torch import optim
from torch.u... |
1747927 | from setuptools import setup, find_packages
print(find_packages())
setup(
name='spano',
version='1.0',
long_description=__doc__,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=['flask', 'python-magic', 'Flask-HashFS', 'Flask-IndieAuth'],
)
|
1747953 | import pickle
def Bdelete():
# Opening a file & loading it
F= open("studrec.dat","rb")
stud = pickle.load(F)
F.close()
print(stud)
# Deleting the Roll no. entered by user
rno= int(input("Enter the Roll no. to be deleted: "))
F= open("studrec.dat","wb")
rec= []... |
1748008 | import os
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data.sampler import SubsetRandomSampler
from .generate_train_dataset import get_train_test_set
torch.set_default_tensor_type(torch.FloatTensor)
class Net(nn.Module):
def __init__(self):
super(Net, se... |
1748068 | import base64
MSG_SCRAPE = '\x01'
MSG_PEERCOUNTDELTA = '\x02'
IPC_PATH = 'ipc:///tmp/fairywrenStats'
API_PATH = 'api'
TORRENTS_PATH = '%s/torrents' % API_PATH
TORRENT_FMT = TORRENTS_PATH + '/%.8x.torrent'
TORRENT_INFO_FMT = TORRENTS_PATH + '/%.8x.json'
USERS_PATH = '%s/users' % API_PATH
USER_FMT = USERS_PATH + '/%.8... |
1748122 | from django.test import TestCase
from django.conf import settings
# Create your tests here.
class ProductionTestCase(TestCase):
def test_is_debug_off(self):
""" ensures that the project has DEBUG set to False """
self.assertFalse(settings.DEBUG, "DEBUG is ON, not ready for production !")
... |
1748130 | class Frood:
def __init__(self, age):
self.age = age
print("Frood initialized")
def anniversary(self):
self.age += 1
print("Frood is now {} years old".format(self.age))
f1 = Frood(12)
f2 = Frood(97)
f1.anniversary()
f2.anniversary()
f1.anniversary()
f2.anniversary()
|
1748160 | import json
import os
import random
import string
from pathlib import Path
from eth_typing import ChecksumAddress
from eth_utils import to_checksum_address
PATH_CONFIG = Path("/opt/synapse/config/synapse.yaml")
PATH_CONFIG_TEMPLATE = Path("/opt/synapse/config/synapse.template.yaml")
PATH_MACAROON_KEY = Path("/opt/syna... |
1748169 | import gym
import gym_donkeycar
def factory_creator(sim_path, host, port, sim_track):
def create_simulator_agent():
conf = {"exe_path": sim_path, "port": port, "host": host, "frame_skip": 1}
env = gym.make(sim_track, conf=conf)
return env
return create_simulator_agent
|
1748177 | from pylab import *
def initialize(x0, y0): ###
global x, y, xresult, yresult
x = x0 ###
y = y0 ###
xresult = [x]
yresult = [y]
def observe():
global x, y, xresult, yresult
xresult.append(x)
yresult.append(y)
def update():
global x, y, xresult, yresult
nextx = - 0.5 * x - 0.7 ... |
1748212 | import numpy as np
import pandas as pd
import csv
import seaborn as sns
import sys
import matplotlib.pyplot as plt
from collections import OrderedDict
from argparse import ArgumentParser
import pathlib
import math
import copy
def main():
args = get_args()
sns.set(style='white',)
palette=sns.color_palette('... |
1748235 | import logging, datetime
from pprint import pprint
from diana.utils.guid import GUIDMint
def test_guid_genders():
M = GUIDMint()
expected = {
'ID': 'WHLOKMAGICLQGYKC3ZQLLMFKMOX3ZAP2',
'Name': ['WAGENAAR', 'HERIBERTO', 'L'],
'BirthDate': datetime.date(1999, 10, 8),
'TimeOffset'... |
1748245 | import networkn
class ndexGraphBuilder:
def __init__(self):
self.ndexGraph = networkn.NdexGraph()
self.nodeIdCounter = 0
self.sidTable = {} # external id to nodeIt mapping table
self.edgeIdCounter = 0
def addNamespaces(self, namespaces):
self.ndexGraph.set_namespace(n... |
1748271 | from coworks import Blueprint, entry
class BP(Blueprint):
@entry
def get_test(self, index):
return f"blueprint test {index}"
@entry
def get_extended_test(self, index):
return f"blueprint extended test {index}"
|
1748312 | import numpy as np
import collections
from random import randint
from core.evaluation.labels import PositiveLabel, NegativeLabel, NeutralLabel
from sample import Sample
from extracted_relations import ExtractedRelation
class BagsCollection:
def __init__(self,
relations,
bag_size... |
1748327 | from typing import Any, Set
from boa3.model.type.collection.sequence.sequencetype import SequenceType
from boa3.model.type.itype import IType
class GenericSequenceType(SequenceType):
"""
An class used to represent a generic Python sequence type
"""
def __init__(self, values_type: Set[IType] = None):... |
1748382 | import os
from enum import Enum
from pathlib import Path
from os.path import join, exists
import argparse
import pathlib
import click
import numpy as np
import pandas as pd
import download_data
import dataframe
import plotter
from matplotlib import pyplot as plt
import seaborn as sns
import dataframe
import plotter... |
1748391 | from abc import ABCMeta
from typing import Optional, Union, Tuple
import torch
import torch.nn.functional as F
from torch.distributions import Gumbel
from torch.nn import Sequential
def set_temperature(m: torch.nn.Module, temp: torch.Tensor):
if isinstance(m, MixedModule):
m.gumbel_temperature.copy_(temp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.