id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11476645 | import random
import re
import six
from geodata.address_expansions.gazetteers import *
from geodata.encoding import safe_decode, safe_encode
from geodata.text.tokenize import tokenize_raw, token_types
from geodata.text.utils import non_breaking_dash_regex
LOWER, UPPER, TITLE, MIXED = range(4)
def token_capitalizat... |
11476654 | from sciwing.infer.interface_client_base import BaseInterfaceClient
from typing import Dict, Any
import wasabi
import sciwing.constants as constants
from sciwing.modules.embedders.trainable_word_embedder import TrainableWordEmbedder
from sciwing.modules.embedders.concat_embedders import ConcatEmbedders
from sciwing.dat... |
11476658 | from PIL import Image, ImageDraw, ImageFont
import os
import json
import random
def drawing(types,fromQQ):
# 插件目录 C:\Users\asus\Downloads\Programs\github\fortune\server\server\fortune
base_path = os.path.split(os.path.realpath(__file__))[0]
img_dir = f'{base_path}/data/img/{types}/'
img_path = img_dir ... |
11476671 | import copy
import nose.tools as nt
import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
fX = theano.config.floatX
def test_reference_node_serialization():
tn.check_serialization(tn.ReferenceNode("a"))
tn.check_serialization(tn.ReferenceNode("a", reference="b... |
11476706 | import os
import logging
import types
import numpy as np
from glob import glob
from types import TupleType, StringType
from aeon import timer
logger = logging.getLogger(name='finmag')
class Tablewriter(object):
# It is recommended that the comment symbol should end with a
# space so that there is no danger th... |
11476709 | from scipy.signal import find_peaks
from tssearch.search.search_utils import lockstep_search, elastic_search
def time_series_segmentation(dict_distances, query, sequence, tq=None, ts=None, weight=None):
"""
Time series segmentation locates the time instants between consecutive query repetitions on a more exte... |
11476720 | import torch.nn.functional as F
import torch
import random
import numpy as np
from fastNLP import Const
from fastNLP import CrossEntropyLoss
from fastNLP import AccuracyMetric
from fastNLP import Tester
import os
from fastNLP import logger
def should_mask(name, t=''):
if 'bias' in name:
return False
if ... |
11476826 | import logging
import uuid
from django.utils import timezone
from elasticsearch import Elasticsearch, RequestError
from elasticsearch.client import IlmClient
from zentral.core.exceptions import ImproperlyConfigured
from zentral.contrib.inventory.models import Source
from zentral.contrib.inventory.utils import SourceFil... |
11476897 | from edi_835_parser.elements import Element
organization_types = {
'PE': 'payee',
'PR': 'payer',
}
class OrganizationType(Element):
def parser(self, value: str) -> str:
value = value.strip()
return organization_types.get(value, value)
|
11476912 | from typing import (
List,
Optional,
)
from functools import (
reduce,
)
from ..token import (
Token,
TokenType,
)
from ..node import (
CykNode,
)
from ..peaker import (
Peaker,
)
from .identifiers import (
NoqaIdentifier,
)
def _is(peaker, token_type, index=1):
# type: (Peaker[Tok... |
11476940 | from anoncreds.protocol.types import AttribType, AttribDef
GVT = AttribDef('gvt',
[AttribType('name', encode=True),
AttribType('age', encode=False),
AttribType('height', encode=False),
AttribType('sex', encode=True)])
|
11476955 | import pandas as pd
import pytest
from orion.evaluation.utils import (
from_list_points_labels, from_list_points_timestamps, from_pandas_contextual,
from_pandas_points, from_pandas_points_labels)
def assert_list_tuples(returned, expected_return):
assert len(returned) == len(expected_return)
for ret, ... |
11476997 | n = int(input())
marksheet = [(input(), float(input())) for _ in range(n)]
marks = [mark for name, mark in marksheet]
second_highest = sorted(set(marks))[1]
names = [name for [name, grade] in marksheet if grade == second_highest]
print("\n".join(sorted(names)))
|
11477042 | import uvicore
import inspect
import importlib
from uvicore.support import module
from uvicore.container import Binding
from uvicore.support.dumper import dd, dump
from uvicore.contracts import Ioc as IocInterface
from uvicore.typing import Any, Callable, List, Optional, Type, TypeVar, Dict, Union
T = TypeVar('T')
c... |
11477053 | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import range
from uuid import uuid4
from datetime import datetime
from traildb import TrailDBConstructor, TrailDB
cons = TrailDBConstructor('tiny', ['usern... |
11477069 | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import MetaData
import uuid
# def auto_constraint_name(constraint, table):
# if constraint.name is None or constraint.name == "_unnamed_":
# return "sa_autoname_%s" % str(uuid.uuid4())[0:5]
# else:
# return constrain... |
11477080 | import click
from opnsense_cli.formatters.cli_output import CliOutputFormatter
from opnsense_cli.callbacks.click import \
formatter_from_formatter_name, bool_as_string, available_formats, int_as_string, tuple_to_csv, \
resolve_linked_names_to_uuids
from opnsense_cli.types.click_param_type.int_or_empty import IN... |
11477138 | import pickle as pkl
import matplotlib.pyplot as plt
import seaborn as sns
filename = 'results_all_2021-05-21-11-21-42.pickle'
# change to your pickle name which includes the concatenated dataframe
with open(filename, "rb") as f:
results = pkl.load(f)
df = results["results"]
df_pivot = (
df[["dataset", "cl... |
11477144 | from os import listdir
from os.path import join
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
from torch.utils import data
import torchvision.transforms as transforms
def build_file_paths(base):
img_paths = []
names = []
img_names = sorted(listdir(base))
img_paths = [join(base... |
11477178 | import os
import setuptools
README = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'README.rst')
setuptools.setup(
name='theanets',
version='0.8.0pre',
packages=setuptools.find_packages(),
author='lmjohns3',
author_email='<EMAIL>',
description='Feedforward and recurrent neural nets ... |
11477207 | import numpy as np
import os
import pickle
import pysam
from math import ceil, floor
from arcsv.constants import ALTERED_QNAME_MAX_LEN
from arcsv.helper import path_to_string, block_gap, fetch_seq, GenomeInterval
from arcsv.sv_affected_len import sv_affected_len
from arcsv.sv_classify import classify_paths
from arcsv.... |
11477241 | import pytest
from hooks.po_location_format import main
from hooks.utils import get_current_branch
INPUT_PO_DATA = """
#: foo/bar.py:123 foo/bar.py:200
#: foo/foo.py:123
msgid "Foo"
msgstr "Bar"
#: foo/bar.py:123 foo/bar.py:200
#: foo/foo.py:123
msgid "Bar"
msgstr "Foo"
"""
FILE_PO_DATA = """
#: foo/bar.py
#: foo/... |
11477260 | import datetime
import logging
import boto3
from django.conf import settings
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import AbstractUser
from django.contrib.gis.db import models as gis_models
from django.core.exceptions import FieldError
from django.db import Integrity... |
11477270 | from fightchurn.listings.chap8.listing_8_2_logistic_regression import prepare_data
from fightchurn.listings.chap9.listing_9_1_regression_auc import reload_regression
import numpy
def calc_lift(y_true, y_pred):
if numpy.unique(y_pred).size < 10:
return 1.0
sort_by_pred=[(p,t) for p,t in sorted(zip(y_pr... |
11477281 | import math
# print resourse usage estimates?
estimate_resources = 1
# General Network Parameters
INPUT_SIZE = 28 # dimension of square input image
NUM_KERNELS = 8
KERNEL_SIZE = 7 # square kernel
#NUM_KERNELS = 2
#KERNEL_SIZE = 3 # square kernel
KERNEL_SIZE_SQ = KERNEL_SIZE**2
NEIGHBORHOOD_SIZE = 4
FEATURE_SIZE = ... |
11477332 | import os
import pytest
import subprocess
import tempfile
import configparser
@pytest.mark.parametrize("config_fname", ["./tests/_local_test_config.conf"])
@pytest.mark.parametrize("cleanup", [False, True])
@pytest.mark.parametrize("print_all", [False, True])
@pytest.mark.parametrize("force_pass", [False, True])
@pyt... |
11477336 | import argparse
import numpy as np
import sys
SCALE_OPTIONS = ['log', 'linear']
def check_both_int(a, b):
if a.is_integer() and b.is_integer():
return True
else:
return False
def process_args(args):
""" Prints grid to standard error. """
min_val, max_val, num_points, scale = args.min... |
11477341 | import re
from janome.tokenizer import Tokenizer
class Preprocessor():
def __init__(self):
self.tokenizer = Tokenizer()
self._symbol_replace = re.compile(r"[^ぁ-んァ-ン一-龥ーa-zA-Za-zA-Z0-90-9]")
self._numbers = re.compile(r"[0-90-9一二三四五六七八九十百千万億兆]")
def tokenize(self, text, join=False):
... |
11477357 | from decimal import Decimal
from django.db.models import Count, Sum
from django.conf import settings
from rest_framework import viewsets, mixins, decorators
from rest_framework.response import Response
from rest_framework.views import APIView, status
from rest_framework.permissions import IsAuthenticated, IsAdminUser
f... |
11477363 | import numpy as np
from scipy.integrate import quad
from scipy.special import gamma
class Park(object):
"""Class for fatigue life estimation using frequency domain
method by Tovo and Benasciutti[1, 2].
References
----------
[1] <NAME>, <NAME> and <NAME>. A new fatigue prediction model for m... |
11477391 | from tempfile import mkstemp
import numpy as np
from numpy.testing import assert_array_equal
from nose.tools import assert_less
from sklearn.datasets import load_iris
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
from pystr... |
11477392 | from mpas_analysis.shared.io.namelist_streams_interface import NameList, \
StreamsFile
from mpas_analysis.shared.io.utility import paths, decode_strings
from mpas_analysis.shared.io.write_netcdf import write_netcdf
from mpas_analysis.shared.io.mpas_reader import open_mpas_dataset
|
11477395 | from django.apps import AppConfig
class ExampleBackendAppConfig(AppConfig):
name = 'example_backend_app'
|
11477398 | import sys
import torch
import random
import numpy as np
import json
from torch.nn.utils import rnn
import progressbar
import random
import json
from torch import nn
import os
def map_bool(bool_status):
if bool_status == 'True':
return True
elif bool_status == 'False':
return False
else:
... |
11477411 | import keras.backend as K
from keras.metrics import get
from keras import Model
from keras.layers import Dense, Dropout, Input, Flatten, Add, BatchNormalization, Concatenate
from keras import regularizers, initializers, constraints, activations
import numpy as np
class FFNN:
def __init__(self,
la... |
11477449 | import os
import logging
import torch
from torch.utils.data import TensorDataset
from src.pequod.data.utils_squad import (read_squad_examples,
convert_examples_to_features)
logger = logging.getLogger(__name__)
def load_and_cache_examples(args, split, lang, tokenizer, key="", evaluate=False):
cache_filename = o... |
11477468 | import torch.nn as nn
from .configuration_rcan import RcanConfig
from ...modeling_utils import (
default_conv,
BamBlock,
MeanShift,
Upsampler,
PreTrainedModel
)
class CALayer(nn.Module):
def __init__(self, channel, reduction=16):
super(CALayer, self).__init__()
# global averag... |
11477489 | import tensorflow as tf
import numpy as np
from scipy.interpolate import interp1d
def weight_variable(shape, name=None):
return tf.get_variable(name=name, shape=shape, dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.001))
def bias_variable(shape, name=None):
return tf.get_variable(... |
11477491 | import math
class Solution:
def maxScore(self, s: str) -> int:
count0 = count1 = 0
maxDiff = -math.inf
for i, c in enumerate(s):
if c == '0':
count0 += 1
else:
count1 += 1
if i != len(s) - 1:
maxDiff ... |
11477498 | import numpy as np
# grid
spacing = 0.01
length = 1.5
x = np.arange(0, length, spacing)
# velocity
v = 1.0
# time
start = 0.0
end = 1.0
step = 0.01
# initial gauss profile
loc = 0.3
scale = 0.1
u = np.exp(-1 / scale ** 2 * (x - loc) ** 2)
u0 = u.copy()
# time loop - Lax method
factor = (v * step) / (2 * spacing)
... |
11477515 | from vizh.ir import *
import tests.backend_test
class HelloPutstr(tests.backend_test.BackendTest):
def __init__(self):
super().__init__("putstr")
def get_function(self):
return Function(FunctionSignature("main", 1, False), self.to_instructions(
[InstructionType.INC]*72 +
... |
11477523 | import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import button
from esphome.components.ota import OTAComponent
from esphome.const import (
CONF_ID,
CONF_OTA,
DEVICE_CLASS_RESTART,
ENTITY_CATEGORY_CONFIG,
ICON_RESTART_ALERT,
)
DEPENDENCIES = ["ota"]
safe_m... |
11477536 | from sys import platform
import argparse
import os
from dotaservice.dotaservice import main
from dotaservice.dotaservice import verify_game_path
def get_default_game_path():
game_path = None
if platform == "linux" or platform == "linux2":
game_path = os.path.expanduser("~/Steam/steamapps/common/dota ... |
11477555 | class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
n = len(matrix)
lo = matrix[0][0]
hi = matrix[n - 1][n - 1]
def countNotGreater(target: int) -> int:
i, j = 0, n - 1
cnt = 0
while i < n and j >= 0:
if ... |
11477599 | import argparse
import numpy as np
import pandas as pd
import time
import random
import os
import torch
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch import nn, optim, autograd
from torch.autograd import Variable
from torchvision.utils import save_i... |
11477609 | import uuid
from ichnaea.models.config import ExportConfig
class TestExportConfig(object):
def test_fields(self, session):
name = uuid.uuid4().hex
skip_keys = [<KEY>().hex for i in range(3)]
skip_sources = ["query", "fused"]
session.add(
ExportConfig(
n... |
11477679 | from renormalizer.mps import Mpo
from renormalizer.utils import Quantity
from renormalizer.model.op import Op
from renormalizer.model import HolsteinModel, Model
import numpy as np
def e_ph_static_correlation(model: HolsteinModel, imol:int =0, jph:int =0,
periodic:bool =False, name:str="S"... |
11477692 | from paraview.simple import *
from paraview.vtk.util.misc import vtkGetTempDir
from os.path import join
import shutil
Sphere()
UpdatePipeline()
e = Elevation()
UpdatePipeline()
dirname = join(vtkGetTempDir(), "savedatawitharrayselection")
shutil.rmtree(dirname, ignore_errors=True)
filename = join(dirname, "data.pvd... |
11477719 | import sys
from string import ascii_uppercase, ascii_lowercase, digits
class MaxLengthException(Exception):
pass
class WasNotFoundException(Exception):
pass
class Pattern:
MAX_LENGTH = 20280
@staticmethod
def gen(length):
"""
Generate a pattern of a given length up to a maximu... |
11477722 | import unittest
from minos.common import (
Config,
)
from minos.networks import (
HttpAdapter,
HttpRouter,
MinosRedefinedEnrouteDecoratorException,
)
from tests.test_networks.test_routers import (
_Router,
)
from tests.utils import (
CONFIG_FILE_PATH,
)
class TestHttpAdapter(unittest.TestCase... |
11477762 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
requirements = [
'lmdb~=0.98',
'pycapnp~=0.6.4',
]
setuptools.setup(
name='osmx',
version='0.0.4',
author="<NAME>",
author_email='<EMAIL>',
description='Read OSM Express (.osmx) database files.',
lic... |
11477814 | import datetime
import unittest
from peerplays import PeerPlays
from peerplays.utils import parse_time
from peerplays.exceptions import ObjectNotInProposalBuffer
from peerplaysbase.operationids import getOperationNameForId
from peerplays.instance import set_shared_peerplays_instance
wif = "5KQwrPbwdL6PhXujxW37FSSQZ1Ji... |
11477863 | import config
import json
from multiprocessing import Process
import os
from pprint import pprint
import re
import requests
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from subprocess import call
from urllib import parse
from webcocktail.crawler.items import ResponseI... |
11477888 | import chainer
import chainer.functions as F
import chainer.links as L
from tgan2.models.resblocks import DisBlock
from tgan2.models.resblocks import OptimizedDisBlock
class ResNetVideoDiscriminator(chainer.Chain):
def __init__(self, in_channels, mid_ch=64, n_classes=0, activation='relu'):
super(ResNetV... |
11477965 | from trafaret.utils import fold, split, unfold
class TestUtils:
def test_split(self):
data = 'leads[delete][0][id]'
split_data = split(data, ('[]', '[', ']'))
assert split_data == ['leads', 'delete', '0', 'id']
def test_fold(self):
data = {'leads[delete][0][id]': '42', 'accoun... |
11477966 | from six import StringIO
import random
import string
import pytest
import numpy as np
from eight_mile.utils import read_label_first_data, write_label_first_data
def random_str(len_=None, min_=5, max_=21):
if len_ is None:
len_ = np.random.randint(min_, max_)
choices = list(string.ascii_letters + stri... |
11477972 | from agent import BaseAgent, Observer
from malmo_rl.agents.random_agent import Random
from malmo_rl.agents.qlearner import QLearner
from malmo_rl.agents.ddpglearner import DDPGLearner
class AbstractAgent(BaseAgent):
def __init__(self, name, env, agent_type, **kwargs):
if agent_type == 'random':
... |
11477988 | import imp
import logging
import os
import re
from datetime import datetime
logger = logging.getLogger(__name__)
class MigrationFile(object):
PATTERN = '^(?P<id>[0-9]+)_[a-z0-9_]+\.py$'
def __init__(self, id, filename):
self.id = int(id)
self.filename = filename
def __str__(self):
... |
11478031 | from airflow import DAG
import datetime
from airflow.hooks.S3_hook import S3Hook
from elasticsearch import Elasticsearch
import json
import gzip
import io
import logging
import base64
from elasticsearch.helpers import bulk
from airflow.operators.python_operator import PythonOperator
from airflow.models import Variable
... |
11478063 | import sys
import json
def init(config_filename = 'config.json'):
infile = open(config_filename, "rt")
#json python module doesn't honor comment lines.
#so we are going to strip them out.
json_lines = []
for line in infile:
comment = line.find('//')
if comment == -1:
... |
11478076 | import FWCore.ParameterSet.Config as cms
hcaltbfilter_beam = cms.EDFilter("HcalTBTriggerFilter",
AllowLED = cms.bool(False),
AllowPedestalOutSpill = cms.bool(False),
AllowLaser = cms.bool(False),
AllowPedestal = cms.bool(False),
AllowBeam = cms.bool(True),
AllowPedestalInSpill = cms.bool(False)... |
11478083 | from collections import defaultdict
from typing import TYPE_CHECKING, DefaultDict, Dict, List, Optional
from beagle.nodes.node import Node
from beagle.edges import FileOf, CopiedTo
# mypy type hinting
if TYPE_CHECKING:
from beagle.nodes import Process # noqa: F401
class File(Node):
__name__ = "File"
__... |
11478100 | import os
import sys
sys.path.insert(0, './scripts/')
import numpy as np
import tensorflow as tf
import random
from glob import glob
from utils import *
from models import *
import argparse
parser = argparse.ArgumentParser(description='Auto Encoder for 3D object reconstruction from images')
parser.add_argument('-o... |
11478104 | import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from davg.lanefinding.ImgMgr import ImgMgr
from davg.lanefinding.BirdsEyeTransform import BirdsEyeTransform
from davg.lanefinding.Thresholds import Thresholds
from davg.lanefinding.DiagnosticScreen import Diagnos... |
11478133 | from uuid import uuid4
from flask import Blueprint, Response, abort, request
from flask_restful import Api
from flasgger import swag_from
from app.docs.v2.admin.account.account_management import *
from app.models.account import AdminModel, StudentModel, SignupWaitingModel
from app.views.v2 import BaseResource, auth_r... |
11478167 | import sys
# import from official repo
sys.path.append('tensorflow_models')
from official.nlp.bert.tf1_checkpoint_converter_lib import convert, BERT_V2_NAME_REPLACEMENTS, BERT_NAME_REPLACEMENTS, BERT_PERMUTATIONS, BERT_V2_PERMUTATIONS
from utils.misc import ArgParseDefault
def main(args):
convert(args.input_chec... |
11478172 | import typing
import torch
import torch.nn as nn
from pyraug.models.nn import *
class Encoder_Conv(BaseEncoder):
def __init__(self, args):
BaseEncoder.__init__(self)
self.input_dim = args.input_dim
self.latent_dim = args.latent_dim
self.n_channels = 1
self.layers = nn.Se... |
11478189 | import dash
import dash_html_components as html
app = dash.Dash(meta_tags=[
# A description of the app, used by e.g.
# search engines when displaying search results.
{
'name': 'description',
'content': 'My description'
},
# A tag that tells Internet Explorer (IE)
# to use the la... |
11478205 | from django.conf.urls import include
from django.urls import path
from django.contrib import admin
urlpatterns = (
path('', include('landing.urls', namespace='landing')),
path('', include('registration.urls', namespace='registration')),
path('slack/', include('slack.urls', namespace='slack')),
path('jo... |
11478212 | import math
from typing import Optional
import numpy as np
from paramak import ExtrudeStraightShape
class InnerTfCoilsFlat(ExtrudeStraightShape):
"""A tf coil volume with straight inner and outer profiles and
constant gaps between each coil. Note: the inner / outer surface is not
equal distance to the c... |
11478245 | def init():
import os
if 'DJANGO_SETTINGS_MODULE' in os.environ:
try:
import django
django.setup()
except AttributeError:
pass
|
11478315 | from django.shortcuts import render
def test(request):
return render(request, "context_processors/test.html")
|
11478324 | import functools
import importlib
import inspect
import os.path
import time
from datetime import datetime
from datetime import timezone
from urllib.parse import urlparse
import pytest
def make_url_base(feed_url):
# FIXME: this is very brittle (broken query string and fragment support),
# and also very far aw... |
11478348 | import math
from dependent_injection import parameter_dependent
def test_good_dependency():
assert parameter_dependent(25, math.sqrt) == 5
def test_negative():
def bad_dependency(number):
raise Exception('Function called')
assert parameter_dependent(-1, bad_dependency) == 0
def test_zero():
... |
11478363 | import time
import numpy as np
import tensordata.gfile as gfile
import tensordata.utils.request as rq
from tensordata.utils.compress import un_gz, un_tar
from tensordata.utils._utils import assert_dirs
from linora.image import save_image, array_to_image
__all__ = ['stl10']
def stl10(root):
"""Stl10 dataset from ... |
11478379 | from .. import networks
const = lambda x: x
def get_network(name):
if name in NETWORKS:
return NETWORKS[name]
else:
return NETWORKS["elementsregtest"]
NETWORKS = {
"liquidv1": {
"name": "Liquid",
"wif": b'\x80',
"p2pkh": b'\x00',
"p2sh": b'\x27',
... |
11478465 | import os
from kaa import config
class TestHistory:
def test_history(self):
storage = config.KaaHistoryStorage('')
try:
hist = storage.get_history('hist1')
hist.add('1', 1)
hist.add('2', 2)
hist.add('1', 1)
assert hist.get() == [('1', 1... |
11478522 | for row in range(7):
for col in range(4):
if row==0 or row in {1,2} and col<1 or row in{4,5} and col>2 or row in {3,6} and col<3:
print('*',end=' ')
else:
print(' ',end=' ')
print()
### Method-5
for i in range(6):
for j in range(5):
if i==0 or i==2 and j<4 or j=... |
11478527 | from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
(r'^request_attrs/$', views.request_processor),
)
|
11478539 | import os
import sys
import hashlib
from trackhub import helpers
def test_example_data_md5s():
data_dir = helpers.data_dir()
data = [i.strip().split() for i in '''
3735b696b3a416a59f8755eaf5664e5a sine-hg38-0.bedgraph.bw
73ad8ba3590d0895810d069599b0e443 sine-hg38-1.bedgraph.bw
85478d1ecc5906405c... |
11478552 | from chainermn.iterators.multi_node_iterator import create_multi_node_iterator # NOQA
from chainermn.iterators.synchronized_iterator import create_synchronized_iterator # NOQA
|
11478578 | import attr
@attr.s
class DatasetVersionTagSummary(object):
"""
Dataset version tag summary class
"""
name = attr.ib(type=str, default=None)
@attr.s
class DatasetVersion(object):
"""
Dataset version class
"""
version = attr.ib(type=str, default=None)
message = attr.ib(type=str, d... |
11478581 | import click
import mock
import pytest
from click.testing import CliRunner
from sigopt.cli import cli
class TestRunCli(object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collect... |
11478642 | import imageio
import json
import numpy as np
import os
import warnings
from torch.utils import data
from onconet.datasets.factory import RegisterDataset
MP4_LOADING_ERR = "Error loading {}.\n{}"
@RegisterDataset("kinetics")
class Kinetics(data.Dataset):
"""A pytorch Dataset for the Kinetics dataset."""
def ... |
11478685 | from imap_tools import MailBox
# get size of message and attachments
with MailBox('imap.my.ru').login('acc', 'pwd', 'INBOX') as mailbox:
for msg in mailbox.fetch():
print(msg.date_str, msg.subject)
print('-- RFC822.SIZE message size', msg.size_rfc822)
print('-- bytes size', msg.size) # wil... |
11478693 | import pytest as pytest
from plenum.common.util import get_utc_epoch
from plenum.server.request_handlers.txn_author_agreement_disable_handler import TxnAuthorAgreementDisableHandler
from plenum.test.req_handler.conftest import taa_request
from storage.kv_in_memory import KeyValueStorageInMemory
from common.serializer... |
11478805 | import xmlrpclib
class NoteAPI:
def __init__(self, srv, db, user, pwd):
common = xmlrpclib.ServerProxy('%s/xmlrpc/2/common' % (srv))
self.api = xmlrpclib.ServerProxy('%s/xmlrpc/2/object' % (srv))
self.uid = common.authenticate(db, user, pwd, {})
self.pwd = <PASSWORD>
self.... |
11478817 | import FWCore.ParameterSet.Config as cms
import copy
from PhysicsTools.NanoAOD.nanoDQM_cfi import nanoDQM
from PhysicsTools.NanoAOD.nanoDQM_tools_cff import *
from PhysicsTools.NanoAOD.nano_eras_cff import *
## Modify plots accordingly to era
_vplots80X = nanoDQM.vplots.clone()
# Tau plots
_tauPlots80X = cms.VPSet()
... |
11478895 | def remove(text, what):
result = []
for a in text:
try:
if what[a] >= 1:
what[a] -= 1
continue
except KeyError:
pass
result.append(a)
return ''.join(result)
|
11478901 | from kts.modelling.mixins import RegressorMixin, NormalizeFillNAMixin
from kts.models.common import XGBMixin, LGBMMixin, CatBoostMixin, all_estimators, BLACKLISTED_PARAMS
__all__ = []
class XGBRegressor(RegressorMixin, XGBMixin): pass
class LGBMRegressor(RegressorMixin, LGBMMixin): pass
class CatBoostRegressor(Regre... |
11478929 | import heapq
class MedianFinder(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.leftHeap = []
self.rightHeap = []
def addNum(self, num):
"""
:type num: int
:rtype: void
"""
if len(self.leftH... |
11478973 | import argparse
import collections
import csv
import itertools
import json
import pathlib
from typing import Dict, List, NamedTuple
import matplotlib.pyplot as plt # type: ignore
def main() -> None:
args = parse_args()
files = [
"kite-go/navigation/recommend/recommend.go",
"kite-go/client/int... |
11478984 | import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3, 4], dtype=np.uint8)
y = x**2 + 1
plt.plot(x, y)
y = x + 1
plt.plot(x, y)
plt.title('Graph')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.grid('on')
plt.savefig('test1.png', dpi=300, bbox_inches='tight')
plt.show()
|
11478990 | from qm.QuantumMachinesManager import QuantumMachinesManager
from qm.qua import *
from configuration import config
from qm import LoopbackInterface
from qm import SimulationConfig
from random import random
import matplotlib.pyplot as plt
import numpy as np
from numpy import pi
from scipy import signal
nSamp... |
11479000 | from paymentwall.base import Paymentwall
from paymentwall.product import Product
from paymentwall.widget import Widget
from paymentwall.pingback import Pingback
|
11479012 | from typing import List, Optional
from spacy.language import Language
from spacy.tokens import Doc, Span
from edsnlp.matchers.phrase import EDSPhraseMatcher
from edsnlp.matchers.regex import RegexMatcher
from edsnlp.matchers.utils import Patterns
from edsnlp.pipelines.base import BaseComponent
from edsnlp.utils.filte... |
11479029 | class IsBest(object):
def __init__(self):
"""
This class check if a given value is the best so far
"""
self.val = None
def is_best(self, val) -> bool:
"""
This function returns the status of the current value and update the best value.
:param val: The cur... |
11479032 | from typing import Tuple, List
import torch
import torch.nn as nn
import torch.nn.functional as F
from .pytorch_modules import SharedMLP
from .pu_utils import square_distance, index_points, farthest_point_sample, \
QueryAndGroup, GroupAll
class _PointnetSAModuleBase(nn.Module):
def __init__(self):
... |
11479034 | from init_helpers import *
from image_helpers import *
from pointcloud_helpers import *
from msg_helpers import *
from threading_helpers import *
from geometry_helpers import *
from rviz_helpers import *
from cv_debug import *
from bag_crawler import *
from plotter import *
|
11479040 | import urllib2
import json
import os
import os.path
import datetime
import time
from os.path import expanduser
def getName(urlname):
i = urlname.find("_EN")
i -= 1
s1 = ""
while (urlname[i] != '/') :
s1 += urlname[i]
i -= 1
s1 = s1[::-1] + '.jpg'
return s1
market = "en-US"
resolution = "1920x1080"
wallpaper... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.