id
stringlengths
3
8
content
stringlengths
100
981k
466980
import collections import re import inspect import copy from functools import wraps from flask import request from flask_restful import Resource, reqparse, inputs # python3 compatibility try: basestring except NameError: basestring = str class ValidationError(ValueError): pass def auth(api_key, endpo...
467047
import dataclasses import datetime import json from decimal import Decimal from typing import Iterator, Any, Union INFINITY = float('inf') class Decoder(json.JSONDecoder): def __init__(self): super().__init__(parse_int=Decimal, parse_float=Decimal) class Encoder(json.JSONEncoder): def __init__(self...
467083
import os #################################################### # Extract value from split list of data #################################################### def get_value(lst, row_name, idx): """ :param lst: data list, each entry is another list with whitespace separated data :param row_name: name of the ro...
467096
import json import math import sys from collections import deque from glob import glob from typing import Optional import cv2 import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np # use the master branch of nuscenes-devkit instead of pip installed version import torch from fire import Fire from ...
467099
import pypy import py from pypy.interpreter.astcompiler.test.test_compiler import \ compile_with_astcompiler class TestStdlib: def check_file_compile(self, filepath): space = self.space print 'Compiling:', filepath source = filepath.read() compile_with_astcompiler(source...
467101
from terra_sdk.core import AccAddress, Coins from ._base import BaseAsyncAPI, sync_bind __all__ = ["AsyncBankAPI", "BankAPI"] class AsyncBankAPI(BaseAsyncAPI): async def balance(self, address: AccAddress) -> Coins: """Fetches an account's current balance. Args: address (AccAddress):...
467103
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import gzip import hashlib import io import logging import os import re import sys from collections import Counter from collections import defaultdict from contextlib import contextmanager import js...
467108
import logging import socket from threading import Thread from QRServer.game.gameclient import GameClientHandler from QRServer.game.gameserver import GameServer log = logging.getLogger('game_listener') def game_listener(conn_host, conn_port): log.info('Game starting on ' + conn_host + ':' + str(conn_port)) ...
467154
from io import BytesIO from mimetypes import guess_type import requests def get_image(url): ''' Get the image at the provided URL and returns a file-like buffer containing its bytes, and its MIME type. ''' resp = requests.get(url) if not resp.ok: raise RuntimeError( 'Failed...
467165
import numpy as np from automix.rules.rule import Rule from automix.utils import quantization class EventsAlignmentRule(Rule): """ The structure of the tracks should be aligned TODO: change to the loop instead of the segments ? """ def __init__(self, event="boundaries"): raise Deprecatio...
467169
import os from setuptools import setup def package_files(directory): paths = [] for (path, directories, filenames) in os.walk(directory): for filename in filenames: paths.append('/'.join(os.path.join(path, filename).split('/')[1:])) return paths extra_files = package_files('panda/da...
467189
import insightconnect_plugin_runtime from .schema import ConfigurationCommandsInput, ConfigurationCommandsOutput, Component, Input, Output import netmiko from insightconnect_plugin_runtime.exceptions import PluginException class ConfigurationCommands(insightconnect_plugin_runtime.Action): def __init__(self): ...
467193
import random while True: player = input("stone, paper, scissor? : ") computer = random.choice(['stone' , 'paper' , 'scissor']) if player == computer: print("Tie!") elif player == "stone": if computer == "paper": print(" You lose! :( " , computer , "covers " , player) ...
467216
import os import setuptools with open("README.md", "r") as fh: long_description = fh.read() about = {} with open(os.path.join("django_graphene_permissions", "__version__.py")) as f: exec(f.read(), about) setuptools.setup( name="django_graphene_permissions", version=about["__version__"], author="<NAME>", a...
467217
import igv_notebook from urllib.parse import urlparse from os.path import basename from IPython import get_ipython from .navbar import show_navbar # Attempt to import nbtools, if it's not installed create a dummy decorator that does nothing try: from nbtools import build_ui except ImportError: def build_ui(*a...
467236
from torchmeta.datasets.triplemnist import TripleMNIST from torchmeta.datasets.doublemnist import DoubleMNIST from torchmeta.datasets.cub import CUB from torchmeta.datasets.cifar100 import CIFARFS, FC100 from torchmeta.datasets.miniimagenet import MiniImagenet from torchmeta.datasets.omniglot import Omniglot from torch...
467239
from datetime import timedelta, tzinfo, datetime import re TIMEDELTA_ZERO = timedelta(0) DATETIME_RE = re.compile( r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})' r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})' r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?' r'(?P<tzinfo>Z|[+-]\...
467269
from plugin.core.filters import Filters from plugin.core.helpers.variable import merge from plugin.managers.core.base import Get, Manager, Update from plugin.managers.core.exceptions import ClientFilteredException from plugin.models import Client, ClientRule from exception_wrappers.libraries import apsw from plex impo...
467345
from typing import Tuple, Dict import aiohttp from pyot.pipeline.handler import ErrorHandler from pyot.pipeline.token import PipelineToken from pyot.endpoints.merakicdn import MerakiCDNEndpoint from pyot.utils.parsers import safejson from pyot.utils.logging import Logger from pyot.utils.nullsafe import _ from .base i...
467352
from .functions import vtos, stov class ModelFile: def __init__(self, filename, mode='r'): self.__fp = open(filename, mode) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.__fp.close() return False def write(self, x): ...
467370
import tensorflow as tf from detector.constants import BATCH_NORM_MOMENTUM, BATCH_NORM_EPSILON, DATA_FORMAT def batch_norm_relu(x, is_training, use_relu=True, name=None): x = tf.layers.batch_normalization( inputs=x, axis=1 if DATA_FORMAT == 'channels_first' else 3, momentum=BATCH_NORM_MOMENTUM, ep...
467382
import pytest import torch from ludwig.modules import metric_modules @pytest.mark.parametrize("preds", [torch.arange(6).reshape(3, 2).float()]) @pytest.mark.parametrize("target", [torch.arange(6, 12).reshape(3, 2).float()]) @pytest.mark.parametrize("output", [torch.tensor(6).float()]) def test_rmse_metric(preds: tor...
467425
import copy import itertools from enum import IntEnum from .config import Config class Urgency(IntEnum): LOW = 0 MEDIUM = 1 CRITICAL = 2 class Notification: __slots__ = ( "id", "app_name", "app_icon", "body", "summary", "actions", "created_at...
467434
import unittest from unittest import mock from django.core.exceptions import ValidationError class TestValidationError(unittest.TestCase): def test_messages_concatenates_error_dict_values(self): message_dict = {} exception = ValidationError(message_dict) self.assertEqual(sorted(exception....
467447
import multiprocessing import tensorflow as tf from tensorflow.python.ops.signal.fft_ops import ifft2d, fft2d, fft, ifft def tf_mp_ifft(kspace): k_shape_x = tf.shape(kspace)[-1] batched_kspace = tf.reshape(kspace, (-1, k_shape_x)) batched_image = tf.map_fn( ifft, batched_kspace, pa...
467470
from typing import Dict, List, Any import json from bech32 import convertbits, bech32_encode from pytest import raises import e2e.Libs.Ristretto.Ristretto as Ristretto from e2e.Classes.Transactions.Transactions import Send, Data, Transactions from e2e.Classes.Consensus.SpamFilter import SpamFilter from e2e.Meros.RP...
467485
import json from typing import List from model.transaction import Transaction from model.wallet import Wallet class Portfolio: def __init__(self): self.wallets = {} def add_transactions(self, transactions: List[Transaction]): for transaction in transactions: if transaction.walle...
467495
import nltk import spacy class Lang: def __init__(self): self.unk_idx = 0 self.pad_idx = 1 self.sou_idx = 2 self.eou_idx = 3 self.word2index = {'__unk__': self.unk_idx, '__pad__': self.pad_idx, '__sou__': self.sou_idx, '__eou__': self.eou_idx} self.word2count = {'_...
467521
def extractQxbluishWordpressCom(item): ''' Parser for 'qxbluish.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('gtvftbv', 'Guide The Villain Father To Be Virtuous', ...
467547
from decimal import Decimal def ensure_type(value, types): if isinstance(value, types): return value else: raise TypeError('Value {value} is {value_type}, but should be {types}!'.format( value=value, value_type=type(value), types=types)) class Token: def __init__(self, weight: ...
467589
import pytest from markdown_it import MarkdownIt @pytest.mark.parametrize( "input,expected", [ ("#", "<h1></h1>\n"), ("###", "<h3></h3>\n"), ("` `", "<p><code> </code></p>\n"), ("``````", "<pre><code></code></pre>\n"), ("-", "<ul>\n<li></li>\n</ul>\n"), ("1.", ...
467595
from seldon_e2e_utils import ( initial_rest_request, retry_run, to_resources_path, wait_for_rollout, wait_for_status, ) def test_xss_escaping(namespace): sdep_name = "mymodel" sdep_path = to_resources_path("graph-echo.json") retry_run(f"kubectl apply -f {sdep_path} -n {namespace}") ...
467597
from __future__ import absolute_import, unicode_literals from django.conf import settings from django.core.files import File from django.core.files.storage import default_storage import os import subprocess from celery import shared_task from videokit.apps import VideokitConfig @shared_task def generate_video(file...
467621
import os import time import atexit from django.contrib.auth.models import User from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium import webdriver; from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver import Rem...
467630
from context import arkouda as ak import numpy as np import pandas as pd from time import time from base_test import ArkoudaTest def compare_strategies(length, ncat, op, dtype): keys = ak.randint(0, ncat, length) if dtype == 'int64': vals = ak.randint(0, length//ncat, length) elif dtype == 'bool': ...
467668
from __future__ import unicode_literals, division, print_function, absolute_import from builtins import zip import os import random import numpy as np from scipy.sparse import csr_matrix, lil_matrix from sklearn.svm import LinearSVC from sklearn.linear_model import LogisticRegression as logreg import sklearn.metrics as...
467688
import math import numpy as np def sum_circle(data, x, y, r): """Sum array values that fall within the given circle. Parameters ---------- data : numpy.ndarray The array to sum. x, y, r : float The center and radius of circle, in array coordinates. """ imin = math.floo...
467785
import morepath import {{ cookiecutter.package_name }} from webtest import TestApp as Client def test_root(): morepath.scan({{ cookiecutter.package_name }}) morepath.commit({{ cookiecutter.package_name }}.App) client = Client({{ cookiecutter.package_name }}.App()) root = client.get('/') assert ...
467796
from netforce.model import Model,fields,get_model class Settings(Model): _name="ecom2.settings" _string="Settings" _fields={ "delivery_slot_discount": fields.Decimal("Same Delivery Slot Discount"), "delivery_max_days": fields.Integer("Delivery Max Days"), "delivery_min_hours": field...
467806
from __future__ import annotations from typing import Any from dependency_injector.wiring import Container, Provide, inject from rich.style import Style from rich.text import Text from textual.layouts.grid import GridLayout from textual.views import GridView from textual.widget import Widget from textual.widgets impo...
467819
import base64 from collections import namedtuple import pytest KubeResult = namedtuple("KubeResult", ["data"]) # =========== # base secret # =========== def test_secret_get(gsecret): with pytest.raises(NotImplementedError) as exc: gsecret.get("foo") assert "" in str(exc.value) def test_secret_s...
467842
from ciscoconfparse import CiscoConfParse from pprint import pprint bgp_config = """ router bgp 44 bgp router-id 10.220.88.38 address-family ipv4 unicast ! neighbor 10.220.88.20 remote-as 42 description pynet-rtr1 address-family ipv4 unicast route-policy ALLOW in route-policy ALLOW out ! ! neighbor...
467911
import os import torch class BasenjiDataset(torch.utils.data.Dataset): def __init__(self, human_file, mouse_file): self._human_file = human_file self._mouse_file = mouse_file self._human_data = torch.load(self._human_file) self._mouse_data = torch.load(self._mouse_file) @prop...
467916
import logging as log import shutil import sys import time from pathlib import Path from halo import Halo from . import errors, utils from .stages import Source, SourceType def discover_implied_stage(filename, config, possible_dests=None): """ Use the mapping from filename extensions to stages to figure out...
467922
import psnr import ssim import os import sys import cv2 import scipy.misc import uqim_utils import numpy as np #import matlab.engine import cv2 import imgqual_utils from PIL import Image #author:yetian #time:2020/12/7 # ref_file = r'sample1.jpg' # dist_file = r'sample1_tmp.jpg' #ref_path = r'D:\underwaterImageDatese...
467924
import jax.numpy as jnp from jax import jit from jax.lax import scan @jit def erfcx(x): """erfcx (float) based on Shepherd and Laframboise (1981) Scaled complementary error function exp(-x*x) erfc(x) Args: x: should be larger than -9.3 Returns: jnp.array: erfcx(x) Note: ...
467943
from os.path import abspath, dirname from typing import Any, Sequence, Union import matplotlib.pyplot as plt import numpy as np from matplotlib.axes import Axes from matplotlib.gridspec import GridSpec from matplotlib.offsetbox import AnchoredText from numpy.typing import NDArray from sklearn.metrics import r2_score ...
467949
import torch import torch.nn as nn import torch.nn.functional as F from .attention import Attention from .residual_mlp import ResidualMLP from .shifted_softplus import ShiftedSoftplus from .swish import Swish from typing import Optional class NonlinearElectronicEmbedding(nn.Module): """ Block for updating ato...
467950
import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras import backend as K from keras.preprocessing import sequence import Levenshtein import pickle # The custom accuracy metric used for this task def accuracy(y_true, y_pred): y = tf.argmax(y_true, axis =- 1) ...
467956
import csv import tempfile import pytest from datarobot_batch_scoring.batch_scoring import run_batch_predictions from utils import PickableMock from datarobot_batch_scoring.reader import DETECT_SAMPLE_SIZE_SLOW def test_gzipped_csv(live_server, ui): base_url = '{webhost}/predApi/v1.0/'.format(webhost=live_serve...
468006
import numpy as np import robot_sim.robots.ur3_dual.ur3_dual as ur3ds import robot_con.ur.ur3_dual_x as ur3dx import motion.probabilistic.rrt_connect as rrtc import motion.optimization_based.incremental_nik as inik import manipulation.pick_place_planner as ppp import visualization.panda.world as wd class UR3DualHelper...
468018
import sys import vim from powerline.bindings.vim import vim_get_func, vim_getoption, environ, current_tabpage, get_vim_encoding from powerline.renderer import Renderer from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE from powerline.theme import Theme from powerline.lib.unicode import unichr, ...
468023
from __future__ import print_function class Sampler(object): def pretrain_begin(self, begin, end): pass def pretrain_end(self): pass def pretrain_begin_iteration(self): pass def pretrain_end_iteration(self): pass def online_begin(self, begin, end): pass ...
468030
from .Scheduler import * import numpy as np from copy import deepcopy class RLScheduler(Scheduler): def __init__(self): super().__init__() def selection(self): return self.RandomContainerSelection() def placement(self, containerIDs): return self.MaxFullPlacement(containerIDs)
468036
import unittest from quickbooks import QuickBooks from quickbooks.objects.estimate import Estimate class EstimateTests(unittest.TestCase): def test_unicode(self): estimate = Estimate() estimate.TotalAmt = 10 self.assertEquals(str(estimate), "10") def test_valid_object_name(self): ...
468059
import unittest from mal import Anime class TestAnime(unittest.TestCase): @classmethod def setUpClass(cls): cls.anime = Anime(1) def test_anime(self): self.assertEqual(self.anime.mal_id, 1) self.assertEqual(self.anime.title, "Cowboy Bebop") self.assertEqual(s...
468076
import unittest import numpy as np from arrus.utils.tests.utils import ArrusImagingTestCase from arrus.utils.imaging import ( FirFilter, BandpassFilter ) class FirFilterTestCase(ArrusImagingTestCase): def setUp(self) -> None: self.op = FirFilter self.context = self.get_default_context(...
468134
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import binary_sensor, esp32_ble_tracker from esphome.const import ( CONF_MAC_ADDRESS, CONF_SERVICE_UUID, CONF_IBEACON_MAJOR, CONF_IBEACON_MINOR, CONF_IBEACON_UUID, ) DEPENDENCIES = ["esp32_ble_tracker"] ble...
468141
import torch from overrides import overrides from allennlp.training.metrics.metric import Metric import torch.distributed as dist @Metric.register("vqa") class VqaMeasure(Metric): """Compute the VQA metric, as described in https://www.semanticscholar.org/paper/VQA%3A-Visual-Question-Answering-Agrawal-Lu/97ad...
468163
from typing import NewType from web3._utils.compat import TypedDict Drip = NewType('Drip', int) class SponsorInfo(TypedDict): sponsorBalanceForCollateral: int sponsorBalanceForGas: int sponsorGasBound: int sponsorForCollateral: str sponsorForGas: str
468168
import os # These imports are here so that when we evaluate parameters we have access to the functions from math import * import numpy as n class EvaluatedParams(dict): """ Stores parameters that have been evaluated and ensures consistency of default parameters if defaults are used in multiple places or ...
468205
from contextlib import contextmanager class SQLite3DriverAdapter(object): @staticmethod def process_sql(_query_name, _op_type, sql): """Pass through function because the ``sqlite3`` driver already handles the :var_name "named style" syntax used by anosql variables. Note, it will also accept "q...
468220
import os import subprocess from rubicon_ml.exceptions import RubiconException from rubicon_ml.repository import LocalRepository, MemoryRepository, S3Repository class Config: """Used to configure `rubicon` client objects. Configuration can be specified (in order of precedence) by: 1. environment var...
468247
import multiprocessing import time import cotyledon class Manager(cotyledon.ServiceManager): def __init__(self): super(Manager, self).__init__() queue = multiprocessing.Manager().Queue() self.add(ProducerService, args=(queue,)) self.printer = self.add(PrinterService, args=(queue,)...
468286
import argparse import json import os from multiprocessing.sharedctypes import Value from pathlib import Path from shutil import copyfile from web3.main import Web3 from web3.middleware import geth_poa_middleware from moonworm.crawler.ethereum_state_provider import Web3StateProvider from moonworm.watch import watch_c...
468315
import random import numpy as np import torch import torch.nn.functional as F def floyed(r): """ :param r: a numpy NxN matrix with float 0,1 :return: a numpy NxN matrix with float 0,1 """ r = np.array(r) N = r.shape[0] for k in range(N): for i in range(N): for j in range...
468316
import torch from torch import nn from torch import Tensor class Convolution(nn.Module): def __init__(self, _in: int, _out: int, kernel_size: int, residual: bool): """ 기본적인 Convolution - BN - Relu 블럭입니다. :param _in: 입력 채널 사이즈 :param _out: 출력 채널 사이즈 :param kernel_size: 커널 ...
468327
from . import any_drivers from . import io_tam from . import tam_surface from . import tam_colors from . import tam_drivers from . import tam_identifier from . import tam_keys from . import uni_drivers from . import win_drivers from . import ansi_256_drivers from . import ansi_true_color_drivers from . import tcp_io fr...
468337
import torch from collections import OrderedDict from score_following_game.reinforcement_learning.algorithms.a2c import A2CAgent from score_following_game.reinforcement_learning.algorithms.agent import Agent from score_following_game.reinforcement_learning.torch_extentions.distributions.adapted_categorical import Adap...
468425
import typing as tp from abc import ABC, abstractmethod import httpx class BaseCache(ABC): @abstractmethod def get(self, request: httpx.Request) -> tp.Optional[httpx.Response]: """Get cached response from Cache. We use the httpx.Request.url as key. Args: request: httpx.R...
468436
from contextlib import contextmanager from typing import NamedTuple import pytest import trio from libp2p.exceptions import ValidationError from libp2p.pubsub.pb import rpc_pb2 from libp2p.pubsub.pubsub import PUBSUB_SIGNING_PREFIX, SUBSCRIPTION_CHANNEL_SIZE from libp2p.tools.constants import MAX_READ_LEN from libp2p...
468442
import os import sys import apache_beam.options.pipeline_options as pipeline_options class PipelineCLIOptions(pipeline_options.StandardOptions, pipeline_options.WorkerOptions, pipeline_options.SetupOptions, pipeline_options.GoogleCloudOptions)...
468551
import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = os.path.abspath(os.path.join(BASE_DIR,os.pardir,'Data')) ROOT_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir))
468594
from . import loss_functional as LF import torch def l1(params): return branched_loss(LF.l1_loss, params) def l2(params): return branched_loss(LF.l2_loss, params) def l1_attention(params): return branched_loss(LF.l1_attention_loss, params) def branched_loss(loss_function, params): """ Args ...
468608
import csv import re from collections import defaultdict from os.path import join from ngs_utils import logger from ngs_utils.file_utils import verify_file, verify_dir, adjust_path from ngs_utils.utils import OrderedDefaultDict import vcf_stuff.filtering.ngs_reporting.reference_data as filt_ref_data from vcf_stuff.fi...
468621
import unittest from airmozilla.search.split_search import split_search class Test(unittest.TestCase): def shortDescription(self): return None def test_basic(self): """ one free text part, two keywords """ keywords = ('to', 'from') q = "Peter something to:AAa aa from:Foo bar...
468622
from openmdao.api import Problem,IndepVarComp,ScipyOptimizeDriver from Classes import Vflutter from time import * import os name = ctime() os.makedirs(name) os.chdir(name) objectif='mVflutter' # opposite of the critical speed (first unstable mode, either divergence or flutter) Ori1Dep = 42 Ori2Dep = 42 Start = time...
468635
import json import logging import os import sys LOG = logging.getLogger(__name__) runtimeValues = {} # Depth of credscan credscan_depth = "2" DEPSCAN_CMD = "/usr/local/bin/depscan" # Flag to disable telemetry DISABLE_TELEMETRY = False # Telemetry server if required here TELEMETRY_URL = "" """ Supported language...
468687
from typing import List, Tuple from rlbench.backend.task import Task from typing import List from rlbench.backend.task import Task from rlbench.const import colors from rlbench.backend.conditions import NothingGrasped, DetectedCondition from rlbench.backend.spawn_boundary import SpawnBoundary import numpy as np from py...
468728
import compas_rrc as rrc if __name__ == "__main__": # Create Ros Client ros = rrc.RosClient() ros.run() # Create ABB Client abb = rrc.AbbClient(ros, "/rob1") print("Connected.") # Set tool abb.send(rrc.SetTool("tool0")) # Set work object abb.send(rrc.SetWorkObject("wobj0")) ...
468766
import random from schafkopf.game_modes import NO_GAME from schafkopf.players.player import Player class RandomPlayer(Player): """Random Player that never declares a game mode and randomly plays cards""" def choose_game_mode(self, options, public_info): return (NO_GAME, None) def play_card(self, ...
468784
x = 7 y = 11 print("x={}, y={}".format(x, y)) # swap: nonpythonic # temp = x # x = y # y = temp y, x = x, y print("x={}, y={}".format(x, y))
468795
from multiprocessing import * from ctypes import * def f(): print(1) # string_at(1) print(2) if __name__ == '__main__': p = Process(target=f) p.start() p.join() print(3, p.exitcode)
468827
from pkg_resources import parse_version import os, requests # The default namespace for our tagged container images DEFAULT_TAG_NAMESPACE = "adamrehn" class GlobalConfiguration(object): """ Manages access to the global configuration settings for ue4-docker itself """ @staticmethod def getLatest...
468854
from hamcrest.library.text.substringmatcher import SubstringMatcher from hamcrest.core.helpers.hasmethod import hasmethod __author__ = "<NAME>" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class StringContains(SubstringMatcher): def __init__(self, substring): super(...
468887
import io import csv import glob import os.path import constants import re import sys import itertools import operator # for getbds4opt4start() import subprocess, shlex import errno # for makedir() # check character string def is_None_empty_whitespace(mystr): if mystr and mystr.strip(): # mystr is not None AND mys...
468892
import sys; sys.path.append('..') # make sure that pylsl is found (note: in a normal program you would bundle pylsl with the program) import pylsl import random import time # first create a new stream info (here we set the name to BioSemi, the content-type to EEG, 8 channels, 100 Hz, and float-valued data) # The last...
468900
from flask_wtf import FlaskForm from wtforms import BooleanField, HiddenField, StringField, SubmitField, ValidationError from wtforms.validators import Length, NumberRange, Required from .. models import LookupValue class LookupValueForm(FlaskForm): name = StringField("Name", validators = [Required(), Length(1, 45)])...
468905
from django.db import models from wagtailstreamforms.models import AbstractFormSetting, Form from ..test_case import AppTestCase from . import ValidFormSettingsModel class ModelGenericTests(AppTestCase): fixtures = ["test"] def test_abstract(self): self.assertTrue(AbstractFormSetting._meta.abstract...
468918
from lib.models.gupnet import GUPNet def build_model(cfg,mean_size): if cfg['type'] == 'gupnet': return GUPNet(backbone=cfg['backbone'], neck=cfg['neck'], mean_size=mean_size) else: raise NotImplementedError("%s model is not supported" % cfg['type'])
468921
import math from chempy import Reaction from chempy.units import allclose, default_units as u from ..testing import requires from ..rendering import eval_template from ..parsing import get_parsing_context from chempy.units import units_library @requires(units_library) def test_eval_template(): rendered = eval_tem...
468974
import enum class EncodingStatusValues(enum.Enum): RUNNING = 'RUNNING' QUEUED = 'QUEUED' CREATED = 'CREATED' FINISHED = 'FINISHED' ERROR = 'ERROR'
469033
import _init_paths import os.path as osp import os import numpy as np from sacred import Experiment import torch from torch.autograd import Variable import torch.nn.functional as F import cv2 from PIL import Image import matplotlib.pyplot as plt from model.config import cfg as frcnn_cfg from tracker.config import g...
469045
import gzip import orjson from somajo import SoMaJo from tqdm import tqdm import argparse tokenizer = SoMaJo("de_CMC") # see https://github.com/tsproisl/SoMaJo/issues/17 def detokenize(tokens): out = [] for token in tokens: if token.original_spelling is not None: out.append(token.origina...
469079
class PNMessageCountResult(object): def __init__(self, result): """ Representation of message count server response :param result: result of message count operation """ self._result = result self.channels = result['channels'] def __str__(self): return "M...
469089
import itertools from omegaconf import OmegaConf def bifpn_config(min_level, max_level, weight_method=None): """BiFPN config. Adapted from https://github.com/google/automl/blob/56815c9986ffd4b508fe1d68508e268d129715c1/efficientdet/keras/fpn_configs.py """ p = OmegaConf.create() weight_method = we...
469092
from typing import List import pytest from gym.spaces import Discrete from stable_baselines3.common.envs import IdentityEnv from sb3_contrib.common.wrappers import ActionMasker class IdentityEnvDiscrete(IdentityEnv): def __init__(self, dim: int = 1, ep_length: int = 100): """ Identity environmen...
469113
import os, sys parent_dir = os.path.sep.join(os.path.abspath(__file__).split(os.path.sep)[:-2]) sys.path.append(parent_dir) from fsl import main assert len(sys.argv) == 9 script, windowsSDK, dst, binary_dst, src, lang, compile, verbose, config = sys.argv windowsSDKPaths = windowsSDK.split(';') if windowsSDKPaths: ...
469124
import sublime, sublime_plugin, json from urllib import urlopen CFLIBCATS = r"http://www.cflib.org/api/api.cfc?method=getlibraries&returnformat=json" CFLIBUDFS = r"http://www.cflib.org/api/api.cfc?method=getudfs&returnformat=json&libraryid=" CFLIBUDF = r"http://www.cflib.org/api/api.cfc?method=getudf&returnFormat=json...
469207
from django.contrib import admin from .models import DoorStatus, OpenData @admin.register(DoorStatus) class DoorStatusAdmin(admin.ModelAdmin): fieldsets = [ ( "Status", { "fields": [ "name", "datetime", "s...