id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9891900 | from ..mapper import PropertyMapper, ApiInterfaceBase
from ..mapper.types import Timestamp, AnyType
__all__ = ['Counts', 'CountsInterface']
class CountsInterface(ApiInterfaceBase):
relationships: AnyType
requests: AnyType
photos_of_you: AnyType
usertags: AnyType
comments: AnyType
likes: AnyTy... |
9891925 | from torchpack.mtpack.utils.config import Config, configs
configs.train.compression.warmup_epochs = 5
configs.train.compression.warmup_coeff = [1, 1, 1, 1, 1]
|
9891942 | import unittest
import ircstates, irctokens
class CapTestLS(unittest.TestCase):
def test_one_line(self):
server = ircstates.Server("test")
self.assertFalse(server.has_cap)
self.assertEqual(server.available_caps, {})
server.parse_tokens(irctokens.tokenise("CAP * LS :a b"))
se... |
9891975 | import click
from graviteeio_cli.commands.apim.pages.fetch import fetch
from graviteeio_cli.commands.apim.pages.update import update_content
from graviteeio_cli.commands.apim.pages.get import get
from graviteeio_cli.http_client.gio_resources import APIM_Client
@click.group()
@click.pass_context
def pages(ctx):
""... |
9892041 | import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn.functional as F
import os
import torch
import numpy as np
def normalize_transform():
return transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
def trai... |
9892051 | from django import forms
from django.db.models import Q
from django.utils import timezone
from django.conf import settings
from django.forms import widgets
from django.forms.utils import to_current_timezone
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.forms import modelforms... |
9892061 | from distutils.core import setup, Extension
ion_hash_module = Extension('ion_hash',
sources = ['ionmodule.c',
'ion.c',
'sha3/blake.c',
'sha3/bmw.c',
... |
9892065 | import torch
from torch import nn
import torch.nn.functional as F
import math
import numpy as np
class BConv2d(nn.Conv2d):
def __init__(self, *args, binary=False, **kwargs):
super().__init__(*args, **kwargs)
self.binary = binary
self.alpha = nn.Parameter(torch.ones(1, self.out_channels, ... |
9892067 | class MetricEmitter:
""" Push load test metrics into CloudWatch """
def __init__(self, metric: dict):
from libs import cloudwatch as cw
try:
self.name = metric["name"]
self.stage = metric["stage"]
self.lambda_name = metric["lambda_name"]
self.app ... |
9892079 | def get_bit(z, i):
"""
gets the i'th bit of the integer z (0 labels least significant bit)
"""
return (z >> i) & 0x1
|
9892130 | from os.path import splitext, dirname, basename, isfile
from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from package.context_processors import used_packages_list
register = template.Library()
class ParticipantURLNode(template.Node):
def __init__(self, r... |
9892132 | import torch
import torch.nn as nn
from torch.autograd import Variable
class edge_loss(nn.Module):
def __init__(self):
super(edge_loss, self).__init__()
self.criterion = nn.BCELoss(reduction='sum')
def forward(self, all_scores, labels, masks, num_classes):
total_loss = 0
masks ... |
9892145 | import socket
import sys
import time
import os
# Assigning the environment variables
# Time period (in sec) between retries for DB init check
i_w_d = os.environ['INIT_WAIT_DELAY']
# Number of retries for DB init check
i_r_c = os.environ['INIT_RETRY_COUNT']
# Time period (in sec) between liveness checks
l_p_s = os.envi... |
9892180 | import struct
import db
from eoslib import N
import eoslib
_code = N('eosio.token')
#_code = N('mytoken')
def to_symbol_name(s):
n = int.from_bytes(s, 'little')
return n>>8
class Asset(object):
def __init__(self, amount=0, symbol=None):
self.amount = amount
self.symbol = symbol
def ... |
9892219 | from dps.hyper import run_experiment
from silot.run import basic_config, alg_configs, env_configs
distributions = None
late_config = dict(max_steps=250000)
long_wall_time = "60hours"
readme = "Running SQAIR experiment with conv net on hard_shapes."
pmem = 6000
project = "rpp-bengioy"
n_gpus = 2
gpu_set = ",".join(s... |
9892275 | import argparse
import sys
from blingfire import *
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--model", default="./bert_base_tok.bin", help="bin file with compiled tokenization model")
parser.add_argument("-s", "--no-output", default=False, help="No output, False by default")
parser.add_argument("-n... |
9892285 | from django.db import models
from open_humans.models import OpenHumansMember
from datetime import timedelta
import arrow
import json
class SharedNotebook(models.Model):
"""
Store OAuth data for a data source.
This is a one to one relationship with a OpenHumansMember model
You can find the OpenHumansMe... |
9892292 | import asyncio
import random
import string
from windyquery import DB
loop = asyncio.get_event_loop()
def test_raw_select(db: DB):
async def raw_select():
return await db.raw('SELECT * FROM cards WHERE board_id = $1', 5)
rows = loop.run_until_complete(raw_select())
assert rows[0]['id'] == 7
def... |
9892293 | import asyncio
import aiohttp
import pynws
PHILLY = (39.95, -75.16)
USERID = "<EMAIL>"
async def example():
async with aiohttp.ClientSession() as session:
nws = pynws.SimpleNWS(*PHILLY, USERID, session)
await nws.set_station()
await nws.update_observation()
await nws.update_fore... |
9892311 | import collections
import ctypes
from . import core as DbgEng
from . import exception
from .dbgengstructs import DebugValue
class Registers(collections.Sequence, collections.Mapping):
def __init__(self, DebugRegistersObj):
self.__dict__['_reg'] = DebugRegistersObj
def _get_register_idx(self, name):
... |
9892316 | import re
class BaseTokenizer(object):
def __init__(self, do_lower_case=False, preserved_pattern=None):
self.do_lower_case = do_lower_case
self.preserved_pattern = preserved_pattern
def tokenize_words(self, text):
raise NotImplementedError
def tokenize(self, text):
if sel... |
9892350 | import os
baseLoc = os.path.dirname(os.path.realpath(__file__)) + '/'
from gimpfu import *
import sys
sys.path.extend([baseLoc + 'gimpenv/lib/python2.7', baseLoc + 'gimpenv/lib/python2.7/site-packages',
baseLoc + 'gimpenv/lib/python2.7/site-packages/setuptools', baseLoc + 'PD-Denoising-pytorch'])
... |
9892389 | from enum import IntEnum
class VendorSpecificEvents(IntEnum):
HCI_EXTENSION_SET_RX_GAIN = 0X0400
HCI_EXTENSION_SET_TX_POWER = 0X0401
HCI_EXTENSION_ONE_PACKET_PER_EVENT = 0X0402
HCI_EXTENSION_CLOCK_DIVIDE_ON_HALT = 0X0403
HCI_EXTENSION_DECLARE_NV_USAGE = 0X0404
HCI_EXTENSION_DECRYPT = 0X0405
... |
9892390 | import time
import os
from time import gmtime, strftime
from datetime import datetime
import torch
from torch import nn
from torch.autograd import Variable
import torch.utils.data
from torchfoldext import FoldExt
import util
from dynamicplot import DynamicPlot
from grassdata import GRASSDataset
from grassmodel import ... |
9892396 | from oncall.constants import EMAIL_SUPPORT, SMS_SUPPORT, CALL_SUPPORT
import logging
logger = logging.getLogger('dummy_messenger')
class dummy(object):
supports = frozenset([EMAIL_SUPPORT, SMS_SUPPORT, CALL_SUPPORT])
def __init__(self, config):
pass
def send(self, message):
logger.info(... |
9892398 | import random
import time
from datetime import timedelta
import pytest
from decimal import Decimal
from django.conf import settings
from django.utils.timezone import now
from django.utils.translation import gettext as _
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditi... |
9892413 | import unittest
from flask import request
from webargs import flaskparser
from tests import factories
from tests.common import ApiBaseTest
from webservices import args
from webservices import rest
from webservices import sorting
from webservices.resources import candidate_aggregates
from webservices.resources import... |
9892415 | import grpc
from bettermq_pb2 import *
from bettermq_pb2_grpc import *
host = '127.0.0.1:8404'
data = open('/bin/ls', 'rb').read()
with grpc.insecure_channel(host) as channel:
client = PriorityQueueStub(channel)
for i in range(1,100001):
req = EnqueueRequest(
topic = "root",
m... |
9892422 | import os
import re
from typing import Optional, List, Generator, Union
ASM_LINE_RE = re.compile(
r'^\s*([0-9A-Fa-f]+):\s*[0-9A-Fa-f]+\s+(\S+)\s*(?:([^,# ]+(?:,\s*[^,# ]+)*)\s*)?(?:<([^>#]+)>\s*)?(?:#(.*))?$')
LABEL_RE = re.compile(r'^([0-9A-Fa-f]{8}) <([^>#]+)>:$')
RELOC_RE = re.compile(r'^\s*[0-9A-Fa-f]+: R_RISC... |
9892445 | class Solution:
def expressiveWords(self, S, words):
if not S: return 0
guide, i, j, res = [], 0, 0, 0
while i < len(S):
while j + 1 <len(S) and S[j + 1] == S[j]: j += 1
guide.append((S[i], j - i + 1))
i = j = j + 1
for word in words:
i... |
9892471 | import socket, os, time
import cv2, numpy
banner ="""
( * ) ( (
)\ ` ) /( ( )\ )\
(((_) ( ( ( )(_)) )( ( ((_) ((_)
)\___ )\ )\ ) (_(_()) (()\ )\ _ ... |
9892478 | from __future__ import division
def print_info(router_obj):
print('Details for router at %s:%d' % (router_obj.host, router_obj.port))
print('')
router_info = router_obj.get_router_info()
print('Router %s %s running on firmware %s' % (router_obj.__class__.__name__, router_info.hardware_version, router_... |
9892513 | from sklearn.cross_validation import train_test_split
RANDOM_STATE = 42 # For reproducibility
def split_validation_set(train, target, test_size):
X_train, X_test, y_train, y_test = train_test_split(
train, target, test_size=test_size, random_state=RANDOM_STATE)
return X_train, X_test, y_train, y_te... |
9892527 | from collections import OrderedDict
import os
from django.utils.safestring import mark_safe
import environ
env = environ.Env()
if os.path.exists("/.env"):
env.read_env("/.env")
BASE_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))
SECRET_KEY = env("SECRET_KEY")
DEBUG = env.bool("DEBUG", de... |
9892553 | import time
import tensorflow as tf
from six.moves import cPickle as pickle
import numpy as np
import matplotlib.pyplot as plt
import skimage.transform as skt
import skimage.io as io
from skimage import exposure, img_as_float, img_as_uint
import os
"""
References and code snippets from:
Tensorflow manual: https://www.... |
9892567 | import os
import os.path as osp
import argparse
import h5py
parser = argparse.ArgumentParser(description='Clean datasets for GLO.')
parser.add_argument('--datasets', metavar='N', type=str, nargs='+', choices=['MNIST', 'SVHN', 'CIFAR10'])
def clean(dir):
file_path = osp.join(dir, 'data.hdf5')
if not osp.exist... |
9892576 | from django.conf.urls import url
from . import views
app_name = 'admin'
urlpatterns = [
url(r'^$', views.BrandList.as_view(), name='list'),
url(r'^create/$', views.BrandCreate.as_view(), name='create'),
url(r'^(?P<brand_id>[0-9]+)/$', views.BrandDetail.as_view(), name='detail'),
]
|
9892630 | from genix.ui_main import UIMain
from genix import colours
from genix.components.ui_component import UIComponent
from genix.containers.ui_container import UIContainer
from genix.containers.ui_select_box import UISelectBox
from genix.constraints.center_x import CenterX
from genix.constraints.center_y import Center... |
9892638 | import logging
import requests
from storyweb.core import app
log = logging.getLogger(__name__)
def extract_calais(text):
calais_key = app.config.get('CALAIS_KEY')
if calais_key is None:
log.warning('No CALAIS_KEY is set, skipping entity extraction')
return
if text is None or len(text.str... |
9892662 | import eigen
import math
import mc_control
import mc_rbdyn
import mc_rtc
import mc_solver
import mc_tasks
import sva
APPROACH = 0
HANDLE = 1
OPEN = 2
class MyFirstController(mc_control.MCPythonController):
def __init__(self, rm, dt):
self.qpsolver.addConstraintSet(self.dynamicsConstraint)
self.qps... |
9892688 | import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.patches import Polygon
from davg.lanefinding.ImgMgr import ImgMgr
from davg.lanefinding.BirdsEyeTransform import BirdsEyeTransform
from davg.lanefinding.Thresholds import Thresholds
img_mgr = Img... |
9892728 | from PySide import QtCore, QtGui
from colors import Colors
from demoitem import DemoItem
from demoitemanimation import DemoItemAnimation
from demotextitem import DemoTextItem
from scanitem import ScanItem
class ButtonBackground(DemoItem):
def __init__(self, type, highlighted, pressed, logicalSize, scene, parent)... |
9892744 | import torch
from .. import log
from .walkers import Walkers
class SamplerBase:
def __init__(self, nwalkers, nstep, step_size,
ntherm, ndecor, nelec, ndim, init,
cuda):
"""Base class for the sampler
Args:
nwalkers (int): number of walkers
... |
9892774 | import numpy as np
import pandas as pd
from pandas.util.testing import assert_frame_equal
import pytest
from scipy.spatial.distance import euclidean
from sklearn.preprocessing import MaxAbsScaler
from api.client.samples.analogous_years.lib import distance_matrix
# TODO: test_dtw_dist_matrix
def create_test_data():
... |
9892799 | from ..Empty.BaseEmpty import BaseEmpty
class Singer(BaseEmpty):
def __init__(self, _dic=None):
if _dic is None:
_dic = {}
self.id = _dic.get("id","")
self.name = _dic.get("name","")
self.pics: list[str] = _dic.get("pics",[])
|
9892808 | from typing import Iterable
from functools import partial, lru_cache, update_wrapper
class method_decorator_meta(type):
def __instancecheck__(self, method):
""" Metaclass magic enables isinstance() checks even for decorators wrapped with other decorators """
# Recursion stopper
if method i... |
9892826 | from sequence import *
class HighScoreCategory:
game_data_key = None
"""Key to this high score category's data within :attr:`game.GameController.game_data`."""
scores = None
"""List of :class:`HighScore` objects for this category. Populated by :meth:`load_from_game`."""
score_suffix_singular = ''
"""Singular... |
9892856 | from typing import Sequence
import tensorflow as tf
class GraphNet(tf.keras.layers.Layer):
def __init__(
self,
encoder: tf.keras.layers.Layer,
cores: Sequence[tf.keras.layers.Layer],
decoder: tf.keras.layers.Layer,
name: str = 'graph_net',
):
super().__init__(n... |
9892860 | import random
import string
def get_random_id(length):
"""Generate a random, alpha-numerical id."""
alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(alphabet) for _ in range(length))
|
9892873 | import pytest
from test.data import TEST_IMAGE_URL, EVERYDAY_OBJECT_DETECTOR_ID, TEST_VIDEO_URL, RANDOM_MONGO_ID
from matroid.error import InvalidQueryError, APIError
from test.helper import print_test_pass
class TestVideos(object):
def test_videos(self, set_up_client):
threshold = 0.3
# set up client
... |
9892901 | import pandas as pd
import os
from configparser import ConfigParser, NoOptionError
from datetime import datetime
import statistics
import numpy as np
import glob
from simba.drop_bp_cords import define_movement_cols
from simba.rw_dfs import *
def ROI_process_movement(configini):
dateTime = datetime.now... |
9892918 | from django.db import models
from ..config import DELETED_VISIBLE_BY_FIELD
from ..managers import SafeDeleteManager
from ..models import SafeDeleteModel
from .testcase import SafeDeleteTestCase
class PkVisibleManager(SafeDeleteManager):
_safedelete_visibility = DELETED_VISIBLE_BY_FIELD
class PkVisibleModel(Saf... |
9892985 | from pornhub_api.schemas.tag import TagsResult
from pornhub_api.modules.base import WebMasterUrlBuilder
from pornhub_api.schemas.video import VideoResult, IsVideoActiveResult
from pornhub_api.schemas.category import CategoriesResult
__all__ = ("Video",)
class Video(WebMasterUrlBuilder):
__slots__ = ("backend",)
... |
9892995 | import pubrunner
import argparse
import hashlib
import json
from collections import defaultdict
def md5(text):
if text is None:
return ''
if isinstance(text,list):
text = "\n".join(text)
if not isinstance(text,str):
text = str(text)
m = hashlib.md5()
m.update(text.encode('utf8'))
return m.hexdigest()
def... |
9893017 | from django.test import TestCase
from apps.iiif.manifests.github import GithubApi, GithubApiException, GithubAccountNotFound
from apps.users.tests.factories import UserFactory, SocialAccountFactory, SocialAppFactory, SocialTokenFactory
import httpretty
class TestGithubApi(TestCase):
def setUp(self):
self.u... |
9893089 | from app.thirdparty.oneforall.common.lookup import Lookup
class QuerySPF(Lookup):
def __init__(self, domain):
Lookup.__init__(self)
self.domain = domain
self.module = 'dnsquery'
self.source = "QuerySPF"
self.qtype = 'SPF' # 利用的DNS记录的SPF记录收集子域
def run(self):
""... |
9893110 | import unittest
from rest_tester.utils import convert_to_list
from test import are_equal_lists
class TestUtils(unittest.TestCase):
def test_convert_to_list(self):
actual = convert_to_list('item')
expected = ['item']
self.assertTrue(are_equal_lists(actual, expected))
def test_conver... |
9893123 | import numpy as np
from PuzzleLib.Backend import gpuarray
from PuzzleLib.Containers.Sequential import Sequential
from PuzzleLib.Containers.Parallel import Parallel
from PuzzleLib.Modules.Conv2D import Conv2D
from PuzzleLib.Modules.MaxPool2D import MaxPool2D
from PuzzleLib.Modules.Activation import Activation, relu, ... |
9893133 | class Solution:
def countBits(self, num: int) -> List[int]:
res = [0]
while len(res) <= num:
res += [x+1 for x in res]
return res[:num+1] |
9893151 | import click
import numpy as np
import logging
import pickle
from sklearn.preprocessing import RobustScaler
from sklearn.utils import check_random_state
from recnn.recnn import event_baseline_predict
logging.basicConfig(level=logging.INFO,
format="[%(asctime)s %(levelname)s] %(message)s")
@cli... |
9893159 | import time
import pytest
from assemblyline.common.metrics import MetricsFactory, PerformanceTimer
from assemblyline import odm
from assemblyline.common import forge
from assemblyline.remote.datatypes.exporting_counter import export_metrics_once
@odm.model()
class Metrics(odm.Model):
counter = odm.Integer()
... |
9893196 | from .io import imread, imwrite, imfrombytes
from .transforms import (solarize, posterize, bgr2gray, rgb2gray, gray2bgr,
gray2rgb, bgr2rgb, rgb2bgr, bgr2hsv, hsv2bgr, bgr2hls,
hls2bgr, iminvert, imflip, imrotate, imcrop, impad,
impad_to_multiple... |
9893198 | import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
# os.chdir("U:\\GitHub\\scGEAToolbox\\+run\\thirdparty\\MELD")
# os.chdir("C:\\Users\\jcai.AUTH\\Documents\\GitHub\\scGEAToolbox\\+run\\thirdparty\\MELD")
import pandas as pd
import meld
data=pd.read_csv("input.txt",header... |
9893215 | from pprint import pprint
import datetime as dt
p = pprint
#p(dir(dt))
print dir()
print "\n\n\n"
print help(dt.time)
'''
keyword signature denoted by brackets
eg: datetime.time([hour[, minute[, second[, microsecond[, tzinfo]]]]])
is distinguished with key=value arguments
time(hour=x, minute=y, etc...)
positiona... |
9893247 | import pytest
@pytest.mark.parametrize('parametrize', [True, False])
def test_repeating_each_test(suite, suite_test, parametrize):
num_repetitions = 5
suite_test.repeat(num_repetitions)
if parametrize:
param = suite_test.add_parameter()
summary = suite.run()
results = summary.get_all_res... |
9893286 | import textwrap
from xarray import Dataset
from .mapping import map_over_subtree
"""
Module which specifies the subset of xarray.Dataset's API which we wish to copy onto DataTree.
Structured to mirror the way xarray defines Dataset's various operations internally, but does not actually import from
xarray's internal... |
9893307 | from django.views.generic import ListView
from django.http import HttpResponse
from .models import Job
from geoq.maps.models import FeatureType
from django.shortcuts import get_object_or_404
from datetime import datetime
from pytz import timezone
from webcolors import name_to_hex, normalize_hex
from xml.sax.saxutils i... |
9893310 | from .bounding_box import BoxList
from .segmentation_mask import SegmentationMask
from .image_list import to_image_list
from .boxlist_ops import cat_boxlist, boxlist_nms, remove_small_boxes, boxlist_iou, boxlist_ml_nms
|
9893339 | from timemachines.skaters.dlm.dlmunivariate import using_dlm, autoReg, dlm
if using_dlm:
class fixedAutoReg(autoReg):
# A hack to make DLM auto work, the version in PyPI at time of writing throws error trying to append
def __init__(self,*arg,**kwargs):
super().__init__(*arg,**kwargs)
... |
9893343 | from .adulto_seinagi_org import AdultoSeinagiOrg
class ChouTensei260mbNet(AdultoSeinagiOrg):
def prepare_cookies(self):
self._storage['cookies'][' __test'] = '9f148766d926b07a85683d7a6cd50150'
super().prepare_cookies()
main = ChouTensei260mbNet
|
9893347 | from __future__ import with_statement
from util.primitives import odict
from util.primitives.structures import oset
from digsby_chatlogs.interfaces import IAliasProvider
import struct
import oscar
import contacts
import warnings
import logging
from oscar.OscarBuddies import OscarBuddy
import common
from co... |
9893403 | import os
import time
from TCAction import TCActionBase
from TCAction import PerformanceTCBase
from NativeLog import NativeLog
SOFTAP_SSID = "SoftAPSSID4NVSCompatibleTest"
SOFTAP_PASSWORD = "<PASSWORD>"
NVS_FILE_NAME = "nvs_wifi.bin"
class TestCase(PerformanceTCBase.PerformanceTCBase):
def __init__(self, tes... |
9893409 | from jsonschema_typed import JSONSchema
from typing import TYPE_CHECKING, Final, Literal, TypedDict, Type
data: JSONSchema["schema/hard.json"]
number: JSONSchema["schema/hard.json", "num"]
status: JSONSchema["schema/hard.json", "status"]
diagnostics_list: JSONSchema["schema/hard.json", "status", "diagnostics"]
diagno... |
9893497 | import os
import sys
import copy
import logging
from checker import *
from .ofp import register_ofp_creators
from .ofp import OfpBase
from .ofp_desc_stats import SCE_DESC_STATS
from .ofp_desc_stats import OfpDescStatsCreator
# YAML:
# desc_stats_reply:
# flags: 0
# body:
# desc_stats:
# mfr_desc: ""
# ... |
9893513 | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
def choose_adventure_type(request):
if 'ok_to_start' not in request.session:
return HttpResponseRedirect(reverse('student_pas... |
9893534 | from pgmpy.models import BayesianModel
from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference import VariableElimination
import random
import numpy
model = BayesianModel([('D', 'G'), ('I', 'G'), ('G', 'L'), ('I', 'S')])
cpd_d = TabularCPD(variable='D', variable_card=2, values=[[0.6],[0.4]])
cpd_i = T... |
9893554 | from __future__ import annotations
from reamber.base import item_props
from reamber.base.Bpm import Bpm
from reamber.osu.OsuSampleSet import OsuSampleSet
from reamber.osu.OsuTimingPointMeta import OsuTimingPointMeta
MAX_BPM = 1e07
MIN_BPM = 1e-07
@item_props()
class OsuBpm(OsuTimingPointMeta, Bpm):
def __init__... |
9893584 | from functools import partial
import hydra
import numpy as np
import pandas as pd
from hydra.utils import to_absolute_path
from omegaconf import DictConfig
from tuning.bayesian import BayesianOptimizer, xgb_objective
@hydra.main(config_path="../../config/optimization/", config_name="xgb.yaml")
def _main(cfg: DictCon... |
9893639 | import argparse
import os
from functools import lru_cache
import spacy
import numpy as np
from nltk import edit_distance
from datasets import load_dataset
from tqdm import tqdm
from scipy import sparse
from scipy.sparse.csgraph import maximum_bipartite_matching
from summarus.util.spacy import spacy_deserialize, norma... |
9893657 | import sys
import unittest
from inspect import signature
# from trex_stl_lib.api import *
from wireless.trex_wireless_rpc_message import *
from wireless.trex_wireless_worker_rpc import *
from wireless.trex_wireless_worker import *
class WorkerCallTest(unittest.TestCase):
"""Tests methods for the WorkerCall subcl... |
9893702 | from torchvision.models.inception import InceptionAux
from torchvision.models.inception import InceptionA as torchInceptionA
from torchvision.models.inception import InceptionB as torchInceptionB
from torchvision.models.inception import InceptionC as torchInceptionC
from torchvision.models.inception import InceptionD a... |
9893706 | import io
import logging
import os
import shutil
import zipfile
from datetime import date
from pathlib import Path
import pandas as pd
import requests
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
PROJECT_ROOT = Path(__file__).parent.parent.parent
RESOURCE_DIR = os.path.join(PROJECT_R... |
9893714 | import gfapy
def unsafe_decode(string):
return gfapy.Alignment(string, valid = True, version = "gfa2")
def decode(string):
return gfapy.Alignment(string, valid = False, version = "gfa2")
validate_encoded = decode
def validate_decoded(alignment):
alignment.validate()
def unsafe_encode(obj):
return str(obj)
... |
9893832 | import numpy as np
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import optim
from torch.autograd import Variable
from opytimizer import Opytimizer
from opytimizer.core import Function
from opytimizer.optimizers.swarm import PSO
from opytimizer.sp... |
9893840 | from base64 import b16encode, b16decode
from django.core.urlresolvers import reverse
from django.http import HttpResponseNotAllowed
from django.test import RequestFactory
from spam.views import ReportSpamCreateView
from test_plus.test import TestCase
from test_app.models import Data
from test_app.views import DataDe... |
9893842 | import os
import pytest
import shutil
from pathlib import Path
from typing import Any, cast
from fora import example_deploys
def test_init_unknown():
with pytest.raises(ValueError, match="Unknown deploy layout structure"):
example_deploys.init_deploy_structure(cast(Any, "__unknown"))
def test_init(reques... |
9893851 | from maro.simulator import Env
from maro.simulator.scenarios.vm_scheduling.common import Action
from maro.simulator.scenarios.vm_scheduling import AllocateAction, DecisionPayload, PostponeAction
class VMSchedulingAgent(object):
def __init__(self, algorithm):
self._algorithm = algorithm
def choose_act... |
9893899 | import torch
import math
import mmcv
import torch
import torch.nn as nn
from mmdet.core import bbox_overlaps
#from ..builder import LOSSES
#from .utils import weighted_loss
from mmdet.models.losses.utils import weighted_loss
from mmdet.models.builder import LOSSES
from easymd.models.utils.visual import save_tensor
... |
9893936 | import pytest
def test_default_root_response(docker_compose, nginxproxy):
r = nginxproxy.get("http://nginx-proxy.test/")
assert r.status_code == 418
@pytest.mark.parametrize("stub,header", [
("nginx-proxy.test/web1", "bar"),
("foo.nginx-proxy.test", "f00"),
])
def test_custom_applies(docker_compose, n... |
9893952 | from typing import Dict, List, Sequence, Union
Numeric = Union[int, float]
ObsType = ObservationType = Union[List[int], List[float]]
StateType = Union[int, List[float]]
ActionType = Union[int, float, List]
DoneType = bool
RewardType = Union[int, float]
HyperparameterType = Dict[str, str]
FeatureType = Sequence[int]
|
9893958 | from setuptools import setup, find_packages
setup(
name="voltron-web",
version="0.1.1",
author="snare",
author_email="<EMAIL>",
description=("Voltron web interface"),
license="MIT",
keywords="voltron voltron-web debugger ui gdb lldb vdb",
url="https://github.com/snare/voltron-web",
... |
9894013 | from ._line import Line
from ._colorbar import ColorBar
from plotly.graph_objs.bar.marker import colorbar
|
9894026 | import random
import aiohttp
import discord
import asyncio
import secrets
from discord.ext import commands
from cogs.utils import utilities as utils
from typing import Union
class Fun(commands.Cog, name="Fun"):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def pizza(self, c... |
9894034 | import numpy as np
import cupoch as cph
import matplotlib.pyplot as plt
np.random.seed(42)
def pointcloud_generator():
yield "cube", cph.geometry.TriangleMesh.create_sphere(
).sample_points_uniformly(int(1e4)), 0.4
mesh = cph.geometry.TriangleMesh.create_torus().scale(5)
mesh += cph.geometry.Triangl... |
9894045 | from .split import train_test_split
from .validation import cross_validate
__all__ = ["train_test_split", "cross_validate", ]
|
9894102 | from __future__ import division
import unittest
from collections import defaultdict
from math import log
from time import sleep
from feemodel.tests.config import tmpdatadir_context
from feemodel.tests.pseudoproxy import install
from feemodel.util import cumsum_gen
from feemodel.simul.pools import SimPoolsNP
from feem... |
9894115 | import numpy as np
from scipy import sparse
def normalize_sparse_adj(A, sparse_type='coo'):
"""
normalize A along the second axis
A: scipy.sparse matrix
sparse_type: str (optional, default 'coo')
returns: scipy.sparse.coo_marix
"""
in_degree = np.array(A.sum(1)).reshape(-1)
in_degree[... |
9894120 | from django.contrib import admin
from library.models import Book, Borrowing, Reader
admin.site.register(Book)
admin.site.register(Borrowing)
admin.site.register(Reader)
admin.site.name = '图书馆信息管理'
admin.site.site_header = '图书馆信息管理'
|
9894126 | from .processor import ProcessorBase
class Generator(ProcessorBase):
def __init__(self, app, pipeline, id=None, config=None):
super().__init__(app, pipeline, id, config)
# The correct depth is later set by the pipeline
self.PipelineDepth = None
def set_depth(self, depth):
assert(self.PipelineDepth is None... |
9894129 | import asyncio
from time import time
from config import BOT_NAME, AllGroupMemberDatabaseName
from pyrogram import Client, filters
from others.operational_database import write_data, check_database, check_table, update_data_one, get_data_count, \
find_data, delete_data_one, write_data_one
@Client.on_message(
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.