id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1640324 | from kolibri.core.errors import KolibriError
class InvalidStorageFilenameError(KolibriError):
pass
class InsufficientStorageSpaceError(KolibriError):
pass
|
1640351 | from datetime import datetime, timedelta
from typing import Union
from passlib.context import CryptContext
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
import jwt
from jwt.exceptions import InvalidSignatureError
from sqlalchemy.orm import Session
from starlette.requests ... |
1640362 | import torchsample.transforms as ts
from medseg.dataset_loader._utils.affine_transform import MyRandomFlip, MySpecialCrop, MyPad, MyRandomChoiceRotate
from medseg.dataset_loader._utils.intensity_transform import RandomGamma, MyNormalizeMedicPercentile, MyRandomPurtarbation, MyRandomPurtarbationV2, RandomBrightnessFluct... |
1640399 | with open('log.txt', 'r') as ifs:
lines = filter(lambda line: 'main' in line, ifs.readlines())
record_list = set(map(lambda line: line.split('main:')[1], lines))
record_pair_list = map(lambda record: record.strip().split(','), record_list)
queue_list = filter(lambda ele: 'QUEUE' in ele[0], record_pair_... |
1640404 | import sys
import speech_recognition as sr
r = sr.Recognizer()
r.dynamic_energy_threshold = False
r.energy_threshold = 400
value=1
while(value):
try:
with sr.Microphone() as source:
audio = r.listen(source, timeout=2)
try:
print("You said " + r.recognize_google(audio))
sys.stdout.flush()
except... |
1640454 | import inspect
from enum import Enum
from typing import (
Any, AnyStr, ClassVar, Dict, List, Literal, Optional, Tuple, Type, Union,
get_args, get_origin
)
from typing_extensions import Annotated
from ...errors import CommandSetupError
from ...models import InteractionChannel, InteractionMember, InteractionUse... |
1640459 | import argparse
import jsons
import logging
import os
from overrides import overrides
from typing import List, Tuple
from sacrerouge.commands import RootSubcommand
from sacrerouge.common import Params
from sacrerouge.common.logging import prepare_global_logging
from sacrerouge.common.util import import_module_and_subm... |
1640475 | import os
import re
import subprocess
from collections import namedtuple
import logging
import bisect
from common import SushiError, get_extension
import chapters
MediaStreamInfo = namedtuple('MediaStreamInfo', ['id', 'info', 'default', 'title'])
SubtitlesStreamInfo = namedtuple('SubtitlesStreamInfo', ['id', 'info', ... |
1640479 | import jinja2
from jinja2 import Environment, select_autoescape
templateLoader = jinja2.FileSystemLoader( searchpath="/" )
something = ''
Environment(loader=templateLoader, load=templateLoader, autoescape=True)
templateEnv = jinja2.Environment(autoescape=True,
loader=templateLoader )
Environment(loader=templat... |
1640493 | import smbus
import gevent
from gevent.lock import BoundedSemaphore
from Node import Node
READ_ADDRESS = 0x00
READ_RSSI = 0x01
READ_FREQUENCY = 0x03
READ_TRIGGER_RSSI = 0x04
READ_LAP = 0x05
READ_TIMING_SERVER_MODE = 0x06
WRITE_TRIGGER_RSSI = 0x53
WRITE_FREQUENCY = 0x56
WRITE_TIMING_SERVER_MODE = 0x57
UPDATE_SLEEP =... |
1640508 | import logging
#import traceback
from pypes.component import Component
from pypesvds.lib.extras.pdfparser import PDFConverter
log = logging.getLogger(__name__)
class PDFReader(Component):
__metatype__ = 'ADAPTER'
def __init__(self):
# initialize parent class
Component.__init__(self)
... |
1640510 | import os, sys, glob
name = 'pydbVar'
version = '0.1'
from distutils.core import setup
from distutils.extension import Extension
metadata = {
'name': name,
'version': version,
'cmdclass': cmdclass,
}
if __name__ == '__main__':
pass
|
1640533 | from setuptools import setup, find_packages
with open("README.md", "r") as fp:
long_description = fp.read()
setup(
name='pymlir',
version='0.3',
url='https://github.com/spcl/pymlir',
author='SPCL @ ETH Zurich',
author_email='<EMAIL>',
description='',
long_description=long_description,
... |
1640589 | import os
import json
import random
import numpy as np
import tensorflow as tf
import src.core.constants as constants
import src.retina_net.anchor_generator.box_utils as box_utils
import src.retina_net.datasets.dataset_utils as dataset_utils
from src.core.abstract_classes.dataset_handler import DatasetHandler
from s... |
1640719 | from py_algorithms.data_structures import new_max_heap
class TestHeap:
def test_properties(self):
ds = new_max_heap()
assert ds.size == 0
assert ds.is_empty is True
def test_push(self):
ds = new_max_heap()
ds.push(1, 11)
ds.push(2, 12)
ds.push(3, 13)
... |
1640734 | from __future__ import unicode_literals
try:
from http.cookiejar import CookieJar
except ImportError:
from cookielib import CookieJar
import bottle
from webtest import TestApp
from bottle_utils import ajax
bottle.debug()
app = bottle.default_app()
app.config.update({str('csrf.secret'): 'foo'})
# Test han... |
1640795 | import os
import yaml
from flask import current_app
def load_fixture(fixture_name) -> dict:
fixture_name: str = os.sep.join(
(current_app.config['PROJECT_PATH'], 'fixtures', fixture_name),
)
with open(fixture_name) as f_stream:
return yaml.safe_load(f_stream)
|
1640804 | from common import *
import array
import sys
import math
from ctypes import create_string_buffer
# Useful Stuff
u32 = struct.Struct('>I')
u16 = struct.Struct('>H')
zero32 = u32.pack(0)
def RGBA8Encode(tex):
tex = tex.toImage()
w, h = tex.width(), tex.height()
padW = (w + 3) & ~3
padH = (h + 3) & ~3
destBuffer =... |
1640805 | import click
from testplan.cli.utils.actions import ProcessResultAction
from testplan.cli.utils.command_list import CommandList
from testplan.exporters.testing import (
JSONExporter,
WebServerExporter,
PDFExporter,
)
from testplan.report import TestReport
from testplan.report.testing.styles import StyleArg... |
1640913 | from pyngrok import ngrok
import pychromecast
import threading
import socket
import time
import os
global http_tunnel
http_tunnel = None
hostname = socket.gethostname()
YourPrivateIpAddress = socket.gethostbyname(hostname)
print(YourPrivateIpAddress)
name = "googlecontroller"
__all__ = 'GoogleAssistant'
def httpserver(... |
1640921 | import pytest
from swarmcg.simulations import get_settings
def test_get_settings_fail(ns_opt):
# when:
ns = ns_opt(sim_type="NO_VALID")
print(ns.sim_type)
# then:
with pytest.raises(ValueError):
_ = get_settings(ns)
def test_get_settings_optimal(ns_opt):
# when:
ns = ns_opt(sim... |
1640926 | import sys
import os
import argparse
def gen_txt(dir_path):
dataname = "datasets"
### generator .txt file according to dirs
dirs = os.listdir(os.path.join(dir_path, '{}'.format(dataname)))
print(dirs)
for d in dirs:
txt_file = d + '.txt'
txt_dir = os.path.join(dir_path, d... |
1640942 | import os
import glob
from tqdm import tqdm
import subprocess
import shutil
# Replacing them as your own folder
dataset_video_root_path = '/p300/tpami/iPER_ICCV_TEST/iPER_256_video_release'
save_images_root_path = '/p300/tpami/iPER_ICCV_TEST/images'
def extract_one_video(video_path, save_dir):
os.makedirs(save... |
1640974 | from parsr.query.boolean import TRUE, FALSE, pred
def test_true():
assert TRUE(None)
def test_false():
assert not FALSE(None)
def test_bad_pred():
def boom(v):
raise Exception()
boom = pred(boom)
assert not boom(None)
def test_caseless_predicate():
def is_blue(v):
return... |
1640999 | import logging
import importlib
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from starlette_context import context
from api.core.event_bus import Event
from api.core.profile import Profile
from api.db.errors import DoesNotExist
from api.db.models.tenant_workflow import (
TenantWorkflowRea... |
1641040 | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
# Code from <NAME>
# https://github.com/ehtsham/recsys19vlm/blob/master/RecSys2019-VLMPaper.ipynb
class VLM(object):
def __init__(self, num_users, num_items, num_tags, num_factors, var_prior, reg, video_metadata_array):
self.num_users = num_users... |
1641043 | from .Layer import *
class FC(Layer):
def __init__(self, model, *args, **kwargs):
Layer.__init__(self, model, *args, **kwargs)
self.W = None
self.b = None
self.XN = 0
self.C = 0
self.dim_out = kwargs["dim_out"]
def reshape(self):
# NCHW
self.XN ... |
1641053 | import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
class grid_map:
def __init__(self, map_matrix=None, reward_matrix=None, start_index=(2, 2), goal_index=(16, 16), reward_bound=-5, reward_collision=-0.1):
self.map_matrix = map_matrix
self.state_space = map_matrix.shape[0:2]
... |
1641106 | import json
import os
import shutil
import tempfile
import traceback
from typing import (
Callable,
NamedTuple,
)
from galaxy.datatypes.registry import Registry
from galaxy.files import ConfiguredFileSources
from galaxy.job_execution.compute_environment import SharedComputeEnvironment
from galaxy.job_execution... |
1641114 | import os
import re
import json
import stat
import glob
from pathlib import Path
import jinja2
from git import Repo
from git.exc import NoSuchPathError
from git.exc import InvalidGitRepositoryError
import hypergol
from hypergol import DatasetFactory
from hypergol import RepoData
from hypergol.utils import Mode
from h... |
1641148 | import pya #KLayout Python interface package
import sys
sys.path.append(r"C:\Users\wzhao\AppData\Local\Continuum\Anaconda3\envs\py34\Lib") ##Added other Python package, for KLayout v0.24, Python version is 3.4.2
sys.path.append(r"C:\Users\wzhao\AppData\Local\Continuum\Anaconda3\envs\py34\Lib\site-packages")
import... |
1641263 | from deidentify.surrogates.generators import LocationSurrogates, RandomData
from deidentify.surrogates.generators.location import (NUMBER_REGEX, ZIP_REGEX,
Location,
LocationDatabase,
... |
1641290 | from dexy.doc import Doc
from dexy.node import Node
from dexy.node import PatternNode
from dexy.wrapper import Wrapper
from tests.utils import wrap
import dexy.doc
import dexy.node
import os
import time
def test_create_node():
with wrap() as wrapper:
node = dexy.node.Node.create_instance(
"... |
1641309 | import numpy as np
import pandas as pd
import os
import tensorflow as tf
import keras
import matplotlib.pyplot as plt
from tensorflow.python.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.python.keras.applications.vgg16 import VGG16
from tensorflow.python.keras.preprocessing import image
from tenso... |
1641324 | from .artifact import Artifact
from .cluster import Cluster
from .dataset import Dataset, DatasetRef
from .dataset_tag import DatasetTag, DatasetVersionSummary
from .dataset_version import DatasetVersion, DatasetVersionPreSignedS3Call, DatasetVersionPreSignedURL, \
DatasetVersionTagSummary
from .deployment import D... |
1641372 | from typing import Any, Optional
class ValueObject:
def __repr__(self) -> str:
return "<{}: {}>".format(self.__class__.__name__, self)
def __eq__(self, other: Any) -> bool:
if isinstance(other, self.__class__):
return hash(self) == hash(other)
else:
return Fals... |
1641402 | import feed.handlers
import firenado.tornadoweb
class FeedComponent(firenado.tornadoweb.TornadoComponent):
def get_handlers(self):
return [
(r'/', feed.handlers.IndexHandler),
]
|
1641409 | from ._title import Title
from plotly.graph_objs.scatterpolar.marker.colorbar import title
from ._tickformatstop import Tickformatstop
from ._tickfont import Tickfont
|
1641417 | from tkinter import *
from .PyEditor import PyEditor
class MenuManager:
import Bindings
def __init__(self,parent):
self.parent=parent
self.menu_specs = [
("file", "_File"),
("edit", "_Edit"),
("format", "F_ormat"),
("command", "_Command"),
... |
1641465 | import csv
import json
import os
import sys
import threading
import numpy as np
import pandas as pd
import pymongo
import QUANTAXIS as QA
import requests
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from tabulate import tabulate
import queue
app = Flask(__name__)
app.config['SE... |
1641515 | import pytest
from genomics_data_index.storage.util.ListSliceIter import ListSliceIter
def test_slice_list():
# Case 3 elements
data = [1, 2, 3]
assert [[1], [2], [3]] == list(ListSliceIter(data, slice_size=1).islice())
assert [[1, 2], [3]] == list(ListSliceIter(data, slice_size=2).islice())
asse... |
1641523 | import torch
from torch import nn
import torch.nn.functional as F
def smooth_loss(pred_map):
def gradient(pred):
D_dy = pred[:, :, 1:] - pred[:, :, :-1]
D_dx = pred[:, :, :, 1:] - pred[:, :, :, :-1]
return D_dx, D_dy
loss = 0
weight = 1.
dx, dy = gradient(pred_map)
dx2, dx... |
1641551 | import unittest
import unittest.mock as mock
import io
import os
import split_audiobook
from split_audiobook import * # pylint: disable=W0614
DUMMY_CHAPTERS = """Chapter 1,0,360
"Beers,tears and queers",360,1000
"One/Two:Three",1000,1:01:01.1
"""
class Tests(unittest.TestCase):
def test_secs(self):
s1 ... |
1641579 | import json
import numpy as np
from nose import with_setup
from pybbn.generator.bbngenerator import generate_singly_bbn, convert_for_exact_inference
from pybbn.graph.dag import Dag, BbnUtil, Bbn
from pybbn.graph.edge import Edge, EdgeType
from pybbn.graph.node import Node
def setup():
"""
Setup.
:return... |
1641655 | from project import db
import datetime
from project.corsi.models import Corso
# Tabella di relazione 1 Corso : N Serate
class Serata(db.Model):
__tablename__ = "serata"
__table_args__ = (db.UniqueConstraint("id", "data", name="constraint_serata"),)
id = db.Column(db.Integer(), primary_key=True)
nom... |
1641657 | import random
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
num_games = 1000
ot_shots = 10
##########################
# Team 1 - Stronger Team #
####################... |
1641685 | from django.contrib.auth.models import User
from django.db import models
class Organization(models.Model):
"""Groups users and apps"""
name = models.CharField(max_length=140)
slug = models.SlugField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
r... |
1641694 | from kedro.pipeline import Pipeline, node
from kedro.pipeline.modular_pipeline import pipeline
from .nodes import (
aggregate_company_data,
apply_types_to_companies,
apply_types_to_reviews,
apply_types_to_shuttles,
combine_shuttle_level_information,
)
def create_pipeline(**kwargs) -> Pipeline:
... |
1641696 | def get_related_to(js):
info = get_info(js)
film_name = info[0]
film_id = info[1]
related_list = []
try:
relateds = js['related']['relatedTo']
if relateds != None:
for r in relateds:
title = r['title']
cosmo_id = r['ids']['cosmoId... |
1641793 | from utils import *
if __name__ == '__main__':
prots = [
'np',
'h1',
'gag',
'cov',
'cyc',
'glo',
'pgk',
'eno',
'ser'
]
for prot in prots:
fname_esm1b = f'target/ev_cache/{prot}_pseudotime.txt'
fname_tape = f'target/ev_... |
1641827 | import time
def print_msg_box(msg, indent=1, width=None, title=None):
"""Print message-box with optional title."""
lines = msg.split('\n')
space = " " * indent
if not width:
width = max(map(len, lines))
box = f'╔{"═" * (width + indent * 2)}╗\n' # upper_border
if title:
... |
1641828 | from waitress import serve
from flask import Flask, redirect, url_for, render_template, request, jsonify
from model import Generator
import os
model = Generator()
model_name = 'model-5-epochs-256-neurons.h5'
model_file = os.path.join(os.getcwd(),model_name)
model.load_weights(model_name)
app = Flask(__name__)
@app.... |
1641858 | import time
import seq2science
def log_welcome(logger, workflow):
ascii_logo = (
f"""\
____ ____ __
/ ___)( __) / \
\___ \ ) _) ( O )
(____/(____) \__\)
____
... |
1641876 | from typing import Tuple
from gym import spaces
import numpy as np
from omegaconf import DictConfig
import torch
import torch.nn as nn
from rlcycle.common.abstract.action_selector import ActionSelector
from rlcycle.common.utils.common_utils import np2tensor
class DQNActionSelector(ActionSelector):
"""DQN arg-ma... |
1641908 | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
import tornado.ioloop
from tornado.options import define, options, parse_command_line
from karura.server.server import application
define("port", default=8888, help="run on the given port", type=int)
define("debug", default=False, he... |
1641940 | import os
here = os.path.dirname(__file__)
ini_path = os.environ.get('INI_FILE')
if not ini_path:
ini_path = os.path.join(here, '../../production.ini')
from paste.deploy import loadapp
application = loadapp('config:%s' % ini_path, relative_to='.')
import logging
import logging.config
logging.config.fileConfig(in... |
1642008 | import requests
import os
import gzip
import math
import json
from typing import List, Dict
mapping = {
"earn": {
"metric": "iearn",
"labels": ["vault", "param", "address", "version"]
},
"ib": {
"metric": "ironbank",
"labels": ["vault", "param", "address", "version"]
},
... |
1642010 | from typing import Dict
def normalize_dict(a: Dict)->Dict:
total = sum([
abs(v) for v in a.values()
])
return {
k:abs(v)/total for k, v in a.items()
} |
1642040 | import csv
import json
import logging
import requests
import email.utils as eut
from bs4 import BeautifulSoup
from google.cloud import storage
from datetime import datetime, timedelta, timezone, date
JST = timezone(timedelta(hours=+9), 'JST')
def fetch_csv_as_string(url):
res = requests.get(url)
last_modified =... |
1642082 | import subprocess
import time
# Use snek environment on RHEL7
# snake-RHEL6 on RHEL6
file_name = 'test_results/results.txt'
node_list = ['drp-tst-acc0%i' % x for x in [1,2,3,4]]
nodes = ','.join(node_list)
sub_call = '`which mpirun` -q -map-by node --oversubscribe -n %i -H '+ nodes + ' python rwc_mpi.py | tee -a ... |
1642180 | import torch
import torch.nn as nn
from cuda import USE_CUDA
##################### LSTM 优化器的模型 ##########################
class LSTM_optimizer_Model(torch.nn.Module):
"""LSTM优化器"""
def __init__(self,input_size,output_size, hidden_size, num_stacks, batchsize, preprocess = True ,p = 10 ,output_... |
1642186 | from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class BMacHeader(Base):
__slots__ = ()
_SDM_NAME = 'bMacHeader'
_SDM_ATT_MAP = {
'HeaderBDstAddress': 'bMacHeader.header.bDstAddress-1',
'HeaderBSrcAddress': 'bMacHeader.header.bSrcAddress-2',
}
def __... |
1642208 | data = (
(0.304397, 0.467683),
(0.273844, 0.491539),
(0.245239, 0.509037),
(0.216803, 0.518960),
(0.185120, 0.523613),
(0.148488, 0.525367),
(0.107639, 0.525459),
(0.064614, 0.524310),
(0.021601, 0.522036),
(-0.019468, 0.518775),
(-0.056854, 0.514755),
(-0.089129, 0.510203),
(-0.115583, 0.505188),
(-0.136417, 0.499492)... |
1642212 | import contextlib
import difflib
import pprint
import pickle
import re
import sys
import logging
import warnings
import weakref
import inspect
from copy import deepcopy
from test import support
import unittest
from unittest.test.support import TestEquality, TestHashing, LoggingResult, LegacyLoggingResult, ResultWithNoS... |
1642233 | from .item import Item, ItemCreate, ItemInDB, ItemUpdate
from .msg import Msg
from .token import Token, TokenPayload
from .user import *
from .reponse import Response
from .role import *
from .system.menu import *
from .system.dict import *
from .system.department import *
|
1642245 | import hashlib
import io
import socket
def get_name(uuid):
m = hashlib.sha1()
m.update(uuid)
n = int(m.hexdigest(), 16)
lines = []
with open("names.txt", "r") as f:
lines = f.readlines()
return lines[n % len(lines)].strip().lower()
def get_thing(secret):
"""Get dweet thing name f... |
1642303 | import numpy as np
def dice_numpy(targets, outputs, threshold=None, min_area=None,
empty_one: bool = True, eps=1e-6):
if threshold is not None:
# noinspection PyUnresolvedReferences
outputs = (outputs >= threshold).astype(np.uint8)
targets_sum = targets.sum()
outputs_sum = ... |
1642321 | import sys
sys.path.append('..')
import torch
import torch.nn as nn
import numpy as np
from dataclasses import dataclass
from trphysx.transformer import PhysformerGPT2
@dataclass
class PhooConfig:
n_ctx:int = 16
n_embd:int = 16
n_layer:int = 2
n_head:int = 2
activation_function:str = "gelu_new"
... |
1642332 | import unittest
from slack_sdk.http_retry import RateLimitErrorRetryHandler
from slack_sdk.webhook import WebhookClient
from tests.slack_sdk.webhook.mock_web_api_server import (
cleanup_mock_web_api_server,
setup_mock_web_api_server,
)
from ..my_retry_handler import MyRetryHandler
class TestWebhook_HttpRetri... |
1642374 | import threading
from .peer import Peer
class Shortlist(object):
def __init__(self, k, key):
self.k = k
self.key = key
self.list = list()
self.lock = threading.Lock()
self.completion_value = None
def set_complete(self, value):
with self.lock:
... |
1642425 | import abc
import typing
from ..compose import Intersection, Pipeline, Union
__all__ = ["Query"]
class Query(abc.ABC):
"""Abstract class for models working on a query."""
def __init__(self, on: typing.Union[str, list]):
self.on = on if isinstance(on, list) else [on]
@property
def type(self... |
1642501 | from __future__ import unicode_literals
from six.moves.urllib.parse import urlparse
from rbtools.api.transport.sync import SyncTransport
class RBClient(object):
"""Entry point for accessing RB resources through the web API.
By default the synchronous transport will be used. To use a
different transport... |
1642545 | import sys
if sys.version_info < (3, 5):
print("Python 3.5 or greater required")
sys.exit(1)
import logging
import urllib.request
from zipfile import ZipFile
import os
import os.path
import sys
import platform
import struct
TEMP_DIR = 'tmp'
BINARIES_32_URL = "https://github.com/sk89q/Plumeria/releases/downlo... |
1642555 | def circle_sort_backend(A, L, R):
n = R - L
if n < 2:
return 0
swaps = 0
m = n // 2
for i in range(m):
if A[R - (i + 1)] < A[L + i]:
A[R - (i + 1)], A[L + i] = A[L + i], A[R - (i + 1)]
swaps += 1
if n & 1 and A[L + m] < A[L + m - 1]:
... |
1642566 | import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# torch.manual_seed(1) # reproducible
# np.random.seed(1)
# Hyper Parameters
BATCH_SIZE = 64
LR_G = 0.0001 # learning rate for generator
LR_D = 0.0001 # learning rate for discriminator
N_IDEAS = 5 ... |
1642572 | from typing import List, Optional
from tests.typing.models import Test, ProjectionTest
async def find_many() -> List[Test]:
return await Test.find().to_list()
async def find_many_with_projection() -> List[ProjectionTest]:
return await Test.find().project(projection_model=ProjectionTest).to_list()
async d... |
1642574 | from abc import ABC, abstractmethod
from datetime import datetime
import random
from time import sleep
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
import explorerhat
from .models import Watered, Schedule
class BaseSensor(ABC):
'''Base Sensor class for sensors'''
def __init__(sel... |
1642652 | class ZigbeeMessage:
def __init__(self, message):
self.raw = message
def get_signal_level(self):
if 'linkquality' in self.raw and self.raw['linkquality'] != None:
return int(int(self.raw['linkquality']) * 11 / 255)
else:
return None
def get_battery_level(sel... |
1642670 | import sys
from collections import defaultdict
features = defaultdict(lambda:0)
remap = {
'CopyDistance':'CopyDistance',
'DistanceHuffmanTable':'CopyDistance',
'ComplexLiterals':'ComplexLiterals',
'CopyLength':'CopyLength',
'LiteralHuffmanTable':'ComplexLiterals',
'InsertCopyHuffmanTable':'Copy... |
1642681 | import time
import sys
from app.common import values, definitions, utilities
from app.common.utilities import error_exit, save_current_state, load_state, get_source_name_from_slice
from app.tools import evolver, merger
from app.tools import emitter, reader, logger
from app.ast import ast_generator
file_index = 1
backu... |
1642682 | import numpy as np
import pytest
from numpy.testing import assert_almost_equal as aae
from spectra import SticksSpectrum
def setup():
pass
def teardown():
pass
def test_init():
energies, intensities = np.arange(10), np.arange(10)
s1 = SticksSpectrum("Hello World", energies, intensities, units="ms... |
1642702 | from enum import Enum
from typing import List
from typing import Optional
import numpy as np
import pandas as pd
from etna.transforms.base import PerSegmentWrapper
from etna.transforms.base import Transform
class ImputerMode(str, Enum):
"""Enum for different imputation strategy."""
zero = "zero"
mean =... |
1642721 | import os
from _common_search_paths import charm_path_search, grackle_path_search
is_arch_valid = 1
#python_lt_27 = 1
flags_arch = '-O3 -Wall -g'
#flags_arch = '-Wall -g'
flags_link = '-rdynamic'
#optional fortran flag
flags_arch_fortran = '-ffixed-line-length-132'
cc = 'gcc'
f90 = 'gfortran'
#flags_prec_singl... |
1642732 | r"""
Contains a list of constants and user defined units
"""
__author__ = "<NAME>"
__version__ = "0.1"
import yaml
from dataclasses import replace, asdict, is_dataclass, field, dataclass as dat
from typing import Dict, Optional, List, Union, Literal, NamedTuple
import operator
import functools
from pydantic.datacla... |
1642750 | del_items(0x800A0AE0)
SetType(0x800A0AE0, "void VID_OpenModule__Fv()")
del_items(0x800A0BA0)
SetType(0x800A0BA0, "void InitScreens__Fv()")
del_items(0x800A0C90)
SetType(0x800A0C90, "void MEM_SetupMem__Fv()")
del_items(0x800A0CBC)
SetType(0x800A0CBC, "void SetupWorkRam__Fv()")
del_items(0x800A0D4C)
SetType(0x800A0D4C, "... |
1642751 | import orjson
from rest_framework.renderers import JSONRenderer
from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList
class ORJSONRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Render `data` into JSON, returning a bytestrin... |
1642817 | import unittest
from pathlib import Path
import colab_transfer
class TestTransferMethods(unittest.TestCase):
def get_dummy_data_root(self):
data_root_folder_name = 'dummy_data_for_unit_test/'
return data_root_folder_name
def create_dummy_data(self):
input_data_folder_name = self.ge... |
1642821 | import sys
import matplotlib
matplotlib.use("Agg")
from pylab import *
base = '../'
sys.path.append(base+"utils/Correlation")
sys.path.append(base+"utils/OptExtract")
sys.path.append(base+"utils/GLOBALutils")
baryc_dir= base+'utils/SSEphem/'
sys.path.append(baryc_dir)
ephemeris='DEc403'
import matplotlib.pyplot as... |
1642849 | import dominate.tags as dt
import dominate.util as du
from io import BytesIO
from IPython.display import HTML, display
from ipywidgets import Box, Output
from nbconvert.filters.pandoc import convert_pandoc
from ..image import Image
_p = print
def _html(text, color=""):
"""print in html"""
text = convert_pan... |
1642934 | import unittest
import numpy as np
import numpy.testing as npt
from scipy.linalg import toeplitz
from doatools.model.array_elements import CustomNonisotropicSensor
from doatools.model.perturbations import LocationErrors, GainErrors, \
PhaseErrors, MutualCoupling
from doatools.mo... |
1642939 | import collections
import datetime
import pytz
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render
from standup.status.models import Status, Team, StandupUser
def require_superuser(fun):
def authorize_user(user):
return user.is_active and user.is_superuser
... |
1642940 | import numpy as np
import copy
import cv2
from parameter import *
class BoundBox:
def __init__(self, class_num):
self.x, self.y, self.w, self.h, self.c = 0., 0., 0., 0., 0.
self.probs = np.zeros((class_num,))
def iou(self, box):
intersection = self.intersect(box)
union = self.w... |
1642949 | from setuptools import setup
from distutils.core import Extension
from glob import glob
SOURCES = glob('source/*.c') + ['platforms/python/m3module.c']
setup(
name='wasm3',
version='0.0.1',
ext_modules=[
Extension('m3', sources=SOURCES, include_dirs=['source'],
extra_compile_args=['-g', '-O... |
1642959 | import numpy as np
from collections import OrderedDict
from misc.math_utils import find
from osu.local.beatmap.beatmap import Beatmap
from osu.local.hitobject.hitobject import Hitobject
from osu.local.hitobject.std.std import Std
from osu.local.hitobject.taiko.taiko import Taiko
from osu.local.hitobject.catch.catch ... |
1642995 | import os
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
class Flatten(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return x.view(-1)
class PerceptualLoss(nn.Module):
def __init__(sel... |
1643040 | from typing import Dict, Iterable, List, Tuple, Union
import pydantic
import ujson
from server import db_dir
from tarkov.exceptions import NotFoundError
from .models import Item, ItemTemplate, NodeTemplate
from .types import TemplateId
AnyTemplate = Union[ItemTemplate, NodeTemplate]
class ItemTemplatesRepository:
... |
1643071 | import requests
import os
import json
import logging
from wrapanapi.exceptions import RestClientException
requests.packages.urllib3.disable_warnings()
class BearerTokenAuth(requests.auth.AuthBase):
"""Attaches a bearer token to the given request object"""
def __init__(self, token):
self.token = toke... |
1643077 | import os
import sys
from math import sqrt
from simple_oss import SimpleOss
INSTANCE_ID = int(os.environ.get('ALI_DIKU_INSTANCE_ID'))
TASK_ID = os.environ.get('ALI_DIKU_TASK_ID')
INSTANCE_COUNT = int(os.environ.get('INSTANCE_COUNT'))
OSS_HOST = os.environ.get('ALI_DIKU_OSS_HOST')
ID = 'P4c9wtscfsH4rxeT'
KEY = '<KEY>... |
1643080 | from dcard.manager import Downloader
class TestDownloader:
def test_dwonload_with_bundles_but_no_urls(self):
downloader = Downloader()
metas = dict(test='some data')
urls = []
bundles = [(metas, urls)]
downloader.resource_bundles = bundles
cnt, _ = downloader.down... |
1643089 | from app.errors.handlers import bad_request
from re import T
from flask import jsonify
from app import db
from app.tasks import bp
from app.schemas import TasksSchema
from flask_jwt_extended import jwt_required, current_user
tasks_schema = TasksSchema(many=True)
@bp.get("/background-task/count-seconds/<int:number... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.