id
stringlengths
3
8
content
stringlengths
100
981k
11539422
def count(data, var=None, globvar=None): if var: try: _ttp_["parser_object"].vars[var] += 1 except KeyError: _ttp_["parser_object"].vars[var] = 1 if globvar: try: _ttp_["global_vars"][globvar] += 1 except KeyError: _ttp_["global_va...
11539428
import unittest from socketlabs.injectionapi.message.customheader import CustomHeader from socketlabs.injectionapi.message.bulkrecipient import BulkRecipient from socketlabs.injectionapi.core.sendvalidator import * from socketlabs.injectionapi.message.basicmessage import BasicMessage from socketlabs.injectionapi.mes...
11539439
from pathlib import Path from alfasim_sdk._internal.alfacase import case_description def generate_alfacase_file( alfacase_description: case_description.CaseDescription, alfacase_file: Path ) -> None: """ Dump the case_description to the given alfacase_file, using YAML format. PvtModels that are of m...
11539481
from collections import namedtuple from functools import partial from types import MethodType from durations.parser import extract_tokens from durations.scales import Scale from durations.exceptions import ScaleFormatError from durations.constants import * DurationRepresentation = namedtuple( 'DurationRepresenta...
11539494
import pytest import os dbm = pytest.importorskip('dbm') def test_get(tmpdir): path = str(tmpdir.join('test_dbm_extra.test_get')) d = dbm.open(path, 'c') x = d.get("42") assert x is None d.close() def test_delitem(tmpdir): path = str(tmpdir.join('test_dbm_extra.test_delitem')) d = dbm.o...
11539496
import maya.cmds as mc import maya.mel as mm def ui(): ''' ''' # Window win = 'graphFilterUI' if mc.window(win,q=True,ex=True): mc.deleteUI(win) win = mc.window(win,t='Graph Editor Filter',mxb=True,mnb=True,s=True,wh=[248,210]) # Layout fl = mc.formLayout(numberOfDivisions=100) # UI Elements graphFilter...
11539500
from jitcache import Cache import time import multiprocessing as mp cache = Cache() @cache.memoize def slow_fn(input_1, input_2): print("Slow Function Called") time.sleep(1) return input_1 * input_2 n_processes = 10 process_list = [] # Create a set of processes who will request the same value for i i...
11539581
import logging import os from typing import List from xml.etree import ElementTree as ET from dug import utils as utils from ._base import DugElement, FileParser, Indexable, InputFile logger = logging.getLogger('dug') class NIDAParser(FileParser): # Class for parsers NIDA Data dictionary into a set of Dug Eleme...
11539631
from pygame import Rect from albow.resource import get_image class ImageArray(object): def __init__(self, image, shape): self.image = image self.shape = shape if isinstance(shape, tuple): self.nrows, self.ncols = shape else: self.nrows = 1 self.n...
11539632
import pathlib from . import config from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider from cassandra.cqlengine import connection BASE_DIR = pathlib.Path(__file__).resolve().parent SOURCE_DIR = BASE_DIR / 'ignored' if not SOURCE_DIR.exists(): SOURCE_DIR = BASE_DIR / 'decrypted' ...
11539661
import json from datetime import datetime from std_bounties.constants import STANDARD_BOUNTIES_V1, STANDARD_BOUNTIES_V2, STANDARD_BOUNTIES_V2_1, STANDARD_BOUNTIES_V2_2, STANDARD_BOUNTIES_V2_3, STANDARD_BOUNTIES_V2_4 def to_serializable(val): """JSON serializer for objects not serializable by default""" if i...
11539703
import pytest # type: ignore from typing import Any from trio_typing import TaskStatus import trio import trio.testing from .. import open_service_nursery async def test_basic(autojump_clock: trio.testing.MockClock) -> None: record = [] async with open_service_nursery() as nursery: @nursery.start_s...
11539709
import logging, os, sys, json, torch import torch.nn as nn from torch.utils.data.dataset import Dataset from torch.utils.data import DataLoader from torch.nn import MSELoss, CrossEntropyLoss import pytorch_lightning as pl from transformers import AutoTokenizer, AutoModelForTokenClassification, AutoConfig, Trainer, Trai...
11539739
import numpy as np import tensorflow as tf import elbow.util as util from elbow.structure import unpackRV from elbow.conditional_dist import ConditionalDistribution from elbow.transforms import DeterministicTransform from elbow.elementary import Gaussian,BernoulliMatrix def layer(inp, w, b): if len(inp.get_shap...
11539750
from typing import List, Optional, Union, overload, Tuple, Type import warnings import torch import xitorch as xt import dqc.hamilton.intor as intor from dqc.df.base_df import BaseDF from dqc.df.dfmol import DFMol from dqc.hamilton.base_hamilton import BaseHamilton from dqc.hamilton.orbconverter import OrbitalOrthogona...
11539757
import sys import ppp4py.protocol.base class Protocol (ppp4py.protocol.base.Protocol): Protocol = 0x404F ProtocolID = 'P4' ProtocolName = 'PppPrintf' def process (cls, information): sys.stdout.write(cls.Decode(information)) @classmethod def Decode (cls, information): return 'L...
11539849
import numpy as np class parameterRobot(object): def __init__(self, defaultFolder = ""): self.defaultFolder = defaultFolder self.setReadStat() self.setGenomeStat() self.setThresholdPara() self.genome = False self.longOnly = False def setReadSta...
11539875
import unittest from typing import cast from unittest.mock import MagicMock import logging from waves_gateway.service import AddressValidationService, ChainQueryService, TransactionConsumer from waves_gateway.storage import MapStorage, WalletStorage, TransactionAttemptListStorage from waves_gateway.common import Wav...
11539885
import pytest from typing import List from tests.globals.constants import NUMBER_OF_DOCUMENTS from tests.globals.document import pandas_document @pytest.fixture(scope="session") def pandas_documents() -> List: return [pandas_document() for _ in range(NUMBER_OF_DOCUMENTS)]
11539917
from urllib.parse import urlparse class UrlNormalizer: @staticmethod def _parse_sheme(parse, base_parse): if not parse.scheme: uri = base_parse.scheme else: uri = parse.scheme return uri + '://' @staticmethod def _parse_netloc(parse, base_parse): ...
11539983
import torch import numpy as np from deepflow.mrst_coupling import PytorchMRSTCoupler, load_production_data, load_gradients from deepflow.storage import create_dataset from deepflow.utils import set_seed, load_generator, print_header from deepflow.utils import slerp, get_latent_vector from deepflow.losses import comp...
11539984
import logging from anytree import RenderTree from colorama import Fore, init from .analyzer import TableNode, ViewAnalyzer log = logging.getLogger("bqva.analyzer") init(autoreset=True) def color(color: str, text: str) -> str: return color + text + Fore.RESET def format_key() -> str: return f""" Key: {c...
11540014
from continual import rehearsal from continual import classifier from continual import vit from continual import convit from continual import utils from continual import scaler from continual import cnn from continual import factory from continual import sam from continual import samplers from continual import mixup
11540033
import numpy as np a = np.arange(12).reshape(3, 4) print(a) ''' [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] ''' print(a.T) #転置 ''' [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]] ''' b = np.arange(24).reshape(2, 3, 4) print(b) # 3 次元 array ''' [[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] ...
11540036
import argparse import collections import pandas import numpy as np import os import gym from keras.models import Sequential, Model from keras.layers import Dense, Activation, Flatten, Input, Concatenate from keras.optimizers import Adam import tensorflow as tf from rl.agents import NAFAgent from rl.memory import Seq...
11540037
from abc import abstractmethod, ABC from typing import Tuple, Optional from torch.utils.data import Dataset, ConcatDataset # Hydra and OmegaConf from hydra.conf import dataclass from omegaconf import MISSING # Project Imports from slam.common.projection import SphericalProjector from slam.dataset.sequence_dataset im...
11540045
from waflib import TaskGen# import feature, taskgen_method, before_method, task_gen from waflib import Node, Task, Utils, Build import subprocess from waflib import Options import shellcmd #shellcmd.subprocess = pproc # the WAF version of the subprocess module is supposedly less buggy from waflib.Logs import debug, e...
11540054
import numpy as np import pandas as pd import yfinance as yf import matplotlib.pyplot as plt from sklearn.mixture import GaussianMixture import datetime ticker = input('Enter a ticker: ') index = 'SPY' num_of_years = 5 start = datetime.date.today() - datetime.timedelta(days = int(365.25*num_of_years)) yf_prices = yf...
11540112
import os import pickle as pkl import argparse import re import json import numpy as np import nltk from collections import defaultdict def generate_answer_nl(in_dir, dtype): with open(os.path.join(in_dir, '{}_answer.src'.format(dtype)),'r') as f: subgraph_answer = f.readlines() ans_list = [] fo...
11540128
import subprocess # Intel MKL number of threads numThreads = '16' baseCommand += 'export MKL_NUM_THREADS=' + numThreads + '\nexport OMP_NUM_THREADS=' + numThreads + '\nexport VECLIB_MAXIMUM_THREADS=' + numThreads + '\n' # run for script in ['12-14_normal_flow.py']: for meshName in ['cat']: for smoothInten...
11540138
import sys sys.path.append('.') import cfg import async_session while True: sess = async_session.AsyncSession(cfg.timeout_read) sess.open_session() oid = async_session.oid_str_to_tuple('1.3.6.1.2.1.1.1') try: sess.get_next(oid) except async_session.SNMPTimeoutError: pass
11540142
from framework.deprecated.controllers import AdvCommScheduler, CheckpointDriving, MathScheduler, AudioRewardLogic, VisualSearchTask from framework.latentmodule import LatentModule from framework.convenience import ConvenienceFunctions from framework.ui_elements.EventWatcher import EventWatcher from framework.ui_element...
11540147
from django.db import models class ReportingAgencyTas(models.Model): """ Model representing reporting data for appropriation and object class program activity values grouped by TAS and period """ reporting_agency_tas_id = models.AutoField(primary_key=True) toptier_code = models.TextField() ...
11540151
import json import io from PythonBridge.object_registry import registry mapper = {} def addMapping(key_type, mapping_function): mapper[key_type] = mapping_function class JsonEncoder(json.JSONEncoder): def __init__(self, *args, **kwargs): json.JSONEncoder.__init__(self, *args, **kwargs) self.m...
11540163
import glycowork from glycowork.motif.annotate import * glycans = ['Man(a1-3)[Man(a1-6)][Xyl(b1-2)]Man(b1-4)GlcNAc(b1-4)[Fuc(a1-3)]GlcNAc', 'Man(a1-2)Man(a1-2)Man(a1-3)[Man(a1-3)Man(a1-6)]Man(b1-4)GlcNAc(b1-4)GlcNAc', 'GalNAc(a1-4)GlcNAcA(a1-4)[GlcN(b1-7)]Kdo(a2-5)[Kdo(a2-4)]Kdo(a2-6)GlcOPN(b1-6...
11540197
from neuron import h, crxd as rxd import numpy import __main__ name = __main__.__file__ if name[-3:] == ".py": name = name[:-3] h.load_file("stdrun.hoc") dend1 = h.Section() dend1.diam = 2 dend1.nseg = 101 dend1.L = 50 dend2 = h.Section() dend2.diam = 2 dend2.nseg = 101 dend2.L = 50 dend2.connect(dend1) diff_co...
11540198
import os from sys import stdout STYLE = {'None' : '0', 'bold' : '1', 'disable' : '2', 'underline' : '4', 'blink' : '5', 'reverse' : '7', 'invisible' : '8', 'strike' : '9'} FG = {'None' : '', 'gray' : ';30', 'red' : ';31', 'green' : ';32', 'yellow': ';33', 'blue' : ';3...
11540217
import logging import os # Skip bson in requirements , pymongo provides # noinspection PyPackageRequirements from bson import decode_file_iter from bson.codec_options import CodecOptions from mongodb_consistent_backup.Errors import Error from mongodb_consistent_backup.Oplog import Oplog from mongodb_consistent_backup....
11540235
from __future__ import print_function import sys, os import argparse import json from random import random from conrob_pybullet.ss_pybullet.pybullet_tools.utils import connect, disconnect, wait_for_user, LockRenderer, \ has_gui, remove_body, set_camera_pose, get_movable_joints, set_joint_positions, \ wait_for_...
11540247
import py from rpython.jit.backend.test.runner_test import LLtypeBackendTest from rpython.jit.backend.llgraph.runner import LLGraphCPU class TestLLTypeLLGraph(LLtypeBackendTest): # for individual tests see: # ====> ../../test/runner_test.py def get_cpu(self): return LLGraphCPU(None) def test...
11540461
import unittest from pixray import * class TestPixrayMethods(unittest.TestCase): def setup_test_parser(self): parser = argparse.ArgumentParser() return setup_parser(parser) def get_args_for_apply_overlay_test(self, overlay_image, overlay_every, overlay_offset, overlay_until): setti...
11540465
from typing import Dict, Optional, Union from .SchemaOption import SchemaOption from .SchemaOptionDefs import CustomTemplateDefs, SchemaOptionDefs class BooleanSchemaOption(SchemaOption): def __init__(self): self.when_true: Union[SchemaOptionDefs, CustomTemplateDefs, None] = None self.when_false:...
11540495
import torch import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP from dataloader import build_dataloader from utils import Config, setup_seed, configure_hardware from model.MMT4Caption import MMT4Caption from eval import v2t_batch, make_coco_sample, COCOScorer from tqdm impor...
11540508
from datetime import datetime, date, timedelta import unittest import moment import moment_parse # Helpful strftime() format that imcludes all parts of the date including the time zone. fmt = "%Y-%m-%d %H:%M:%S %Z" class TestMoment(unittest.TestCase): new_york = [ # - 1918 - [datetime(1918, 3, 31, 6, 59, 5...
11540554
from __future__ import absolute_import, division, print_function import telnyx TEST_RESOURCE_ID = "6a09cdc3-8948-47f0-aa62-74ac943d6c58" class TestCredentialConnection(object): def test_is_listable(self, request_mock): resources = telnyx.CredentialConnection.list() request_mock.assert_requested(...
11540562
from requests import Session from .lib import IN, web, zonekey URL = "https://core.ap.gov.in/CMDashBoard/UserInterface/Power/PowerReport.aspx" ZONE_KEY = "IN-AP" TIME_FORMAT = "DD-MM-YYYY HH:mm" SOURCE = "core.ap.gov.in" def fetch_production( zone_key=ZONE_KEY, session=None, target_datetime=None, logger=None ) ...
11540586
import pytest from silver.fixtures.pytest_fixtures import * # NOQA pytest.register_assert_rewrite('silver.tests.api.specs.document_entry') pytest.register_assert_rewrite('silver.tests.api.specs.utils')
11540617
import pytest import uvicore from typing import List from uvicore.support.dumper import dump # This is all failing due to my provider refactors @pytest.mark.asyncio async def test_package(app1): from uvicore.package.package import Package assert Package.__module__ + '.' + Package.__name__ == 'app1.overrides....
11540640
from flask_restful import Resource from datetime import datetime from model.FuzzingJobState import FuzzingJobState from model.FuzzingJob import FuzzingJob from model.FuzzingHost import FuzzingHost from model.FuzzingCrash import FuzzingCrash class StatusCtrl(Resource): def get(self): status_active = Fuzzing...
11540663
if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) k=([[i,j,l]for i in range(x+1) for j in range(y+1) for l in range(z+1) if (i+j+l!=n)]) print(k)
11540683
from .base import * from .box_space import * from .tuple_space import * from .dict_space import * from .concatenation_space import * from .axis_angle_space import * from .translation_axis_angle_space import *
11540712
from __future__ import unicode_literals from httoop import URI def test_simple_uri_comparision(uri): u1 = URI(b'http://abc.com:80/~smith/home.html') u2 = URI(b'http://ABC.com/%7Esmith/home.html') u3 = URI(b'http://ABC.com:/%7esmith/home.html') u4 = URI(b'http://ABC.com:/%7esmith/./home.html') u5 = URI(b'http://...
11540718
from sqlobject.dbconnection import DBAPI from sqlobject import col import re class MSSQLConnection(DBAPI): supportTransactions = True dbName = 'mssql' schemes = [dbName] limit_re = re.compile('^\s*(select )(.*)', re.IGNORECASE) def __init__(self, db, user, password='', host='localhost', port=Non...
11540721
from django.core.management.base import BaseCommand from 臺灣言語服務.models import 訓練過渡格式 class 匯入枋模(BaseCommand): def handle(self, *args, **參數): self.stdout.write('資料數量:{}'.format(訓練過渡格式.資料數量())) 訓練過渡格式.加一堆資料(self.全部資料(*args, **參數)) self.stdout.write('資料數量:{}'.format(訓練過渡格式.資料數量()))
11540732
from mock import patch from pytest import mark from invocations.environment import in_ci @mark.parametrize( "environ,expected", [ (dict(), False), (dict(WHATEVS="true", SURE_WHYNOT=""), False), (dict(CIRCLECI=""), False), (dict(TRAVIS=""), False), (dict(CIRCLECI="", WH...
11540802
from abc import ABC, abstractmethod from redbot.core import Config from redbot.core.bot import Red class MixinMeta(ABC): """Base class for well behaved type hint detection with composite class. Basically, to keep developers sane when not all attributes are defined in each mixin. """ def _...
11540836
import unittest from unittest import SkipTest import six from codetools.contexts.data_context import DataContext from codetools.contexts.multi_context import MultiContext class Events2TestCase(unittest.TestCase): """ Test events with the new contexts. """ def setUp(self): self.event_count = 0 ...
11540843
import random import argparse import json from common import EMPTY, AllKeyValueFactory, IntKeyValueFactory from dictinfo import dump_py_dict from dict_reimplementation import PyDictReimplementation32, dump_reimpl_dict from js_reimplementation_interface import Dict32JsImpl, AlmostPythonDictRecyclingJsImpl, AlmostPython...
11540845
import polars as pl __all__ = [ 'col', 'exclude', 'lit', 'Expr', 'Series', # dtypes 'Int8', 'Int16', 'Int32', 'Int64', 'UInt8', 'UInt16', 'UInt32', 'UInt64', 'Float32', 'Float64', 'Boolean', 'Utf8', 'List', 'Date', 'Datetime', 'Object' ] col = pl.col exclude = pl.exclude lit = pl.lit Expr = p...
11540862
import os import io import yaml from tcfcli.common.user_exceptions import ContextException from tcfcli.libs.utils.yaml_parser import yaml_parse class Template(object): @staticmethod def get_template_data(template_file): if not os.path.exists(template_file): return {} with io.open...
11540878
import os from behave.matchers import Match, ParseMatcher, RegexMatcher, MatchWithError from behave.matchers import matcher_mapping from collections import defaultdict import six from functools import partial class TransformerBase(object): """ Defines the basic functions of a Transformer As implemented, it...
11540885
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import time import pickle import numpy as np import math from config import args from loss_funcs.keypoints_loss import batch_kp_2d_l2_loss, ca...
11540918
from __future__ import print_function import io import os import re import stat import sys import zipfile from textwrap import dedent, fill import six from click import UsageError from click.testing import CliRunner from humanize import naturalsize from twisted.internet import endpoints, reactor from twisted.internet...
11540929
class Display: def showTemperature(self, temp_str): pass def showDutyCycle(self, duty_cycle): pass def showAutoMode(self, set_point): pass def showBoilMode(self): pass def showManualMode(self): pass def showOffMode(self): pass class LCD(Display): ...
11540953
import numpy as np from mpi4py import MPI from distdl.backends.mpi.partition import MPIPartition from distdl.nn.mixins.halo_mixin import HaloMixin from distdl.nn.mixins.pooling_mixin import PoolingMixin class MockPoolLayer(HaloMixin, PoolingMixin): pass def test_mixin(): P_world = MPIPartition(MPI.COMM_WO...
11541008
from pprint import pprint from fuzzy_logic.terms import Term from fuzzy_logic.variables import FuzzyVariable, SugenoVariable, LinearSugenoFunction from fuzzy_logic.sugeno_fs import SugenoFuzzySystem from fuzzy_logic.mf import TriangularMF t1: Term = Term('mf1', TriangularMF(0, 0, 0.5)) t2: Term = Term('mf2', Triangula...
11541056
from abc import ABC, abstractmethod from typing import Dict, Any import contextvars from esphome.types import ConfigFragmentType, ID, ConfigPathType import esphome.config_validation as cv class FinalValidateConfig(ABC): @property @abstractmethod def data(self) -> Dict[str, Any]: """A dictionary t...
11541063
from rodan.models import WorkflowJobGroup from rodan.serializers.workflow import version_map from django.conf import settings from rest_framework import serializers from rodan.serializers import TransparentField class WorkflowJobGroupSerializer(serializers.HyperlinkedModelSerializer): appearance = TransparentFie...
11541074
import torch from torch import nn class BaseEmbedding(nn.Module): def get_loss(self): return None def forward(self, **kwargs): raise NotImplementedError def train(self, mode=True): self.training = mode if self.trainable and mode: super().train() retur...
11541081
import webbrowser class Tabla(): def write(self,entorno,tree): input = "<html>" + '\n' + "<head>" + '\n' + "<title>Reporte Gramatical</title>" + '\n' + "</head>" + '\n' input = input + "<body bgcolor=\"white\">" + '\n' + "<center><Font size=12 >" + "Tabla de simbolos" + "</Font></center>" + '\...
11541096
import numpy as np import matplotlib.pyplot as plt def log_barrier_aux_eval_constraints(eval_f_const_inequality): """ Auxiliary function for evaluation of constraint inequalities in logarithmic barrier """ #get values that are nonnegative through indexes idx_zeros = np.logical_and(eval_f_const_...
11541098
from random import shuffle import os import sys def patch_path(path): return os.path.join(os.path.dirname(__file__), path) def load_audio_path_label_pairs(max_allowed_pairs=None): from mxnet_audio.library.utility.gtzan_loader import download_gtzan_genres_if_not_found download_gtzan_genres_if_not_found(p...
11541111
import random import string def vault_from_glacier_url(full_url): return full_url.split("/")[-1] def get_job_id(): return "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(92) )
11541115
from typing import Any, List, Tuple from pytest import fixture, mark from pytest_lazyfixture import lazy_fixture as lz from arger.typing_utils import get_origin, match_types @fixture(params=[list, List, List[str], List[int], List[Any]]) def list_type(request): return request.param @fixture( params=[tuple,...
11541116
import subprocess import os.path import json import argparse import pathlib import logging import errno import getpass import datetime import time class LoopDevice: __lo_name: str = "" __offset: int = 0 __target: str = "" __has_setup: bool = False def __init__(self, target: str, offset: int): ...
11541155
import argparse import datetime import json import sys import boto3 import dateutil from boto3.dynamodb.conditions import Attr DB_KEY = "COMPUTE_FLEET" DB_DATA = "Data" COMPUTE_FLEET_STATUS_ATTRIBUTE = "status" COMPUTE_FLEET_LAST_UPDATED_TIME_ATTRIBUTE = "lastStatusUpdatedTime" def to_utc_datetime(time_in, default...
11541192
import platform from nspawn.wrapper.sudo import SUDO from nspawn.tool import stamp from nspawn.base.machine import * build_stamp = stamp.build_stamp() epoch = "3.10" release = f"{epoch}.3" hardware = platform.machine() image_url = f"file://localhost/tmp/nspawn/repo/alpine/base/default-{release}-{hardware}.tar.gz" boo...
11541203
import dis import opcode class InvalidConstantError(Exception): pass def const(**names): """Decorator to rewrite lookups to be constants @const(x=1) def func(): print(x) # prints 1 """ def decorate(func): # Constants are not allowed to be assigned to within the function. # Thus they should never appear in...
11541204
from scipy import interpolate import collections import numpy as np import os import re import torch import pylab as plt import matplotlib.ticker as mtick import math import itertools from tensorboard.backend.event_processing import event_accumulator def get_run_names(logdir, patterns): run_names = [] for pat...
11541222
import pytest import shutil from pathlib import Path from imageatm.scripts import run_cloud from imageatm.components.cloud import AWS TEST_JOB_DIR = Path('./tests/data/test_train_job').resolve() TEST_TF_DIR = 'test_tf_dir' TEST_REGION = 'test_region' TEST_INSTANCE_TYPE = 'test_instance_type' TEST_VPC_ID = 'test_vpc_i...
11541243
from pyglet_gui.sliders import Slider class ScrollBar(Slider): """ An abstract scrollbar with a specific knob size to be set. """ def __init__(self, width, height): Slider.__init__(self, width=width, height=height) # the size of the knob. Value runs from [_knob_size/2, 1 - _knob_size/...
11541255
import numpy as np from spanningtrees.heap import Heap class Edge(object): """ An Edge is between an ordered pair of nodes (src and tgt) and has an associated weight. It may optionally also have a label (in the case of multigraphs) """ __slots__ = 'src', 'tgt', 'weight', 'label' def __ini...
11541262
from RestrictedPython import compile_restricted_exec from RestrictedPython._compat import IS_PY3 from RestrictedPython._compat import IS_PY35_OR_GREATER import pytest YIELD_EXAMPLE = """\ def test_generator(): yield 42 """ def test_yield(): """`yield` statement should be allowed.""" result = compile_re...
11541277
class Blog: def __init__(self, id, owner_id, title): self.id = id self.owner_id = owner_id self.title = title
11541287
import asyncio import logging import random import socket import struct from ipaddress import IPv4Address from . import settings logger = logging.getLogger(__name__) class TrackerUDPProtocol(asyncio.DatagramProtocol): def __init__(self, cb, infohash): self.state = "connect" self.transport = None...
11541333
import getopt import logging import os import sys import tensorflow as tf from keras.preprocessing.sequence import pad_sequences from tinydb import TinyDB, where from model.lstm import buildModel from preprocessing.InputHelper import InputHelper from preprocessing.InputHelper import transformLabels # set logging LOG...
11541397
from typing import Dict, List import itertools from mypy.errors import Errors from mypy.errorcodes import ErrorCode from mypy.options import Options from mypy.plugin import FunctionContext, Plugin, CheckerPluginInterface from mypy.types import Instance, Type, CallableType, TypeVarType from mypy.nodes import Expression,...
11541456
from unittest import TestCase def find_friend(friend_dict): not_yet_checked = list(friend_dict.keys()) to_check = [] current_group = [] all_groups = [] while not_yet_checked: # get student to be checked if len(to_check) > 0: checking = to_check.pop() not_ye...
11541468
import pytest import numpy as np import scedar.cluster as cluster import scedar.eda as eda class TestCommunity(object): '''docstring for TestMIRAC''' np.random.seed(123) x_20x5 = np.random.uniform(size=(20, 5)) def test_simple_run(self): cluster.Community(self.x_20x5).labs def test_wro...
11541472
from flask import request, redirect, Response import urllib.parse import json class Origins(): endpoints = ["/api/origins"] endpoint_name = "api_origins" endpoint_methods = ["GET", "POST"] endpoint_default_parameters = { "method": "get" ...
11541474
from labelmodels.label_model import ClassConditionalLabelModel, LearningConfig, init_random import numpy as np from scipy import sparse import torch from torch import nn class HMM(ClassConditionalLabelModel): """A generative label model that treats a sequence of true class labels as a Markov chain, as in a hi...
11541496
import pypugjs from pypugjs.parser import Parser from pypugjs.nodes import Tag from typing import List from operator import itemgetter import ast class XMLElement: def __init__(self, tag: str, attrib: dict): self._tag = tag self._attrib = attrib self._children: List = [] self._...
11541513
import torch import numpy as np import numpy as np from scipy.spatial.transform.rotation import Rotation as R, Slerp from scipy.interpolate.interpolate import interp1d from slam.common.utils import assert_debug, check_tensor from slam.common.rotation import torch_euler_to_mat, torch_mat_to_euler, torch_pose_matrix_jac...
11541519
from __future__ import print_function import json import os import pickle import boto3 import tensorflow as tf from correct_text import create_model, DefaultMovieDialogConfig, decode_sentence from text_corrector_data_readers import MovieDialogReader def safe_mkdir(path): try: os.mkdir(path) except ...
11541522
import unittest import pandas as pd import nlu import tests.nlu_hc_tests.secrets as sct from sparknlp.annotator import BertSentenceEmbeddings from tests.test_utils import * class AssertionTests(unittest.TestCase): def test_assertion_dl_model(self): SPARK_NLP_LICENSE = sct.SPARK_NLP_LICENSE AW...
11541571
import praw import time import re # ### BOT CONFIGURATION ### # CONFIG_WIKIPAGE = "schedulebot-config" # ### END BOT CONFIGURATION ### # class ScheduledPost: def __init__(self, sub, first, title="Scheduled Post", text=None, link=None, repeat="-1", times="-1", flair_text="", flair_css="", distinguish="False", sticky=...
11541572
import pyromod.listen from pyrogram import Client, __version__ from pyrogram.raw.all import layer from DonLee_Robot_V2 import LOGGER, Config class User(Client): def __init__(self): super().__init__( Config.USER_SESSION, api_hash=Config.API_HASH, api_id=Config.API_ID, ...
11541574
import pathlib from daskperiment.core.errors import TrialIDNotFoundError import daskperiment.io.pickle as pickle from daskperiment.util.log import get_logger logger = get_logger(__name__) def init_backend(experiment_id=None, backend=None): """ Initialize backend from Experiment ID and protocol. Pramet...
11541581
from .object import MWDBElement, MWDBObject class MWDBShareReason(object): """ Represents the reason why object was shared with specified group """ def __init__(self, api, share_data): self.api = api self._data = share_data self._related_object = None @property def wha...
11541600
import os import boto3 def answer_no(x): return True if str(x).lower() in [ '0', 'no', 'false'] else False def answer_yes(x): return True if str(x).lower() in [ '1', 'yes', 'true'] else False def send_notifications(message): # TODO return True def is_bucket_not_public(bucket_name): s3 = boto...