id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
144657 | from aw_nas.objective.base import BaseObjective
class ContainerObjective(BaseObjective):
NAME = "container"
def __init__(self, search_space, sub_objectives,
losses_coef=None, rewards_coef=None,
schedule_cfg=None):
super().__init__(search_space, schedule_cfg=schedule_... |
144658 | import rospy
import PyKDL
from geometry_msgs.msg import Twist, Point, PoseStamped, TwistStamped
from std_msgs.msg import String
import numpy
import math
import sys
import copy
from gazebo_msgs.srv import GetModelState
class ReturnHome:
def __init__(self,uav_id):
self.uav_type = 'typhoon_h480'
self.... |
144683 | import numpy as np
import matplotlib.pyplot as plt
from math import sqrt, copysign
from scipy.optimize import brenth
from scipy.optimize import fsolve,fmin_l_bfgs_b,fmin_cg,fminbound
"""
sign of the number
"""
def sign(x):
if x==0:
return 0
else:
return copysign(1,x)
"""
if function f can't b... |
144691 | from openiec.calculate.calcsigma import SigmaPure, SigmaSolLiq, SigmaCoherent
from openiec.property.molarvolume import MolarVolume, InterficialMolarVolume
from openiec.property.meltingenthalpy import MeltingEnthalpy
# binary
# ternary
|
144749 | from Foundation import *
from PyObjCTools.TestSupport import *
try:
unicode
except NameError:
unicode = str
class TestNSOperation (TestCase):
def testConstants(self):
self.assertEqual(NSOperationQueuePriorityVeryLow, -8)
self.assertEqual(NSOperationQueuePriorityLow, -4)
self.assert... |
144754 | TYPE_MAP = {
0: 'bit',
1: 'u32',
2: 's32',
3: 'float',
'bit': 0,
'u32': 1,
's32': 2,
'float': 3,
}
class HalType(object):
bit = 0
u32 = 1
s32 = 2
float = 3
@classmethod
def toString(self, typ):
return TYPE_MAP[typ]
|
144772 | from typing import Dict
from gopay.http import Request, Response, Browser
from gopay.enums import Language
import json
JSON = 'application/json'
FORM = 'application/x-www-form-urlencoded'
class GoPay:
def __init__(self, config: dict, browser: Browser) -> None:
self.browser = browser
self.config ... |
144789 | import asyncio
import os
import tempfile
from pathlib import Path
from typing import Optional, Union
from aiofiles import os as aiofiles_os
from aiohttp.abc import AbstractStreamWriter
from aiohttp.typedefs import LooseHeaders
from aiohttp.web import FileResponse
makedirs = aiofiles_os.wrap(os.makedirs) # as in aiof... |
144805 | from __future__ import unicode_literals, print_function, absolute_import, division, generators, nested_scopes
import unittest
from jsonpath_ng.lexer import JsonPathLexer
from jsonpath_ng.parser import JsonPathParser
from jsonpath_ng.jsonpath import *
class TestParser(unittest.TestCase):
# TODO: This will be much ... |
144832 | import pandas as pd
from .constants import *
def compare_frameworks(results_raw, frameworks=None, banned_datasets=None, folds_to_keep=None, filter_errors=True, verbose=True, columns_to_agg_extra=None, datasets=None):
columns_to_agg = [DATASET, FRAMEWORK, PROBLEM_TYPE, TIME_TRAIN_S, METRIC_ERROR]
if columns_t... |
144835 | r"""undocumented
用于辅助生成 fastNLP 文档的代码
"""
__all__ = []
import inspect
import sys
def doc_process(m):
for name, obj in inspect.getmembers(m):
if inspect.isclass(obj) or inspect.isfunction(obj):
if obj.__module__ != m.__name__:
if obj.__doc__ is None:
# prin... |
144864 | import moai.utils.engine as mieng
import omegaconf.omegaconf
import logging
log = logging.getLogger(__name__)
__all__ = ["Latent_Visualizers"]
class LatentVisualizers(mieng.Collection, mieng.Interval):
def __init__(self,
batch_interval:int,
visualizers: omegaconf.DictConfig,
latent_visua... |
144890 | import numpy as np
import pytest
from ome_zarr.scale import Scaler
class TestScaler:
@pytest.fixture(
params=(
(1, 2, 1, 256, 256),
(3, 512, 512),
(256, 256),
),
ids=["5D", "3D", "2D"],
)
def shape(self, request):
return request.param
... |
144946 | import random
import types
import typing
import torch
class Preprocessing(object):
def __init__(self, augmentation: str='hvr') -> None:
self.augmentation = augmentation
return
def _apply(self, f: typing.Callable, **kwargs) -> dict:
applied = {k: f(v) for k, v in kwargs.items()}
... |
144955 | from .source_gateway import SourceGateway
from .meta_source_gateway import MetaSourceGateway
from .source_service import SourceService
|
144969 | import sys, os, pytest
sys.path.append('.')
import submit
output_worked = 'Your submission has been accepted and will be graded shortly.'
from io import StringIO
class TestCorrectMetadata:
def test_001(self):
meta_data = submit.load_metadata('test/_coursera')
assert len(meta_data.part_data) == ... |
144986 | from ..serializer import Serializable
from .performance import PerformanceInfo
from .message import Message
class Response(Serializable):
"""
Response from chatbot
Attributes
----------
messages : list of minette.Message
Response messages
headers : dict
Response header
per... |
144994 | import cv2
import sys, os, glob, re
import json
from os.path import join, dirname, abspath, realpath, isdir
from os import makedirs
import numpy as np
from shutil import rmtree
from ipdb import set_trace
from .bench_utils.bbox_helper import rect_2_cxy_wh, cxy_wh_2_rect
def center_error(rects1, rects2):
"""Center e... |
145046 | import os
import pytest
from helpers.runner import generate_project, run_main
from helpers.cli import cmdout
TEST_MODULE = """import lemoncheesecake.api as lcc
@lcc.suite("My Suite")
@lcc.prop("suite_prop", "suite_prop_value")
@lcc.tags("suite_tag")
@lcc.link("http://bug.tra.cker/1234", "#1234")
class mysuite:
... |
145125 | from .mapper import ApiResponse, ApiResponseInterface
from .mapper.types import Timestamp, AnyType
from .model import SharedFollower
__all__ = ['SharedFollowersResponse']
class SharedFollowersResponseInterface(ApiResponseInterface):
users: [SharedFollower]
class SharedFollowersResponse(ApiResponse, SharedFollo... |
145171 | import sys
import numpy as np
import skvideo.io
import concurrent.futures
import time
def _detect_black_bars_from_video(frames, blackbar_threshold=16, max_perc_to_trim=.2):
"""
:param frames: [num_frames, height, width, 3]
:param blackbar_threshold: Pixels must be this intense for us to not trim
:param... |
145180 | from __future__ import absolute_import
import ctypes
from .._base import _LIB
from .. import ndarray as _nd
def cross_entropy(y, y_, out, stream=None):
assert isinstance(y, _nd.NDArray)
assert isinstance(y_, _nd.NDArray)
assert isinstance(out, _nd.NDArray)
_LIB.DLGpuCrossEntropy(
y.handle, y_... |
145205 | from module.princess import unitproc
from module.image import proc
import cv2
report = cv2.imread("assets/b.png") # 讀取圖片
report = proc.preprocessing(report) # 中央視窗裁剪
report = proc.report_processing(report) # 傷害報告類型圖片處理
char_list = unitproc.process(report) # 角色頭像鎖定
for char in char_list:
objUnit = unitproc.unit(ch... |
145212 | from flask import jsonify
from utils.endpoint import Endpoint, setup
from random import choice
@setup
class YoMomma(Endpoint):
"""
This endpoint only returns a yo momma joke. No parameters are required.
"""
params = []
def generate(self, avatars, text, usernames, kwargs):
choices = ['Yo ... |
145215 | import unicodedata
encodings = 'ascii latin1 cp1252 cp437 gb2312 utf-8 utf-16le'.split()
widths = {encoding:1 for encoding in encodings[:-3]}
widths.update(zip(encodings[-3:], (2, 4, 4)))
chars = sorted([
'A', # \u0041 : LATIN CAPITAL LETTER A
'¿', # \u00bf : INVERTED QUESTION MARK
'Ã', # \u00c3 : LAT... |
145218 | from twentyc.rpc import RestClient
from twentyc.rpc.client import NotFoundException, PermissionDeniedException
from peeringdb import get_backend
from peeringdb.resource import Network
from . import _data
# try: from peeringdb import _debug_http
# except: pass
__data = {Network: {20: _data.twentyc}}
class Fetcher(... |
145239 | from botocore.exceptions import ClientError
import boto3
import json
import sys
POLICY_DOCUMENT = {
"Statement":[
{
"Action": ["dynamodb:Scan", "dynamodb:Query"],
"Effect": "Allow",
"Resource": "*"
},
{
"Action":[
"ec2:Describe*"
... |
145265 | from decimal import Decimal
import pickle
import pytest
import simplejson
from toloka.client import TolokaClient
import toloka.client as client
from .testutils.util_functions import check_headers
@pytest.fixture
def random_url():
return 'https://testing.toloka.yandex.ru'
def test_client_create_exceptions(ran... |
145311 | import numpy as np
import scipy
from ... import spectrum
from ... import utilits as ut
def ica_kurtosis(x, order, mode = 'full'):
'''
FUNCTION IN TEST
Max-kurtosis Independent Component Analysis (ICA)
References
------------------------
[1] http://www.cs.nyu.edu/~roweis/kica.html
... |
145357 | from i3pystatus.updates import Backend
import sys
# Remove first dir from sys.path to avoid shadowing dnf module from
# site-packages dir when this module executed directly on the CLI.
__module_dir = sys.path.pop(0)
try:
import dnf
HAS_DNF_BINDINGS = True
except ImportError:
HAS_DNF_BINDINGS = False
finall... |
145380 | from typing import List, Dict, Set
import pandas as pd
from ray.data import Dataset
from ray.ml.preprocessor import Preprocessor
class OrdinalEncoder(Preprocessor):
"""Encode values within columns as ordered integer values.
Currently, order within a column is based on the values from the fitted
dataset... |
145397 | import requests
from celery import Celery
from celery.schedules import crontab
from bhagavad_gita_api.config import settings
app = Celery(
"cronjobs",
broker=settings.CELERY_BROKER,
backend=settings.CELERY_BACKEND,
)
app.conf.timezone = "Asia/Calcutta"
@app.task
def set_verse():
url = "{}/v2/set-dai... |
145410 | import os
import sys
sys.path.append(os.path.join(os.getcwd(), '../common'))
from runner_helper2 import *
def get_fgnn_logtable():
return LogTable(
num_row=18,
num_col=4
).update_col_definition(
col_id=0,
definition='epoch_time:sample_total'
).update_col_definition(
... |
145437 | import os
import numpy as np
import json
import logging
from pipeline_monitor import prometheus_monitor as monitor
from pipeline_logger import log
import tensorflow as tf
from tensorflow.contrib import predictor
_logger = logging.getLogger('pipeline-logger')
_logger.setLevel(logging.INFO)
_logger_stream_handler = lo... |
145444 | import pytest
from mock import Mock
from botocore.exceptions import NoCredentialsError
from formica import cli
from tests.unit.constants import STACK, STACK_ID, PROFILE, REGION, CHANGESETNAME, EVENT_ID
@pytest.fixture
def logger(mocker):
return mocker.patch('formica.cli.logger')
def test_catches_common_aws_ex... |
145465 | from django.conf import settings
from django.core.mail import EmailMessage
try:
from django.urls import reverse
except:
from django.core.urlresolver import reverse
def send(to,subject,body):
from_email_address = settings.EMAIL_HOST_USER
if '@' not in from_email_address:
from_email_address = set... |
145485 | from database.mariadb import Database
from broker.fxcm.session import FXCMBroker
from threading import Thread
from queue import Queue, Empty
from subprocess_reader import SubprocessReader
import sys
import time
class SubprocessWorker(object):
def __init__(self, offer):
self._s = input
self._q = Qu... |
145493 | import os
import numpy as np
import json
import random
from PIL import Image
from PIL import ImageDraw
import torch
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
class DatasetBase(Dataset):
"""Base dataset for VITON-GAN.
"""
def __init__(self, opt, mode, data_... |
145494 | T = int(input())
for x in range(1, T + 1):
N = int(input())
names = [input() for index in range(N)]
y = 0
previous = names[0]
for name in names[1:]:
if name < previous:
y += 1
else:
previous = name
print(f"Case #{x}: {y}", flush = True)
|
145502 | import mmcv
import numpy as np
import pytest
from os import path as osp
from mmdet3d.core.bbox import DepthInstance3DBoxes
from mmdet3d.datasets.pipelines import (LoadAnnotations3D, LoadPointsFromFile,
LoadPointsFromMultiSweeps)
def test_load_points_from_indoor_file():
sun... |
145510 | import iotbx.phil
import iotbx.file_reader
import iotbx.reflection_file_utils
from cctbx.array_family import flex
from mmtbx.scaling.absolute_scaling import kernel_normalisation
from yamtbx import util
from yamtbx.util.xtal import CellConstraints
from yamtbx.dataproc.xds import xds_ascii
import collections
master_pa... |
145511 | import numpy as np
from collections import deque
import random
class Buffer:
def __init__(self, max_size=1000, seed=None):
self.buffer = deque(maxlen=max_size)
self.max_size = max_size
random.seed(seed)
@property
def size(self):
return len(self.buffer)
def sam... |
145524 | from django.db.backends.base.creation import BaseDatabaseCreation
from django.db.backends.utils import truncate_name
class DatabaseCreation(BaseDatabaseCreation):
def sql_table_creation_suffix(self):
test_settings = self.connection.settings_dict['TEST']
assert test_settings['COLLATION'] is None, ... |
145566 | import tensorflow as tf
import scipy.misc
import model
import cv2
from subprocess import call
import driving_data
import time
import TensorFI as ti
sess = tf.InteractiveSession()
saver = tf.train.Saver()
saver.restore(sess, "save/model.ckpt")
img = cv2.imread('steering_wheel_image.jpg',0)
rows,cols = img.shape
smoot... |
145603 | import click
import frida
from frida.core import Session, Device, Script
allow_script = "js/allow.js"
signature_script = "js/signature.js"
patche10_script = "js/patch_e10.js"
class FridaWrapper:
def __init__(self, device: Device, session: Session):
self.device = device
self.session = session
... |
145614 | from dassl.engine import TRAINER_REGISTRY,TrainerXU
from dassl.data import DataManager
from torch.utils.data import Dataset as TorchDataset
from dassl.optim import build_optimizer, build_lr_scheduler
from dassl.utils import count_num_param
import torch
import torch.nn as nn
from torch.nn import functional as F
from das... |
145651 | import os
import errno
try:
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
except:
from PySide.QtCore import *
from PySide.QtGui import *
def printText(text, name="Print"):
QMessageBox.warning(QWidget(), str(name), str(text))
def mkdir_p(path):
... |
145679 | from pathlib import Path
from textwrap import dedent
from jupyter_client.kernelspec import find_kernel_specs
SUPPORTED_FILE_SUFFIXES = [".ipynb", ".md", ".markdown", ".myst", ".Rmd", ".py"]
def _filename_to_title(filename, split_char="_"):
"""Convert a file path into a more readable title."""
filename = Path... |
145705 | add_pointer_input = {
"type": "object",
"additionalProperties": False,
"properties": {"pointer": {"type": "string"}, "weight": {"type": "integer"}, "key": {"type": "string"}},
"required": ["pointer", "weight"],
}
remove_pointer_input = {
"type": "object",
"additionalProperties": False,
"prop... |
145717 | import os
import xml.dom.minidom
import Lp_FrontEndFunctions
import Lp_UserInterface
import textwrap
def parseIface(mod,architecture,lpArch):
curDir=os.getcwd()
modName=mod.split('/')[len(mod.split('/'))-1]
modStripped=modName.split('_')[0]
modStripped=modStripped.split('.')[0]
modPath = find... |
145719 | import copy
import numpy as np
import timeit
import torch
import torch.nn as nn
from torch.utils.data import BatchSampler, SubsetRandomSampler
import rl_sandbox.constants as c
from rl_sandbox.algorithms.cem.cem import CEMQ
from rl_sandbox.auxiliary_tasks.auxiliary_tasks import AuxiliaryTask
class GRAC:
def __i... |
145736 | import functools
import getpass
import json
import click
from click_didyoumean import DYMMixin
from click_help_colors import HelpColorsGroup
api_key_option = click.option(
"--apiKey",
"api_key",
help="API key to use this time only",
)
def del_if_value_is_none(dict_):
"""Remove all elements with valu... |
145762 | import json
import os
from requests.auth import HTTPBasicAuth
from moneywagon.core import (
Service, NoService, NoData, ServiceError, SkipThisService, currency_to_protocol,
decompile_scriptPubKey
)
from bitcoin import deserialize
import arrow
from bs4 import BeautifulSoup
import re
import hmac, hashlib, time... |
145801 | from pydantic import BaseModel
from icolos.core.workflow_steps.schrodinger.base import StepSchrodingerBase
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import shortest_path
from icolos.utils.enums.step_enums import StepFepPlusEnum
from typing import List
import time
import os
from ic... |
145805 | from scipy.linalg import toeplitz
import numpy as np
from cooltools.lib.numutils import LazyToeplitz
n = 100
m = 150
c = np.arange(1, n + 1)
r = np.r_[1, np.arange(-2, -m, -1)]
L = LazyToeplitz(c, r)
T = toeplitz(c, r)
def test_symmetric():
for si in [
slice(10, 20),
slice(0, 150),
slic... |
145820 | from ._lambdification import (
DUMMY_TIME_SYMBOL,
lambdify,
LambdifiedArrayExpressions,
LambdifiedMatrixExpressions,
LambdifiedVectorExpressions,
LambdifiedArrayExpression,
LambdifiedMatrixExpression,
LambdifiedVectorExpression,
LambdifiedScalarExpression
)
from .utilities import fi... |
145857 | import sys
from .__version__ import __author__, __author_email__, __title__, __url__, __version__
from .hpm import (
DoubleAssignmentException,
EmptyValue,
HyperParameterManager,
NotLiteralEvaluable,
NotLiteralNameException,
SourceHelper,
)
from .hpm_db import (
HyperParameterDB,
HyperP... |
145875 | self.description = "Install a package with an existing file matching a negated --overwrite pattern"
p = pmpkg("dummy")
p.files = ["foobar"]
self.addpkg(p)
self.filesystem = ["foobar*"]
self.args = "-U --overwrite=foobar --overwrite=!foo* %s" % p.filename()
self.addrule("!PACMAN_RETCODE=0")
self.addrule("!PKG_EXIST=... |
145882 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="dolores",
version="1.0.3",
author="<NAME>, <NAME>, DNE LLC",
author_email="<EMAIL>",
description="Dolores is a Python library for developers using GPT-3.",
long_description=long_descri... |
145888 | import os
import math
import shutil
import torch
from utils import ensure_dir, Early_stopping
class BaseTrainer:
""" Base class for all trainer.
Note:
Modify if you need to change logging style, checkpoint naming, or something else.
"""
def __init__(self, model, loss, vocab, optimizer, epochs... |
145906 | import numpy as np
import torch
import torch.nn as nn
from ....ops.iou3d_nms import iou3d_nms_utils
class CenterTargetLayer(nn.Module):
def __init__(self, roi_sampler_cfg):
super().__init__()
self.roi_sampler_cfg = roi_sampler_cfg
def forward(self, batch_dict):
"""
Args:
... |
145911 | import datetime
from unittest.mock import MagicMock
import pytest
from bloop.models import BaseModel, Column
from bloop.stream.coordinator import Coordinator
from bloop.stream.stream import Stream
from bloop.types import Integer, String
from bloop.util import ordered
from . import build_shards
@pytest.fixture
def ... |
145915 | import math
class Solution:
def constructRectangle(self, area: int) -> List[int]:
W = int(math.sqrt(area))
while area % W:
W -= 1
return [area//W, W]
|
145923 | import csv
import os
import re
import sys
import pandas as pd
try:
import geocoder
except ImportError:
print("[ERROR] Unable to import Geocoder module: cant'run! Exit...")
sys.exit()
try:
import common_utils as cu
except ImportError:
print("[ERROR] Unable to import 'common_utils' module! Exit...")
... |
145925 | from pymatgen.ext.matproj import MPRester
# Change "<APIKEY>" to the API key obtained from MP.
mpr = MPRester("<APIKEY>")
data = mpr.query(criteria={"pretty_formula": "Al2O3"},
properties=["final_energy", "band_gap"])
print(data)
import pandas as pd
df = pd.DataFrame(data) # Convert to DataFrame |
145940 | import ajenti
from ajenti.api import *
from ajenti.plugins import *
info = PluginInfo(
title='Ajenti VH - NGINX Support',
icon='globe',
dependencies=[
PluginDependency('vh'),
PluginDependency('services'),
#BinaryDependency('nginx'),
],
)
def init():
from ajenti.plugins.vh... |
145960 | from m5.params import *
from m5.proxy import *
from MemObject import MemObject
# This is an interface module to attach the PIM to the memory interconnect
class ethz_PIMIF(MemObject):
type = 'ethz_PIMIF'
cxx_header = "mem/ethz_pim_if.hh"
slave = SlavePort('Slave port')
master = MasterPort('Master port')
system = ... |
145973 | import os
import time
from rsqueakvm import constants, error, wrapper
from rsqueakvm.model.character import W_Character
from rsqueakvm.model.compiled_methods import W_CompiledMethod, W_PreSpurCompiledMethod, W_SpurCompiledMethod
from rsqueakvm.model.display import W_DisplayBitmap
from rsqueakvm.model.numeric import W_... |
145976 | import time
from stacksampler import Sampler
def slp():
time.sleep(0.00001)
def fn():
for i in range(50000):
slp()
s = Sampler()
def test_foo():
s.start()
fn()
print s.output_stats()
if __name__ == '__main__':
test_foo()
|
145988 | import logging
from gehomesdk.erd.converters.abstract import ErdReadOnlyConverter
from gehomesdk.erd.converters.primitives import *
from gehomesdk.erd.values.laundry import ErdTumbleStatus
_LOGGER = logging.getLogger(__name__)
class TumbleStatusConverter(ErdReadOnlyConverter[ErdTumbleStatus]):
def erd_decode(sel... |
146005 | from pathlib import Path
import pytest
import pyfqmr
# Get the /example folder at the root of this repo
EXAMPLES_DIR = Path(__file__, "..", "..", "example").resolve()
def test_example():
import trimesh as tr
bunny = tr.load_mesh(EXAMPLES_DIR / 'Stanford_Bunny_sample.stl')
simp = pyfqmr.Simplify()
sim... |
146030 | from fastapi import FastAPI, HTTPException, Depends, Request
from fastapi.responses import JSONResponse
from fastapi_jwt_auth import AuthJWT
from fastapi_jwt_auth.exceptions import AuthJWTException
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
username: str
password: str
# in producti... |
146041 | version https://git-lfs.github.com/spec/v1
oid sha256:00d41c118e6c444c85be97ecd91f67088a2fd53b9c4398d2a9b0b9fd8b244979
size 2932
|
146087 | from gtfspy.import_loaders.table_loader import TableLoader, decode_six
class RouteLoader(TableLoader):
fname = 'routes.txt'
table = 'routes'
tabledef = '(route_I INTEGER PRIMARY KEY, ' \
'route_id TEXT UNIQUE NOT NULL, ' \
'agency_I INT, ' \
'name TEXT, ' \
... |
146117 | from pythran.tests import TestEnv
@TestEnv.module
class TestMath(TestEnv):
def test_cos_(self):
self.run_test("def cos_(a):\n from math import cos\n return cos(a)", 1, cos_=[int])
def test_exp_(self):
self.run_test("def exp_(a):\n from math import exp\n return exp(a)", 1, exp_=[int])
de... |
146188 | from rest_framework.test import APITestCase, APIClient
from src.utils.tests_utils import create_test_log
class TestViews(APITestCase):
def test_get_log_list(self):
create_test_log()
client = APIClient()
response = client.get('/logs/')
self.assertEqual(1, len(response.data))
d... |
146246 | from qcodes.instrument.base import Instrument
from qcodes.utils import validators as vals
from qcodes.instrument.parameter import ManualParameter
import numpy as np
class SimControlCZ_v2(Instrument):
"""
Noise and other parameters for cz_superoperator_simulation_v2
Created for VCZ simulation
"""
... |
146271 | from cipher_description import CipherDescription
def generate_speck_version(n,a,b):
speck = CipherDescription(2*n)
s = ['s{}'.format(i) for i in range(2*n)]
'''
if n == 16:
a = 7
b = 2
else:
a = 8
b = 3
'''
x = s[n:]
y = s[:n]
if n%a==0:
... |
146283 | import os
import numpy as np
from stompy.spatial import field
datadir=os.path.join( os.path.dirname(__file__), 'data')
#depth_bin_file = '/home/rusty/classes/research/spatialdata/us/ca/suntans/bathymetry/compiled2/final.bin'
def test_xyz():
depth_bin_file = os.path.join(datadir,'depth.xyz')
f = field.XYZT... |
146314 | import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import kornia
from codes.models.resnet import resnet18
import matplotlib
from codes.models.region_proposal_network import RegionProposalNetwork
import cv2
from codes.EX_CONST import Const
import matplotlib.pyplot as plt
mat... |
146381 | from whispers.plugins.uri import Uri
from whispers.rules import WhisperRules
class StructuredDocument:
def __init__(self, rules: WhisperRules):
self.breadcrumbs = []
self.rules = rules
def traverse(self, code, key=None):
"""Recursively traverse YAML/JSON document"""
if isinsta... |
146472 | import logging
from collections import namedtuple
from typing import Optional, Dict, Callable, Any
from auth.authorization import Authorizer, is_same_user
from auth.user import User
from execution.executor import ScriptExecutor
from model import script_config
from model.model_helper import is_empty, AccessProhibitedEx... |
146506 | from smartnlp.classfication.svm_classifier import SVMClassifier
if __name__ == '__main__':
svm_model = SVMClassifier('model/svm/model.pkl',
'./data/imdb/aclImdb.txt',
train=True)
# svm_model = SVMClassifier('model/svm/model.pkl')
svm_model.predict... |
146533 | from __future__ import unicode_literals
import re
import json
from .common import InfoExtractor
from ..compat import (
compat_urlparse,
)
from ..utils import (
ExtractorError,
get_element_by_id,
)
class SlideshareIE(InfoExtractor):
_VALID_URL = r"https?://(?:www\.)?slideshare\.net/[^/]+?/(?P<title>.... |
146541 | import numpy as np
import soundfile as sf
import argparse
import os
import keras
import sklearn
import librosa
from keras import backend as K
eps = np.finfo(np.float).eps
def class_mae(y_true, y_pred):
return K.mean(
K.abs(
K.argmax(y_pred, axis=-1) - K.argmax(y_true, axis=-1)
),
... |
146562 | import os.path
import yaml
from appr.auth import ApprAuth
def test_fake_home(fake_home):
assert os.path.expanduser("~") == fake_home
def test_init_create_dir(fake_home):
ApprAuth(".appr")
assert os.path.exists(os.path.join(str(fake_home), ".appr"))
def test_init_token_empty(fake_home):
k = ApprA... |
146579 | from calibre.customize import InterfaceActionBase
class ReadwisePlugin(InterfaceActionBase):
name = 'Readwise'
description = 'Export highlights to Readwise'
supported_platforms = ['windows', 'osx', 'linux']
author = '<NAME>'
version = (0, 1, 1)
minimum_calibre_version = (5, 0, 1)
actual_plugin = 'calibre... |
146618 | from argparse import ArgumentParser
def make_args():
parser = ArgumentParser()
# general
parser.add_argument('--comment', dest='comment', default='0', type=str,
help='comment')
parser.add_argument('--task', dest='task', default='link', type=str,
help='link... |
146626 | from messagebird.base import Base
from messagebird.base_list import BaseList
class CallFlowList(BaseList):
def __init__(self):
self._data = None
self._pagination = None
super(CallFlowList, self).__init__(CallFlow)
@property
def data(self):
return self._data
@propert... |
146632 | import os
import json
with open(os.path.abspath(os.path.dirname(__file__) + '/config.json'), 'r') as f:
raw_config = json.load(f)
class TestConfig:
def setEnvironment(self,test_env):
config = {}
config["botName"] = raw_config["botName"]
if test_env == 'development':
test_en... |
146672 | import tf
import numpy as np
""" convert multicam_calib transforms to tagslam format:
example session:
ipython
import numpy as np
from convert_transforms import multicam_to_tagslam
%load_ext autoreload
%autoreload 2
# copy T_cn_cnm1 from multicam_calibration file:
T=np.array([[0.99995273841, 0.00284628684, 0.0092962... |
146679 | with open("vocab_origin.txt", "r") as f:
lines = f.readlines()
for i in range(185):
lines.append("<s_{}>".format(i))
with open("vocab.txt", "w") as f:
for line in lines:
f.write(line.strip() + "\n")
|
146706 | from .box_utils import *
from .seq_matcher import SeqBoxMatcher
from .detection import Detect
from .prior_box import PriorBox
|
146711 | import pytest
import os
from polyglotdb.io import inspect_orthography
from polyglotdb.exceptions import DelimiterError
from polyglotdb import CorpusContext
def test_load_spelling_no_ignore(graph_db, text_spelling_test_dir):
spelling_path = os.path.join(text_spelling_test_dir, 'text_spelling.txt')
parser =... |
146717 | import numpy as np
import torch
import torch.nn as nn
from .utils import register_model, get_model
from . import cos_norm_classifier
@register_model('MannNet')
class MannNet(nn.Module):
"""Defines a Dynamic Meta-Embedding Network."""
def __init__(self, num_cls=10, model='LeNet', src_weights_init=None,
... |
146723 | import time
from collections import deque
import torch
import numpy as np
from ... import mohex, hex
from . import json, analysis
from .. import common
from rebar import arrdict
from pavlov import stats, runs, logs
from logging import getLogger
import activelo
import pandas as pd
from functools import wraps
from contex... |
146811 | from hparams import *
from sklearn.externals import joblib
from keras.optimizers import Adam
from sklearn.externals import joblib
from model.tacotron_model import get_tacotron_model
# import prepared data
decoder_input_training = joblib.load('data/decoder_input_training.pkl')
mel_spectro_training = joblib.load('data/m... |
146815 | import os
import sys
from px import px
def test_run_on_pid(capfd):
"""
Just run px on a PID.
The only verification done here is that it doesn't crash,
there is room for improvement...
"""
argv = [
sys.argv[0],
"--no-pager", # Paging causes problems on Travis CI
# Not... |
146825 | import falcon
import jinja2
from .base import BaseResource
from .html import read
class LoginResource(BaseResource):
'''Falcon resource for user authentication'''
auth_required = False
def __init__(self, *args, **kwargs):
super(LoginResource, self).__init__(*args, **kwargs)
def on_get(self,... |
146854 | import os.path as op
from pylama.check_async import check_async
from pylama.config import parse_options
from pylama.core import filter_errors, parse_modeline, run
from pylama.errors import Error, remove_duplicates
from pylama.hook import git_hook, hg_hook
from pylama.main import shell, check_path
def test_filter_err... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.