id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
76477 | import locale
import os
from enum import Enum, IntEnum
from functools import lru_cache
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
gi.require_version("Notify", "0.7")
from gi.repository import Gtk, Gdk, Notify
from app.settings import Settings, SettingsException, IS_DARWIN
# Init not... |
76493 | from abc import ABC, abstractmethod
from typing import List
import numpy as np
from scipy.stats import t, spearmanr
from scipy.special import erfinv
from chemprop.uncertainty.uncertainty_calibrator import UncertaintyCalibrator
from chemprop.train import evaluate_predictions
class UncertaintyEvaluator(ABC):
"""
... |
76534 | import hydra
import hydra.utils as utils
from pathlib import Path
import torch
import numpy as np
from tqdm import tqdm
import soundfile as sf
from model_encoder import Encoder, Encoder_lf0
from model_decoder import Decoder_ac
from model_encoder import SpeakerEncoder as Encoder_spk
import os
import random
from glob... |
76536 | import numpy as np
from nms import nms
import cfg
from shapely.geometry import Polygon
class Averager(object):
"""Compute average for torch.Tensor, used for loss average."""
def __init__(self):
self.reset()
def add(self, v):
count = v.data.numel()
v = v.data.sum()
self.n_... |
76538 | class ListView(Control,IComponent,IDisposable,IOleControl,IOleObject,IOleInPlaceObject,IOleInPlaceActiveObject,IOleWindow,IViewObject,IViewObject2,IPersist,IPersistStreamInit,IPersistPropertyBag,IPersistStorage,IQuickActivate,ISupportOleDropSource,IDropTarget,ISynchronizeInvoke,IWin32Window,IArrangedElement,IBindableCo... |
76555 | import torch
import torch.nn as nn
from fpconv.pointnet2.pointnet2_modules import PointnetFPModule, PointnetSAModule
import fpconv.pointnet2.pytorch_utils as pt_utils
from fpconv.base import AssemRes_BaseBlock
from fpconv.fpconv import FPConv4x4_BaseBlock, FPConv6x6_BaseBlock
NPOINTS = [8192, 2048, 512, 128]
RADIUS =... |
76574 | import argparse, os
import malmoenv
from pathlib import Path
from gameai.utils.wrappers import DownsampleObs
def parse_args():
parser = argparse.ArgumentParser(description='malmoenv arguments')
parser.add_argument('--mission', type=str, default='../MalmoEnv/missions/mobchase_single_agent.xml',
... |
76594 | import pytest
from tests.utils.device_mock import DeviceMock
@pytest.fixture()
def device():
dev = DeviceMock({
0x10: bytes.fromhex('59')
})
return dev
class TestEncryptionTemperature:
def test_read_battery(self, device):
assert device.battery == 89
def test_write_battery(self,... |
76608 | from dataclasses import dataclass
import discord
@dataclass(init=False)
class TwitchProfile:
def __init__(self, **kwargs):
self.id = kwargs.get("id")
self.login = kwargs.get("login")
self.display_name = kwargs.get("display_name")
self.acc_type = kwargs.get("acc_type")
self... |
76627 | import pandas as pd
from pandas_datareader import data
start_date = '2014-01-01'
end_date = '2018-01-01'
SRC_DATA_FILENAME = 'goog_data.pkl'
try:
goog_data2 = pd.read_pickle(SRC_DATA_FILENAME)
except FileNotFoundError:
goog_data2 = data.DataReader('GOOG', 'yahoo', start_date, end_date)
goog_data2.to_pickle(SRC... |
76641 | import random
import pecan
from pecan import expose, response, request
_body = pecan.x_test_body
_headers = pecan.x_test_headers
class TestController:
def __init__(self, account_id):
self.account_id = account_id
@expose(content_type='text/plain')
def test(self):
user_agent = request.he... |
76657 | import csv
import os
def remove_if_exist(path):
if os.path.exists(path):
os.remove(path)
def load_metadata(path):
res = {}
headers = None
with open(path, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
if head... |
76674 | import sys
import csv
from matplotlib import image as mpimg
import numpy as np
import scipy.misc
import cv2
vert_filename = sys.argv[1]
edge_filename = sys.argv[2]
img_filename = sys.argv[3]
output_img_filename = sys.argv[4]
thresh = int(sys.argv[5])
print('reading in verts...')
verts = []
with open(vert_filename, '... |
76687 | import torch
from hypothesis import given
from hypothesis import strategies as st
from subset_samplers import ConstructiveRandomSampler
from subset_samplers import ExhaustiveSubsetSampler
from subset_samplers import ProportionalConstructiveRandomSampler
from subset_samplers import RandomProportionSubsetSampler
from su... |
76702 | import tensorflow as tf
import numpy as np
def batches(l, n):
"""Yield successive n-sized batches from l, the last batch is the left indexes."""
for i in range(0, l, n):
yield range(i,min(l,i+n))
class Deep_Autoencoder(object):
def __init__(self, sess, input_dim_list=[7,64,64,7],transfer_function... |
76710 | from .component import Component
class Location(Component):
NAME = "location"
def __init__(self):
super().__init__()
# TODO THIS HOLDS ALL THE INFORMATION NEEDED TO LOCATE SOMETHING
self.local_x = 0
self.local_y = 0
self.global_x = 0
self.global_y = 0
s... |
76740 | from time import time
import os
from random import gauss
import sys
import numpy as np
from keras.models import Sequential, load_model
from keras.layers import Dense, Activation
from Bio.SeqIO import SeqRecord
from Bio import SeqIO, Seq
from advntr.sam_utils import get_id_of_reads_mapped_to_vntr_in_bamfile, make_bam... |
76752 | from django.conf import settings
def get_user_model_name():
"""
Returns the app_label.object_name string for the user model.
"""
return getattr(settings, "AUTH_USER_MODEL", "auth.User")
|
76764 | import os
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MODEL_PATH = os.path.join(PROJECT_ROOT, 'models')
DATA_PATH = os.path.join(PROJECT_ROOT, 'data')
|
76767 | import FWCore.ParameterSet.Config as cms
from CondCore.DBCommon.CondDBCommon_cfi import *
PoolDBESSourcebtagMuJetsWpNoTtbar = cms.ESSource("PoolDBESSource",
CondDBCommon,
toGet = cms.VPSet(
#
# working points
#
cms.PSet(
record = cms.stri... |
76778 | from simple_NER.utils.log import LOG
from simple_NER.rules import RuleNER
from simple_NER import Entity
from os.path import expanduser, isdir, join
from os import makedirs
try:
from padatious import IntentContainer
except ImportError:
LOG.error("padatious not found, run")
LOG.error("pip install fann2==1.0.... |
76852 | from dataclasses import dataclass
from dbt.adapters.sqlserver import (SQLServerConnectionManager,
SQLServerCredentials)
@dataclass
class SynapseCredentials(SQLServerCredentials):
@property
def type(self):
return "synapse"
class SynapseConnectionManager(SQLServerCon... |
76863 | import pytest
from webbpsf import wfirst
from numpy import allclose
def test_WFI_psf():
"""
Just test that instantiating WFI works and can compute a PSF without raising
any exceptions
"""
wi = wfirst.WFI()
wi.calc_psf(fov_pixels=4)
def test_WFI_filters():
wi = wfirst.WFI()
filter_lis... |
76893 | from typing import Optional, List
from platypush.message.response import Response
class PrinterResponse(Response):
def __init__(self,
*args,
name: str,
printer_type: int,
info: str,
uri: str,
state: int,
... |
76933 | from ubinascii import hexlify
from bitcoin import bip32, bip39, script
# NETWORKS contains all constants for HD keys and addresses
from bitcoin.networks import NETWORKS
# we will use testnet:
network = NETWORKS["test"]
entropy = b'\x64\xd3\xe4\xa0\xa3\x87\xe2\x80\x21\xdf\x55\xa5\x1d\x45\x4d\xcf'
recovery_phrase = bip... |
76940 | from manim import *
from manim_ml.neural_network.layers import TripletLayer, triplet
from manim_ml.neural_network.layers.feed_forward import FeedForwardLayer
from manim_ml.neural_network.neural_network import NeuralNetwork
config.pixel_height = 720
config.pixel_width = 1280
config.frame_height = 6.0
config.frame_width... |
76944 | import typing
from pycspr.crypto import KeyAlgorithm
from pycspr.factory import create_public_key
from pycspr.serialisation.cl_type_from_bytes import decode as cl_type_from_bytes
from pycspr.serialisation.cl_value_from_bytes import decode as cl_value_from_bytes
from pycspr.types import Timestamp
from pycspr.types impo... |
77067 | import re
from os import environ
import boto3
import pytest
from botocore.exceptions import ClientError
from moto import mock_efs
from tests.test_efs.junk_drawer import has_status_code
ARN_PATT = r"^arn:(?P<Partition>[^:\n]*):(?P<Service>[^:\n]*):(?P<Region>[^:\n]*):(?P<AccountID>[^:\n]*):(?P<Ignore>(?P<ResourceType... |
77089 | import numpy as np
from scipy.optimize import least_squares
from scipy.special import gamma
from scipy.stats import gengamma
from percentile_3_moments_first_guess import percentile_3_moments_first_guess
from tqdm import trange
import sys
def percentile_3_moments(trA,trAsq,trAcub,proba,MaxFunEvals):
""" percentile_3... |
77104 | from setuptools import setup, find_packages
VERSION_NUMBER = '0.1.0'
with open('requirements.txt', 'rb') as handle:
REQUIREMENTS = [
x.decode('utf8') for x in handle.readlines()
]
with open('dev_requirements.txt', 'rb') as handle:
TEST_REQUIREMENTS = [
x.decode('utf8') for x in handle.r... |
77119 | import json
from os import write
w = open("json.txt","r",encoding="utf-8")
f = open("dict.txt","w",encoding="utf-8")
arr = json.load(w)
s = dict()
f.write('{')
for item in arr:
s[item["value"]] = item["key"]
print(s)
for key in s:
f.write('"'+str(key)+'"'+':')
f.write('"'+str(s[key])+'"'+',\n')
f.write("}"... |
77127 | import ee
# Initialize the GEE API
# try:
# ee.Initialize()
# except Exception as ee:
# ee.Authenticate()
# ee.Initialize()
# geemap:A Python package for interactive mapping with Google Earth Engine, ipyleaflet, and ipywidgets
# Documentation: https://geemap.org
import geemap
from geemap import ml
import p... |
77141 | from __future__ import absolute_import, division, print_function, unicode_literals
import fractions
import math
from six.moves import xrange
# http://stackoverflow.com/questions/4798654/modular-multiplicative-inverse-function-in-python
# from https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extende... |
77165 | from typing import TYPE_CHECKING, Any, Dict, List, Optional
from app import errors
if TYPE_CHECKING:
from app.database.database import Database
class Autoredeem:
def __init__(self, db: "Database"):
self.db = db
async def get(
self, guild_id: int, user_id: int
) -> Optional[Dict[str,... |
77192 | import os,sys
from scipy.stats.stats import pearsonr
import numpy as np
try:
bacteriaF = sys.argv[1]
phageF = sys.argv[2]
except:
sys.exit(sys.argv[0] + " <bacterial file> <phage file>")
bact={}
with open(bacteriaF, 'r') as bin:
l=bin.readline()
bactheaders = l.strip().split("\t")
for l in ... |
77218 | import sys
sys.path.append('../')
import tensorflow as tf
from google.cloud import storage
from tempfile import TemporaryDirectory
import os
from mreserve.lowercase_encoder import get_encoder
import argparse
from PIL import Image
import numpy as np
from io import BytesIO
import random
encoder = get_encoder()
class GC... |
77222 | import os.path as osp
import random
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal, assert_array_equal
from mmaction.core import (ActivityNetLocalization,
average_recall_at_avg_proposals, confusion_matrix,
get_weighted_score, ... |
77224 | import numpy as np
import sys
import os
import pytest
from knnFeat import _distance
sys.path.append(os.getcwd())
@pytest.mark.success
def test_distance():
a = np.array([0, 0])
b = np.array([3, 4])
expected = _distance(a, b)
actual = 5
assert expected == actual
|
77292 | class BaseSubmission:
def __init__(self, team_name, player_names):
self.team_name = team_name
self.player_names = player_names
def get_actions(self, obs):
'''
Overview:
You must implement this function.
'''
raise NotImplementedError
|
77404 | from plex_database.core import db
from plex_database.models.directory import Directory
from plex_database.models.media_item import MediaItem
from peewee import *
class MediaPart(Model):
class Meta:
database = db
db_table = 'media_parts'
media_item = ForeignKeyField(MediaItem, null=True, rela... |
77487 | import numpy as np
import time
import math
# from cassie_env import CassieEnv
from cassiemujoco import *
from trajectory.trajectory import CassieTrajectory
import matplotlib.pyplot as plt
from matplotlib import style
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
from mpl_too... |
77540 | import pytest
from wemake_python_styleguide.violations.complexity import (
TooDeepAccessViolation,
)
from wemake_python_styleguide.visitors.ast.complexity.access import (
AccessVisitor,
)
# boundary expressions
subscript_access = 'my_matrix[0][0][0][0]'
attribute_access = 'self.attr.inner.wrapper.value'
mixed... |
77615 | import logging
import numpy as np
from numpy.linalg import norm
from scipy.stats import moment
from scipy.special import cbrt
def common_usr(molecule, ctd=None, cst=None, fct=None, ftf=None, atoms_type=None):
"""Function used in USR and USRCAT function
Parameters
----------
molecule : oddt.toolkit.M... |
77653 | import ui, console
import os
import math
def save_action(sender):
with open('image_file.png', 'wb') as fp:
fp.write(img.to_png())
console.hud_alert('image saved in the file image_file.png')
def showimage_action(sender):
img.show()
def make_polygon(num_sides, x=0, y=0, radius=100, phase=0... |
77675 | import torch
from .. import utils
MODULE = torch
FP16_FUNCS = [
# Low level functions wrapped by torch.nn layers.
# The wrapper layers contain the weights which are then passed in as a parameter
# to these functions.
'conv1d',
'conv2d',
'conv3d',
'conv_transpose1d',
'conv_transpose2d'... |
77712 | import re
import uuid
from subprocess import run
from tempfile import NamedTemporaryFile
from typing import List, Optional
import conda_pack
import yaml
from ...utils import logger
from ..constants import MLServerEnvDeps, MLServerRuntimeEnvDeps
from ..metadata import ModelFramework
def _get_env(conda_env_file_path:... |
77716 | from insightconnect_plugin_runtime.exceptions import PluginException
from json import JSONDecodeError
import requests
from requests.auth import HTTPBasicAuth
from urllib.parse import urlsplit
class EasyVistaApi:
def __init__(self, client_login: dict, account: int, url: str):
self.base_url = f"{self.split_... |
77751 | from unittesting import DeferrableTestCase
from GitSavvy.tests.parameterized import parameterized as p
from GitSavvy.core.commands.log_graph import describe_graph_line
examples = [
(
"|",
{},
None
),
(
"● a3062b2 (HEAD -> optimize-graph-render, origin/optimize-graph-render... |
77772 | from __future__ import annotations
from typing import TYPE_CHECKING
import random
from enum import Enum
from configuration import config
from src.genotype.mutagen.option import Option
from src.genotype.neat.gene import Gene
if TYPE_CHECKING:
pass
class NodeType(Enum):
INPUT = 0
HIDDEN = 1
OUTPUT =... |
77781 | import random
import pygame
from . import map_generator, traps
from .pathfinder import Pathfinder
from .tile import Tile
TILE_SIZE = 16
BARRIER_SIZE = 10
def grid_walk(start, end):
start = list(start)
dx = end[0] - start[0]
dy = end[1] - start[1]
nx = abs(dx)
ny = abs(dy)
sign_x = 1 if dx >... |
77841 | import cv2
import tensorflow as tf
import numpy as np
OUTPUT_PATH = "../events/"
NUM_FILTERS = 10
FILTER_SIZE = (3, 3)
STRIDES = (1, 1)
def nn(input_node):
with tf.variable_scope('nn'):
w = tf.get_variable(
name='weight',
shape=[FILTER_SIZE[0], FILTER_SIZE[1], 3, NUM_FILTERS],
... |
77847 | import csv
class Characters:
def getBrawlersID():
BrawlersID = []
with open('Logic/Files/assets/csv_logic/characters.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0 or ... |
77856 | from io import BytesIO
from PIL import Image, ImageDraw
from flask import send_file
from utils.endpoint import Endpoint, setup
from utils.textutils import wrap, render_text_with_emoji
@setup
class SneakyFox(Endpoint):
params = ['text']
def generate(self, avatars, text, usernames, kwargs):
base = Im... |
77858 | from unittest import TestCase
from pypika import (
Table,
functions as fn,
)
import fireant as f
from fireant.tests.dataset.mocks import test_database
test_table = Table("test")
ds = f.DataSet(
table=test_table,
database=test_database,
fields=[
f.Field("date", definition=test_table.date, ... |
77918 | import torch
import json
from os import PathLike
from typing import List, Tuple, Union, Optional
from allennlp.common.file_utils import cached_path
from allennlp.data import Vocabulary
from allennlp.data.tokenizers.tokenizer import Tokenizer
def _convert_word_to_ids_tensor(word, tokenizer, vocab, namespace, all_case... |
77921 | from util.fsm import StateMachine
if __name__ == "__main__":
machine = StateMachine('status', ["off", "fleft", "left", "bleft",
"fright", "right", "bright"], "left")
machine.create_trans("left", "fleft", "otherleft")
print machine.process("otherleft")
#>>> states = ["off", "f... |
77945 | import torch
import numpy as np
from onnx import numpy_helper
from thop.vision.basic_hooks import zero_ops
from .counter import counter_matmul, counter_zero_ops,\
counter_conv, counter_mul, counter_norm, counter_pow,\
counter_sqrt, counter_div, counter_softmax, counter_avgpool
def onnx_counter_matmul(diction,... |
77960 | from torch import nn
class FeedForwardNet(nn.Module):
def __init__(self, inp_dim, hidden_dim, outp_dim, n_layers, nonlinearity, dropout=0):
super().__init__()
layers = []
d_in = inp_dim
for i in range(n_layers):
module = nn.Linear(d_in, hidden_dim)
self.rese... |
77964 | from toga_winforms.libs import WinForms
from .base import Widget
class Tree(Widget):
def create(self):
self.native = WinForms.TreeView()
def row_data(self, item):
self.interface.factory.not_implemented('Tree.row_data()')
def on_select(self, selection):
self.interface.factory.not... |
78001 | import logging
from ...util import none_or
from .collection import Collection
logger = logging.getLogger("mw.database.collections.pages")
class Pages(Collection):
def get(self, page_id=None, namespace_title=None, rev_id=None):
"""
Gets a single page based on a legitimate identifier of the page. ... |
78033 | from rxbp.flowables.controlledzipflowable import ControlledZipFlowable
from rxbp.indexed.selectors.bases.numericalbase import NumericalBase
from rxbp.subscriber import Subscriber
from rxbp.testing.testcasebase import TestCaseBase
from rxbp.testing.testflowable import TestFlowable
from rxbp.testing.tobserver import TObs... |
78063 | from dataclasses import dataclass
from apischema.json_schema import deserialization_schema
@dataclass
class Bar:
baz: str
@dataclass
class Foo:
bar1: Bar
bar2: Bar
assert deserialization_schema(Foo, all_refs=False) == {
"$schema": "http://json-schema.org/draft/2020-12/schema#",
"$defs": {
... |
78065 | import grpc
import time
from bettermq_pb2 import *
from bettermq_pb2_grpc import *
host = '127.0.0.1:8404'
with grpc.insecure_channel(host) as channel:
client = PriorityQueueStub(channel)
i = 1
while True:
req = DequeueRequest(
topic = "root",
count = 1,
)
i... |
78070 | import numpy as np
def prefix_search(mat: np.ndarray, chars: str) -> str:
"""Prefix search decoding.
See dissertation of Graves, p63-66.
Args:
mat: Output of neural network of shape TxC.
chars: The set of characters the neural network can recognize, excluding the CTC-blank.
Returns:... |
78096 | from struct import Struct
def read_records(format, f):
record_struct = Struct(format)
chunks = iter(lambda: f.read(record_struct.size), b'')
return (record_struct.unpack(chunk) for chunk in chunks)
# Example
if __name__ == '__main__':
with open('data.b','rb') as f:
for rec in read_records('<id... |
78107 | from typing import Dict, List
from dataclasses import dataclass, field
import tvm
from tvm import relay
import pickle
import random
import numpy as np
import random
from copy import deepcopy
from .tvmpass import PassDependenceGraph, PassNode
# TODO: Add parameters.
# TODO: Add more passes.
_RELAY_FUNCTION_HARD_PASSE... |
78113 | import json
import os
import unittest
import shutil
from satstac import __version__, Catalog, STACError, Item
testpath = os.path.dirname(__file__)
class Test(unittest.TestCase):
path = os.path.join(testpath, 'test-catalog')
@classmethod
def tearDownClass(cls):
""" Remove test files """
... |
78172 | load("@bazel_skylib//lib:dicts.bzl", _dicts = "dicts")
load(
"//rules/scala_proto:private/core.bzl",
_scala_proto_library_implementation = "scala_proto_library_implementation",
_scala_proto_library_private_attributes = "scala_proto_library_private_attributes",
)
scala_proto_library = rule(
attrs = _dic... |
78194 | import math
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
"""
Turtle drawings
Once the functions reset(), turn(), turnTo() and forw() there is a possibility to
program a path. In essence this is very similar to using polar coordinates relative
to the last set point. Meaning you define t... |
78201 | import os
from unittest import mock
import pytest
from kubernetes.client.exceptions import ApiException
from task_processing.plugins.kubernetes.kube_client import ExceededMaxAttempts
from task_processing.plugins.kubernetes.kube_client import KubeClient
def test_KubeClient_no_kubeconfig():
with mock.patch(
... |
78223 | from joerd.util import BoundingBox
import joerd.download as download
import joerd.check as check
import joerd.srs as srs
import joerd.mask as mask
from joerd.mkdir_p import mkdir_p
from shutil import copyfileobj
import os.path
import os
import requests
import logging
import re
import tempfile
import sys
import tracebac... |
78243 | import logging
from functools import wraps
from celery import states
from . import events
from .application import celery_application
from .events import RUNTIME_METADATA_ATTR
winnow_task_logger = logging.getLogger(__name__)
class WinnowTask(celery_application.Task):
def update_metadata(self, meta=None, task_i... |
78283 | import os
from gitaccount.gitaccounthelpers.gitaccounthelpers import (
get_repos_from_url, clone, pull, already_cloned,
get_gists_from_url)
class GitAccount:
"""GitAccount class provides clone_repos and update_repos methods"""
def __init__(self, account_type, userName):
self._userName = userNa... |
78307 | from backend.serializers.user_model_serializer import UserModelDetailSerializer
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': UserModelDetailSerializer(user, context={'request':request}).data
} |
78309 | from lyrebird import application
from .. import checker
class CustomDecoder:
def __call__(self, rules=None, *args, **kw):
def func(origin_func):
func_type = checker.TYPE_DECODER
if not checker.scripts_tmp_storage.get(func_type):
checker.scripts_tmp_storage[func_typ... |
78314 | from mongoengine import Document, IntField, DoesNotExist, MultipleObjectsReturned, StringField
class SwapTrackerObject(Document):
nonce = IntField(required=True)
src = StringField(required=True, unique=True)
@classmethod
def last_processed(cls, src: str):
"""
Returns last processed co... |
78412 | from bge import logic
class HeartContainer:
def __init__(self, startHeart, maxHeart):
self.isLow = False
# if heartContainer not exist init then
if not 'heartContainer' in logic.globalDict['Player']:
logic.globalDict['Player']['heartContainer'] = {'heart' : startHeart, 'maxHeart' : maxHeart}
def calculLow... |
78457 | class Token:
TOP_LEFT = "┌"
TOP_RIGHT = "┐"
BOTTOM_LEFT = "└"
BOTTOM_RIGHT = "┘"
HORIZONTAL = "─"
BOX_START = TOP_LEFT + HORIZONTAL
VERTICAL = "│"
INPUT_PORT = "┼"
OUTPUT_PORT = "┼"
FUNCTION = "ƒ"
COMMENT = "/*...*/"
SINGLE_QUOTE = "'"
DOUBLE_QUOTE = '"'
LEFT_PARE... |
78509 | class IndexingError(Exception):
"""Exception raised for errors in the indexing flow.
Attributes:
type -- One of 'user', 'user_replica_set', 'user_library', 'tracks', 'social_features', 'playlists'
blocknumber -- block number of error
blockhash -- block hash of error
txhash -- tr... |
78516 | import itertools
import logging
import numpy as np
import pandas as pd
import scipy.stats
def create_regression_dataset(metafeatures, experiments):
X = []
X_indices = []
Y = []
for dataset_name in experiments:
experiment = experiments[dataset_name]
mf = metafeatures.loc[dataset_name]
... |
78604 | from dataclasses import dataclass
from typing import Tuple
from manim import config
from manim import DEFAULT_MOBJECT_TO_EDGE_BUFFER
from manim import DEFAULT_MOBJECT_TO_MOBJECT_BUFFER
from manim import DOWN
from manim import LEFT
from manim import Mobject
from manim import np
from manim import ORIGIN
from manim impor... |
78612 | import unittest
import numpy as np
from audiomentations.augmentations.transforms import Mp3Compression
from audiomentations.core.composition import Compose
class TestMp3Compression(unittest.TestCase):
def test_apply_mp3_compression_pydub(self):
sample_len = 44100
samples_in = np.random.normal(0,... |
78614 | from . import mysqldb
from physical.models import Instance
class MySQLPercona(mysqldb.MySQL):
def get_default_instance_type(self):
return Instance.MYSQL_PERCONA
@classmethod
def topology_name(cls):
return ['mysql_percona_single']
class MySQLPerconaFOXHA(mysqldb.MySQLFOXHA):
def ge... |
78641 | import argparse
import configparser
import torch
import os
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from model import ValueNetwork
from env import ENV
from train import run_one_episode
def visualize(model_config, env_config, weight_path, case, save):
state_dim = ... |
78660 | import ast
from amqp import ChannelError
from kombu import Connection
from kombu.common import uuid, maybe_declare
from mock import patch, ANY
from cell.actors import Actor, ActorProxy
from cell.exceptions import WrongNumberOfArguments
from cell.results import AsyncResult
from cell.tests.utils import Case, Mock, with_... |
78707 | from datetime import datetime
from mongoengine import DateTimeField, Document, UUIDField
from mongoengine.fields import DictField, ListField, ReferenceField
from vim_adaptor.models.vims import BaseVim
class ServiceInstance(Document):
"""
Document class to store data related to a service instance
"""
... |
78756 | import base64
import urllib2
import json
import os
import logging
from celery import task
from django.conf import settings
from django.utils.timezone import now
from github.GithubObject import NotSet
from github import Github, GithubException, InputGitTreeElement
from ide.git import git_auth_check, get_github
from id... |
78792 | import json
import sys
def main():
argv_file = sys.argv[1]
with open(argv_file, "wt") as fp:
json.dump(sys.argv, fp)
sys.exit(0)
if __name__ == "__main__":
main()
|
78793 | import asyncio
import json
import signal
from callosum.rpc import Peer
from callosum.ordering import (
KeySerializedAsyncScheduler,
)
from callosum.lower.zeromq import ZeroMQAddress, ZeroMQRPCTransport
async def handle_echo(request):
print('echo start')
await asyncio.sleep(1)
print('echo done')
r... |
78828 | from collections import OrderedDict as odict
import time
import numpy as np
from .json_encoder import JsonNumEncoder
import os
class Profiler:
"""This class provides a very simple yet light implementation of function profiling.
It is very easy to use:
>>> profiler.reset()
>>> profiler.start("... |
78829 | import math
import hashlib
import zlib
from bitarray import bitarray
from globals import G
class BFsignature():
def __init__(self, total_chunks):
self.total_chunks = total_chunks
if self.total_chunks > 0:
self.cal_m()
#print("bf size = ",self.m)
else:
#lo... |
78857 | from typing import List, TYPE_CHECKING
from cloudfoundry_client.json_object import JsonObject
if TYPE_CHECKING:
from cloudfoundry_client.client import CloudFoundryClient
class ResourceManager(object):
def __init__(self, target_endpoint: str, client: "CloudFoundryClient"):
self.target_endpoint = targ... |
78935 | from aiogram import types
from .dataset import PHOTO
photo = types.PhotoSize(**PHOTO)
def test_export():
exported = photo.to_python()
assert isinstance(exported, dict)
assert exported == PHOTO
def test_file_id():
assert isinstance(photo.file_id, str)
assert photo.file_id == PHOTO['file_id']
d... |
78954 | from yo_fluq_ds__tests.common import *
import numpy as np
class MiscMethodsTests(TestCase):
def test_pairwise(self):
result = Query.args(1,2,3).feed(fluq.pairwise()).to_list()
self.assertListEqual([(1,2),(2,3)],result)
def test_strjoin(self):
result = Query.args(1,2,3).feed(fluq.strjoi... |
78961 | from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectUD import DistributedObjectUD
class AwardManagerUD(DistributedObjectUD):
notify = DirectNotifyGlobal.directNotify.newCategory('AwardManagerUD')
|
78971 | from motion import *
if __name__ == '__main__':
from time import sleep
buf = []
buf_len = 5
last_avg = 0
threshold = 0.02
lsm = accelcomp()
while True:
lsm.getAccel()
buf.append(lsm.accel[X] + lsm.accel[Y] + lsm.accel[Z])
buf = buf[-buf_len:]
avg = reduce... |
79012 | from typing import List
class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
mods = [0] * 60
for t in time:
mods[t % 60] += 1
cnt = sum(mods[i] * mods[60 - i] for i in range(1, 30))
for i in [0, 30]:
cnt += mods[i] * (mods[i] - 1) // 2
... |
79025 | from abc import abstractmethod
import numpy as np
from pymoo.core.population import Population
# ---------------------------------------------------------------------------------------------------------
# Survival
# ----------------------------------------------------------------------------------------------------... |
79078 | import json
import logging
from pprint import pformat
from typing import Any, Dict, Set
import pydantic
from models_library.projects_nodes import NodeID
from models_library.utils.nodes import compute_node_hash
from packaging import version
from ..node_ports_common.dbmanager import DBManager
from ..node_ports_common.e... |
79101 | import warnings
from random import randint
from unittest import TestCase
from .models import (
ColumnFamilyTestModel,
ColumnFamilyIndexedTestModel,
ClusterPrimaryKeyModel,
ForeignPartitionKeyModel,
DictFieldModel
)
from .util import (
connect_db,
destroy_db,
create_model
)
class Colu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.