id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9889700 | import json
import cysimdjson
from ..abc.processor import Processor
class CySimdJsonParser(Processor):
'''
Fast JSON parser. Expects json bytes represented as bytes as input
Based on https://github.com/TeskaLabs/cysimdjson
'''
def __init__(self, app, pipeline, id=None, config=None):
super().__init__(app, pipe... |
9889716 | from numba import njit
@njit
def func(c,par):
return c**(1-par.rho)/(1-par.rho)
@njit
def marg_func(c,par):
return c**(-par.rho)
@njit
def inv_marg_func(q,par):
return q**(-1/par.rho) |
9889731 | import numpy as np
import astropy.units as u
from astropy import constants as const
def beta_fct(M_p, F_xuv, R_p):
"""Function estimates the beta parameter, which is a correction to the
planetary absorption radius in XUV, as planet appers larger than in
optical; this approximation comes from a study by Sa... |
9889741 | import numpy as np
import mcubes
import sys
import os
def read_sdf(filepath):
"""
Read SDF, i.e. from a text file containing one 60*40*60 dim vector.
:param filepath: file to read
:type filepath: str
:return: sdf values
:rtype: numpy.ndarray
"""
values = []
with open(filepath, 'r'... |
9889751 | from x64dbgpy.pluginsdk import *
import x64dbgpy
import os
import subprocess
import yara
import distorm3
from time import sleep
import struct
import sys
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
from x86devirt_jmp import decodeJumps
def findLabelLocation(labels, searchLabel):
... |
9889824 | from django.utils.encoding import smart_text
from ...models import *
from .utils import new, CommonTestCase
class EtatTestCase(CommonTestCase):
model = Etat
def setUp(self):
self.brouillon = new(Etat, nom='brouillon', public=False)
self.nouveau = new(Etat, nom='nouveau', nom_pluriel='nouveaux... |
9889842 | from PySide2 import QtCore
from PySide2 import QtWidgets
import time
import os
from . import maya_main_window
from maya import cmds, mel
from maya.app.general import mayaMixin
class GroupManager(mayaMixin.MayaQWidgetDockableMixin, QtWidgets.QDialog):
instances = list()
def __init__(self, parent=maya_main_w... |
9889856 | import json
import os
from typing import Any, Dict, Sequence, Union
class NestedDict(dict):
def __missing__(self, key):
self[key] = NestedDict()
return self[key]
def update(self, source):
for k, v in source.items():
if isinstance(v, dict):
# Doesn't handle... |
9889867 | from .build import *
from .resnet import *
from .pnasnet import *
from .efficientnet import *
from .dpn import *
from .nas_models import *
from .mnasnet import *
from .mobilenet import *
model_list = [
'DPN26',
'DPN92',
'EfficientNetB0',
'MNASNet0_5',
'MNASNet0_75',
'MNASNet1_0',
'MNASNet1_... |
9889876 | def gen():
try:
yield 1
except ValueError:
print("got ValueError from upstream!")
yield "str1"
raise TypeError
def gen2():
print((yield from gen()))
g = gen2()
print(next(g))
print(g.throw(ValueError))
try:
print(next(g))
except TypeError:
print("got TypeError from downstre... |
9889902 | import argparse
import glob
from os.path import join as path_join
from os.path import abspath, basename, isfile
from os import makedirs, pardir, remove, listdir, sep, urandom
from subprocess import Popen, PIPE
from tempfile import gettempdir
from shutil import rmtree, copyfile
import re
import sys
from locale import ge... |
9889951 | import pytest
from Ejercicio_4 import *
@pytest.mark.parametrize("expected", [
(
"Dispensando 2 billetes de $50\nDispensando 1 billetes de $20\nDispensando 1 billetes de $10\n"
)
])
def test_chain_completo(capfd, expected):
ATM = CajeroATMChain()
ATM.chain1.handle(130)
out, _ = capfd.readou... |
9889993 | from typing import Optional
import tempfile
import subprocess
import os
try:
import lxml.etree
HAVE_LXML = True
except ModuleNotFoundError:
HAVE_LXML = False
if HAVE_LXML:
class XSLTTransform:
def __init__(self, xslt):
parsed_xslt = lxml.etree.parse(xslt)
self.xslt = lx... |
9890059 | import ctypes
import numpy as np
import pytest
from psyneulink.core import llvm as pnlvm
from llvmlite import ir
DIM_X = 1000
DIM_Y = 2000
u = np.random.rand(DIM_X, DIM_Y)
v = np.random.rand(DIM_X, DIM_Y)
vector = np.random.rand(DIM_X)
trans_vector = np.random.rand(DIM_Y)
scalar = np.random.rand()
llvm_mat_res = n... |
9890099 | import logging
import urllib2
from src.commons.tasks import Tasks
class TaskCreator(object):
@staticmethod
def create_organisation_backup_scheduler_task(
page_token=None):
logging.debug(
u'Create Organisation Backup Scheduler task for page_token: %s',
page_token)
... |
9890150 | import uuid
from contextlib import contextmanager
TRACING_ID = uuid.uuid4()
@contextmanager
def new_tracing_id():
global TRACING_ID
prev_identifier = TRACING_ID
TRACING_ID = uuid.uuid4()
try:
yield TRACING_ID
finally:
TRACING_ID = prev_identifier
def get_tracing_id():
retu... |
9890165 | import logging
import fmcapi
def test__application(fmc):
logging.info("Testing Application class.")
obj1 = fmcapi.Applications(fmc=fmc)
logging.info("All Application -- >")
result = obj1.get(limit=1000)
logging.info(result)
logging.info(f"Total items: {len(result['items'])}")
del obj1
... |
9890190 | from flask_restplus import Resource,fields as filed
from app.api import ns
from app.models import User,Role
from app.marshalling import user_schema,users_schema,role_schema,gma
from flask import request,jsonify,current_app
from app.utils import token_required
from app.models import db
from app.utils import arrToRouter
... |
9890206 | import datetime
import time
import unittest
from django.db.models import Q
from django.test import TestCase
import pytz
from vesper.django.app.models import (
AnnotationInfo, Clip, Device, DeviceModel, Recording, Station,
StationDevice, StringAnnotation)
import vesper.django.app.model_utils as model_utils
imp... |
9890215 | from typing import Dict, List
import os
import random
import sys
import json
import torch
from torchvision import transforms
import torch.nn.functional as F
import torchvision
from PIL import Image
from transformers import BertConfig, BertModel, BertTokenizer
from transformers.modeling_bert import BertLayerNorm, gelu... |
9890224 | import FWCore.ParameterSet.Config as cms
from JetMETAnalysis.METSkims.metLow_Sequences_cff import *
metLowPre1HLTPath = cms.Path(metPre1HLTFilter)
metLowPre2HLTPath = cms.Path(metPre2HLTFilter)
metLowPre3HLTPath = cms.Path(metPre3HLTFilter)
|
9890254 | import unittest
from deepwater.models import alexnet
from deepwater import optimizers
from deepwater.models.test_utils import cat_dog_mouse_must_converge
from deepwater.models.test_utils import MNIST_must_converge
class TestAlexnet(unittest.TestCase):
#
# def test_alexnet_MNIST_must_converge(self):
# ... |
9890266 | import pytest
from flask import json
from sqlalchemy.exc import SQLAlchemyError
from app.dao.notifications_dao import get_notification_by_id
from app.models import Complaint
from app.notifications.notifications_ses_callback import (
check_and_queue_callback_task,
handle_complaint,
)
from tests.app.db import (
... |
9890281 | import struct
data = [
[0x6d, 0x03, 0x7b, 0xeb, 0x0d],
[0x6e, 0x60, 0x8a, 0x58, 0x0d],
[0X71, 0X06, 0xba, 0x31, 0x0d],
[0x50, 0x06, 0xba, 0x10, 0x0d],
[0x57, 0x23, 0x2d, 0xa7, 0x0d],
[0x56, 0x26, 0xa9, 0x25, 0x0d]
]
for item in data:
chksum = (item[0] + item[1] + item[2]) & 0xff
if chksum == item[3]... |
9890284 | from __future__ import division, print_function
import datetime
import unittest
import numpy as np
from nose.tools import assert_equal
from sqlalchemy import (
String,
Float,
Boolean,
DateTime,
Date
)
from beam_nuggets.io.relational_db_api import (
infer_db_type,
VARCHAR_DEFAULT_COL_SIZE
... |
9890316 | import math
def jump_search(arr,search):
j_block = len(arr)
low = 0
interval = int(math.sqrt(j_block))
for i in range(0,j_block,interval):
if arr[i] < search:
low = i
elif arr[i] == search:
return i
else:
break # bigger number is found
c=l... |
9890344 | r"""Generate labeled programs from PCFG."""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import cPickle
from .pcfg_utils.models.simulate import generateTrajectories
from .rubric_utils.load_params import get_pcfg_params, get_pcfg_pat... |
9890389 | import ast
from TVMfuzz.elements import *
import random
from TVMfuzz.syntax import *
from TVMfuzz.analyzeSyntax import dealWithStatement
from TVMfuzz.colors import *
from TVMfuzz.utils import varNameGenerator
import copy
'''nestplus components'''
def getAllElementsFromAttrCallSubsName(value):
rcur = []
while ... |
9890425 | payouts_probabilities_file = open('select_bonus.csv', 'r')
line = payouts_probabilities_file.readline()
expected_value = 0.0
while line:
tokens = line.split(',')
if len(tokens) != 2 or len(tokens[0]) < 1:
break
payout = float(tokens[0])
probability = float(tokens[1])
expected_value += payout... |
9890431 | from data.types.pixel_coordinate_system import PixelCoordinateSystem
from data.types.bounding_box_coordinate_system import BoundingBoxCoordinateSystem
from data.types.bounding_box_format import BoundingBoxFormat
from data.types.pixel_definition import PixelDefinition
class DatasetContextDAO:
def __init__(self, at... |
9890433 | import plistlib
class Manifest:
def __init__(self, manifest):
self.manifest = plistlib.loads(manifest)
self.version = self.fetch_version()
self.buildid = self.fetch_buildid()
self.supported_devices = self.fetch_supported_devices()
def fetch_buildid(self): return self.manifest[... |
9890456 | import FWCore.ParameterSet.Config as cms
CaloGeometryBuilder = cms.ESProducer("CaloGeometryBuilder",
SelectedCalos = cms.vstring('HCAL' ,
'ZDC' ,
'CASTOR' ,
'EcalBarrel' ,
... |
9890557 | from collections import Counter
import numpy as np
import random
import rospy
import states
import tensorflow as tf
import util as u
def flatten(state):
return np.asarray(state).reshape(1, -1)
# build a (grouped) copy op that copies the values of all variables between two namespaces.
# use an affine_coefficient t... |
9890563 | from thespian.actors import *
from thespian.test import *
import time
from datetime import timedelta
import sys
max_response_delay = timedelta(seconds=1.0)
class BadMessage(object):
def __init__(self, val):
self.val = val
def __str__(self):
return 'Using an invalid member: ' + str(self.this_... |
9890630 | import json
from types import SimpleNamespace
import relogic.utils.crash_on_ipy
from relogic.logickit.base.constants import DEP_PARSING_TASK
from relogic.logickit.dataflow import TASK_TO_DATAFLOW_CLASS_MAP, DependencyParsingDataFlow
from relogic.logickit.tokenizer.tokenization import BertTokenizer
config = SimpleName... |
9890631 | import json
import pytz # noqa - will get used soon
import logging
from datetime import datetime, timedelta # noqa - will get used soon
from django.db.models import Count
from django.views.generic import TemplateView
from django.db.models.functions import TruncWeek
from django.contrib.auth.mixins import LoginRequir... |
9890634 | import sys
import os
import toolshed as ts
from cyvcf2 import VCF, Writer
HERE = os.path.dirname(__file__)
fname = os.path.join(HERE, "score-lookup.txt")
lookup = {(d['from_short'], d['to_short']): d for d in ts.reader(fname)}
maxg, maxmb, minb = 0, 0, 0
for v in lookup.values():
if v['Grantham']:
v['Gra... |
9890650 | import _lib
# Digital Ocean API token (to create temporary block storage / server)
token = ''
# Digital Ocean SSH Key ID (will be used to connect to temporary backing up server)
sshkeyid = ''
# your web sites root folder path (with the folders named: my.domain.com)
sitepath = '/srv'
sites = _lib.list_dirs(sitepath)
#... |
9890670 | import os.path
from itertools import chain
from functools import total_ordering
HERE = os.path.dirname(os.path.abspath(__file__))
@total_ordering
class IPRange:
def __init__(self, start, stop):
# make stop exclusive, saves on the +1s later on
self.start, self.stop = start, stop + 1
def __e... |
9890706 | import pytest
import zmq
from plenum.common.constants import TRUSTEE_STRING
from plenum.common.exceptions import RequestRejectedException
from plenum.test.helper import sdk_get_and_check_replies, assertExp, sdk_send_random_requests
from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data, waitNodeDa... |
9890823 | from talon import Context, Module, actions
key = actions.key
edit = actions.edit
user = actions.user
mod = Module()
ctx = Context()
@ctx.action_class("edit")
class EditActions:
def word_left():
key("ctrl-left")
def word_right():
key("ctrl-right")
def select_word():
user.select_... |
9890840 | load("@io_bazel_rules_go//go:def.bzl", "GoSource", "go_context")
# This implements the toolchain_library rule, which is used to generate a
# rules_go compatible go_library-style target which contains toolchain.go.in
# augmented with information about the Go SDK's toolchain used by Bazel.
#
# The library can then be us... |
9890854 | class Solution:
def longestMountain(self, A: List[int]) -> int:
left = maxLen = 0
while left < len(A):
mid = left
while mid < len(A) - 1 and A[mid + 1] > A[mid]:
mid += 1
if mid == left:
left += 1
continue
... |
9890893 | class Solution:
def trap(self, height: List[int]) -> int:
return self.trap2(height)
def trap1(self, height: List[int]) -> int:
# TWO TRAVERSALS
if len(height) == 0:
return 0
left = [height[0]]
for i in range(1, len(height)):
left.append(ma... |
9890902 | from __future__ import print_function
import numpy as np
from skimage import color
import torch
import torchvision.datasets as datasets
import ipdb
import pandas as pd
from PIL import Image
class ImageFolderInstance(datasets.ImageFolder):
"""Folder datasets which returns the index of the image as well
"""
... |
9890914 | import logging
from multiprocessing import Process
import socks
from aiohttp import web
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from meross_iot.controller.device import BaseDevice
from meross_iot.controller.known.subdevice import Mts100v3Valve
from meross_iot.controller.mixins.toggle import ... |
9890915 | from .client import *
from .functionality_helpers import *
from .ready_state import *
from .request_helpers import *
from .utils import *
__all__ = (
*client.__all__,
*functionality_helpers.__all__,
*ready_state.__all__,
*request_helpers.__all__,
*utils.__all__,
)
|
9890923 | import json
from threading import Thread
from multiprocessing import Process, Queue
from pypykatz import logger
from pypykatz.commons.winapi.local.function_defs.netapi32 import NetLocalGroupGetMembers
from pypykatz.remote.live.common.common import is_port_up
from pypykatz.commons.common import UniversalEncoder
class... |
9890946 | from torch import nn
from .base import BaseSegmentor
from ..builder import build_network, build_losses, MODEL, build_encoder, build_decoder, build_head, build_center
from ...data.transforms.utils import resize
from ...metrics import build_metrics
@MODEL.register_module()
class EncoderDecoder(BaseSegmentor):
def ... |
9890962 | import requests
from rdflib import RDFS, RDF, XSD, Literal
from vivo_namespace import VIVO, VCARD, OBO, BIBO, FOAF, SKOS
from utility import join_if_not_empty
import re
import bibtexparser
from bibtexparser.bparser import BibTexParser
from bibtexparser.latexenc import unicode_to_latex, unicode_to_crappy_latex1, unicode... |
9891006 | import unittest
from fluentcheck.classes import Check
from fluentcheck.exceptions import CheckError
class TestCollectionsAssertions(unittest.TestCase):
def test_is_set(self):
res = Check(set()).is_set()
self.assertIsInstance(res, Check)
try:
Check(123).is_set()
sel... |
9891011 | import IPython
IPY_MAJOR = IPython.version_info[0]
if IPY_MAJOR < 3:
raise ImportError("IPython version %d is not supported." % IPY_MAJOR)
IPY3 = (IPY_MAJOR == 3)
# IPython underwent a major refactor between versions 3 and 4. Many of the
# imports in version 4 have aliases to their old locations in 3, but they ... |
9891073 | import sys, os, csv
var_file = "./data/variables.txt"
def load_variables(in_filename):
dir = os.path.split(in_filename)[0]
if os.path.exists(dir + "/variables.txt"):
fn = dir + "/variables.txt"
else:
fn = var_file
var_names = []
var_types = {}
with open(fn, "rb") as vfile:
... |
9891084 | import json
import os
from assemblyline.al.service.base import ServiceBase
from assemblyline.al.common.result import Result, ResultSection, SCORE, TAG_TYPE, TAG_WEIGHT, TEXT_FORMAT
import hashlib
import time
class TorrentSlicer(ServiceBase):
SERVICE_CATEGORY = 'Static Analysis'
SERVICE_ACCEPTS = 'meta/torren... |
9891100 | from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from hubspot.crm.extensions.cards.api.cards_api import CardsApi
from hubspot.crm.extensions.cards.api.sample_response_api import SampleResponseApi
|
9891110 | from collections import defaultdict
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Creates the i18n datamigration (django-modeltranslation -> django-modeltrans) for the specified app"
def add_arguments(self, parser):
parser.add_argument("apps", nargs="+", typ... |
9891117 | import os
import pickle
from tensorflow.keras.models import load_model
import tensorflow as tf
import ann_config
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = ""
mean_arr=pickle.load(open( os.path.join(ann_config.model_dir,"mean_part.p"), "rb" ))
std_arr=pickle... |
9891187 | import cv2 as cv
import numpy as np
import time
def surf_image_match(left_image, right_image):
gray_left_image = cv.cvtColor(left_image, cv.COLOR_BGR2GRAY)
gray_right_image = cv.cvtColor(right_image, cv.COLOR_BGR2GRAY)
gpu_gray_left_image = cv.cuda_GpuMat(gray_left_image)
gpu_gray_right_image = cv.cud... |
9891248 | from myhdl import *
def mm_gcd(clock, reset, a, b, c,
start, finished):
# set the default to "finished"
finished._val = True
x,y = [Signal(intbv(0)[len(a):])
for _ in range(2)]
@always_seq(clock.posedge, reset=reset)
def rtl():
if start:
finished.next ... |
9891255 | def represents_int(s):
try:
int(s)
return True
except ValueError:
return False
def get_vips_request(client, search, pagination, id_obj):
fields = ['id', 'name']
if pagination is not None and search is not None:
data_search = {
'start_record': pagination.s... |
9891264 | import InstagramAPI
# // NOTE: THIS IS A CLI TOOL
# /// DEBUG MODE ///
debug = False
r = InstagramAPI.InstagramRegistration(debug)
print "###########################"
print "# #"
print "# Instagram Register Tool #"
print "# #"
print "###########################"
def ... |
9891294 | import numpy as np
import sklearn.metrics
def pr_global(
y_hat,
y_obs,
threshold=0.5
):
"""
:param y_hat:
:param y_obs:
:param threshold:
:return: (data sets, 1) for each metric
"""
for i in range(len(y_hat)):
if len(y_hat[i].shape) == 1:
y_hat[... |
9891313 | import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from collections import defaultdict, Counter
from model.components import *
from model.model_utils import *
from model.dataset import get_relative_robot_traj
import model.dynamics as dynamic_module
from model.mgcvae im... |
9891340 | import re, os
import pycrfsuite
class Tokenize:
def __init__(self):
self.karen_consonant = 'ကခဂဃငစဆၡညတထဒနပဖဘမယရလဝသဟအဧၦ'
self.shan_consonant = 'ၵၶငၸသၹၺတထၼပၽၾမယလဝရႁဢၷႀၻၿ'
self.mon_consonant = 'ကခဂဃၚစဆဇၛညဋဌဍဎဏတထဒဓနပဖဗဘမယရလဝသဟဠၜအၝ'
self.burmese_consonant = 'က-အ'
self.others = '၀... |
9891349 | import pyexcel as p
from nose.tools import eq_
def test_a_dictionary_of_sheet():
test_data = [["a", "b"]]
book_dict = {"test": p.Sheet(test_data)}
book = p.Book(book_dict)
eq_(book.test.array, test_data)
def test_book_len():
test_data = [["a", "b"]]
book_dict = {"test": p.Sheet(test_data... |
9891371 | import abc
from bot.api.api_client import ApiClient
class BaseRoute(abc.ABC):
def __init__(self, client: ApiClient):
self._client: ApiClient = client
|
9891374 | import urllib.request
import base64
import time
from miflora.miflora_poller import MiFloraPoller, \
MI_CONDUCTIVITY, MI_MOISTURE, MI_LIGHT, MI_TEMPERATURE, MI_BATTERY
# Settings for the domoticz server
# Forum see: http://domoticz.com/forum/viewtopic.php?f=56&t=13306&hilit=mi+flora&start=20#p105255
domoticzserve... |
9891394 | import json
import numpy as np
import os
import tensorflow as tf
FLAGS = tf.flags.FLAGS
def sample(query_id, query_gt, query_label, query_loc, all_ids, all_gts,
all_labels, all_locs, is_training):
"""For each query video, random sample a reference video.
Args:
query_id: Query video id.
quer... |
9891407 | from asgiref.sync import AsyncToSync
from channels.generic.websocket import WebsocketConsumer
from lego.apps.events.websockets import find_event_groups
from lego.apps.websockets.groups import group_for_user
def find_groups(user):
return ["global", group_for_user(user)] + find_event_groups(user)
class GroupCons... |
9891446 | from django.conf import settings
from django.shortcuts import render, redirect
from django.views.generic import View
from django.contrib.auth.models import AnonymousUser, User
from django.http import HttpResponseForbidden
class IndexView(View):
template_name = 'dashboard.html'
login_required = True
men... |
9891469 | import copy
import math
import random
from scipy.special import erfinv
import torch
from torch import nn
import torch.nn.functional as F
from data.batcher import make_bert_batch
from tensor_utils import onehot
from .transformer_model import TransformerModel
from .modules import (
IdentityModule,
BinaryLayer... |
9891497 | import os
import yaml
from hokusai import CWD
from hokusai.lib.config import HOKUSAI_CONFIG_DIR
from hokusai.lib.exceptions import HokusaiError
from hokusai.lib.template_selector import TemplateSelector
from hokusai.services.yaml_spec import YamlSpec
def follow_extends(docker_compose_yml):
with open(docker_compose... |
9891503 | from mootdx.quotes import Quotes
client = Quotes.factory(market='std', multithread=True, heartbeat=True) # 标准市场
client = Quotes.factory(market='ext', multithread=True, heartbeat=True) # 扩展市场
# client.config(multithread=True, heartbeat=True)
client.bars(symbol='600036', category=9, offset=10)
client.index(symbol='0000... |
9891510 | import logging
import pathlib
import joblib
from util import init
def dump(df, name):
save_dir = pathlib.Path('../data/06_weight')
if not save_dir.exists():
save_dir.mkdir(parents=True)
joblib.dump(df, save_dir / f'{name}.joblib', compress=True)
def calc_weight(v_sales):
v_sales['sort_key']... |
9891542 | import math
from typing import Callable
import torch
import torch.nn.functional as F
from torch.nn import Module
from torch.nn.parameter import Parameter
class LAMA(Module):
"""
This class implements the low rank factorization multi-head self-attention mechanism described
in `"Low Rank Factorization for ... |
9891548 | import sys
from unittest.mock import Mock, _importer
from functools import wraps
class _isolate(object):
def __init__(self, target, excludes=None):
self.target = target
self.excludes = []
if excludes is not None:
self.excludes = excludes
self.names_under_test = set(self.... |
9891562 | import luigi
import target
from luigi_gcloud.bigquery import BigQueryLoadTask, BigQueryTask
from storage_tasks import CopyLocalToStorage
class CopyBigQueryToStorage(BigQueryTask):
day = luigi.DateParameter()
def requires(self):
return CopyBigQueryToBigQuery(day=self.day)
# def output(self):
... |
9891575 | from .flow import SaveResultTool as FlowSaveResultTool
from .stereo import SaveResultTool as DispSaveResultTool
def SaveResultTool(task):
if task == 'stereo':
return DispSaveResultTool()
elif task == 'flow':
return FlowSaveResultTool()
else:
raise NotImplementedError
from .flow im... |
9891581 | import os
import random
import string
from pytest import fixture
from zipfile import ZipFile
from code.code_fixtures import write_zipfile, read_zipfile
@fixture
def fzipfile():
content_length = 50
content = ''.join(random.choices(string.ascii_lowercase, k=content_length))
fnumber = ''.join(random.choices(... |
9891583 | import json
import base64
from .test_vectors import jsonRPC
def test_sign_ed25519_pass_simple():
res = jsonRPC('signTreeEd25519', {
'condition': {
'type': 'ed25519-sha-256',
'publicKey': "<KEY>",
},
'privateKey': 'D75A980182B10AB7D54BFED3C964073A0EE172F3DAA62325AF02... |
9891615 | import fault
import aetherling.helpers.fault_helpers as fault_helpers
from aetherling.space_time import *
from aetherling.space_time.reshape_st import DefineReshape_ST
@cache_definition
def Module_0() -> DefineCircuitKind:
class _Module_0(Circuit):
name = "Module_0"
IO = ['f_in1', In(ST_Int().magm... |
9891617 | import urllib.parse
import urllib.request
import hmac
import requests
import json
import time
import hashlib
import telegram
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.sup... |
9891620 | import os
def get_registry_info():
return {
"user": os.environ["ANCHORE_TEST_DOCKER_REGISTRY_USER"],
"pass": os.environ["ANCHORE_TEST_DOCKER_REGISTRY_PASS"],
"host": os.environ["ANCHORE_TEST_DOCKER_REGISTRY_HOST"],
"service_name": "docker-registry:5000",
}
|
9891630 | import os
from random import Random
from docker.client import DockerClient
from rchain.crypto import PrivateKey
from . import conftest
from .common import (
CommandLineOptions,
)
from .rnode import (
ready_bootstrap_with_network,
bootstrap_connected_peer
)
from .wait import (wait_for_node_sees_block)
BO... |
9891639 | import uuid
from xss.vuln_app.db import get_db
class TestGuestbookFunctional():
def show_formatted_message(self, app, client):
with app.app_context():
db = get_db()
cursor = db.cursor()
random_beginning = str(uuid.uuid4())
random_ending = str(uuid.uuid4())
... |
9891656 | import dataclasses
import torch
from labml import tracker
from . import Metric
@dataclasses.dataclass
class RecallPrecisionState:
fn: int = 0
fp: int = 0
tn: int = 0
tp: int = 0
def reset(self):
self.fn = 0
self.fp = 0
self.tn = 0
self.tp = 0
@property
d... |
9891678 | import spidev
spi = spidev.SpiDev() # create spi object
spi.open(0, 0) # open spi port 0, device CS=0
spi.bits_per_word=8 # only 8 supported
reg0x05 = 0X3A # LMS6 TX EN reg value
reg0x09 = 0X81 # LMS6 TX_DSM_SPI EN reg value
reg0x44 = 0X13 # LMS6 PA2 EN reg value
freq_in = raw_input("Enter Freq,GHz: ")
fre... |
9891682 | import os
import argparse
import moviepy.editor as mp
from moviepy.video.tools.cuts import FramesMatches
def parse_arguments():
parser = argparse.ArgumentParser(description="Tail wag generation")
parser.add_argument("video", nargs="+",
help="The video(s) to be scanned and giffed"
... |
9891718 | from math import *
from NodeGeneratorBase import *
from Spheral import Vector2d, Tensor2d, SymTensor2d, \
rotationMatrix2d, testPointInBox2d
from SpheralTestUtilities import fuzzyEqual
#-------------------------------------------------------------------------------
# Class to generate 2-D node positions.
#-----... |
9891726 | from Interprete.NodoAST import NodoArbol
from Interprete.Tabla_de_simbolos import Tabla_de_simbolos
from Interprete.Arbol import Arbol
from Interprete.Valor.Valor import Valor
from StoreManager import jsonMode as dbms
from Interprete.Meta import Meta
from Interprete.Manejo_errores.ErroresSemanticos import ErroresSemant... |
9891760 | import arcade
import imgui
import imgui.core
from imflo.wire import Wire
class Page(arcade.View):
def __init__(self, window, name, title):
super().__init__(window)
self.name = name
self.title = title
self.dragged = None
self.nodes = []
self.wires = []
def rese... |
9891781 | from models.hsts_result import HstsResult
from models.requirements import Requirements, RequirementsResult
from reports.constants import HSTS_MISSING, NO_ISSUES, REQ_TITLES
class HstsAnalyzer(object):
def __init__(self, hsts_scan: HstsResult, requirements: Requirements):
self.scan = hsts_scan
self... |
9891800 | from flask import Flask, redirect, request
from flask.views import MethodView
import flask_admin as admin
class ViewWithMethodViews(admin.BaseView):
@admin.expose('/')
def index(self):
return self.render('method.test.html')
@admin.expose_plugview('/_api/1')
class API_v1(MethodView):
... |
9891808 | import bpy
class Version:
"""Adjusts functions according to the differences between 2.79 and 2.8"""
#Render engine
ENGINE = "CYCLES" if bpy.app.version < (2, 80, 0) else "BLENDER_EEVEE"
# Selection / Deselection
def get_selected(obj):
if bpy.app.version < (2, 80, 0):
return ob... |
9891825 | import argparse
import utils
def main(args):
path = args.path
assert path.endswith(".doc.tokens")
# Gold EDUs
edus = utils.read_lines(path.replace(".doc.tokens", ".edus.tokens"), process=lambda line: line.split()) # List[List[str]]
# Paragraphs
lines = utils.read_lines(path, process=lambda l... |
9891838 | import numpy as np
def read_array(input, dimensions):
array = np.fromfile(input, dtype='>f4')
return reshape_array(array, dimensions)
def reshape_array(array, dimensions):
size = array.shape[0]
cols = dimensions
rows = size / dimensions
array = array.reshape((rows, cols))
return np.matri... |
9891849 | from django.test import TestCase as DjangoTestCase
try:
from django.urls import reverse, NoReverseMatch
except ImportError:
from django.core.urlresolvers import reverse, NoReverseMatch # noqa
try:
import rest_framework # noqa
DRF = True
except ImportError:
DRF = False
def get_api_client():
... |
9891856 | import os
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import art3d
from tqdm import tqdm
from utils import create_3d_figure
def create_animation_frames(gif_frames_output_folder: str) -> None:
rs = np.random.RandomState(1)
elev, azim, dist = 90, 80, 10 ... |
9891862 | import json
import textwrap
from collections import defaultdict, Counter, namedtuple
import argparse
import itertools
from csv import DictReader
from time import sleep
import os
kBIGNUMBERS = {
-1: """
88888888
88888888
""",
0: """
.n~~%x.
x88X 888.
X888X 8888L
X8888X 88888
88888X ... |
9891884 | from CSIKit.csi import CSIFrame
import numpy as np
class IWLCSIFrame(CSIFrame):
"""CSIFrame subclass for Intel IWL5300 hardware.
Format produced by Linux 802.11n CSI Tool, developed by <NAME>.
...
Attributes
----------
timestamp_low : int
Timestamp indicating... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.