id
stringlengths
3
8
content
stringlengths
100
981k
4889352
class Borg: _shared_state = {} def __init__(self): self.__dict__ = self._shared_state class MonostateSingleton(Borg): def __init__(self): Borg.__init__(self) self.name = "MySingleton" def get_name(self) -> str: return self.name def set_name(self, name: str): ...
4889361
from __future__ import unicode_literals from itertools import product from distutils.version import LooseVersion import numpy as np import matplotlib as mpl from matplotlib import cm from matplotlib.collections import LineCollection from matplotlib.dates import DateFormatter, date2num mpl_version = LooseVersion(mpl....
4889372
import pickle import warnings import numpy as np from stable_baselines.common.vec_env.base_vec_env import VecEnvWrapper from stable_baselines.common.running_mean_std import RunningMeanStd class VecNormalize(VecEnvWrapper): """ A moving average, normalizing wrapper for vectorized environment. It is pick...
4889407
from unittest import TestCase import numpy as np from cate.util.im.geoextent import GeoExtent # noinspection PyMethodMayBeStatic class GeoRectTest(TestCase): def test_init(self): rect = GeoExtent() self.assertEqual(rect.west, -180.) self.assertEqual(rect.south, -90.) self.assertE...
4889450
import os import cv2 import time import argparse import torch import warnings import numpy as np from detector import build_detector from deep_sort import build_tracker from utils.draw import draw_boxes from utils.parser import get_config from utils.log import get_logger from utils.io import write_results class Vide...
4889467
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * def find_largest_input_or_output(all_args_list) -> dict: max_arg = {'Size(MB)': 0} for arg in all_args_list: if arg.get('Size(MB)') > max_arg.get('Size(MB)'): max_arg = arg return max_a...
4889473
from tuvok import cli from helpers.wrap import Wrap class TestPlugins(object): def setup(self): self.main = cli.main def teardown(self): self.main = None def test_list_plugins(self, capsys): file = '--list-plugins' expected_checks = [ { 'check'...
4889490
import unittest from srp import Usuario #Se crea la suite unitaria de acuerdo al RGF class RGFTest(unittest.TestCase): # Red Test: Se crea una prueba unitaria la cual debe fallar. # def test_RS(self): # user = Usuario( # nombre='Ramanujan', # edad=25, # direcci...
4889505
from django.conf.urls.defaults import patterns from satchmo_store.shop.satchmo_settings import get_satchmo_setting ssl = get_satchmo_setting('SSL', default_value=False) urlpatterns = patterns('', (r'^$', 'payment.modules.cybersource.views.pay_ship_info', {'SSL':ssl}, 'CYBERSOURCE_satchmo_checkout-step2'), (...
4889525
import os from settings import settings import numpy as np import torch import argparse def get_total_number(inPath, fileName): with open(os.path.join(inPath, fileName), 'r') as fr: for line in fr: line_split = line.split() return int(line_split[0]), int(line_split[1]), int(line_sp...
4889526
from typing import ( Mapping, ) import unittest from moto import ( mock_sqs, mock_sts, ) from azul.logging import ( configure_test_logging, ) from health_check_test_case import ( HealthCheckTestCase, ) # noinspection PyPep8Naming def setUpModule(): configure_test_logging() class TestIndexe...
4889560
import typing from datetime import datetime class Action: def __init__(self, timestamp: datetime, tx_hash: str, block_number: str, swap_fee: str, denorms: typing.Dict, action_type: str, action: typing.List): self.timestamp = timestamp self.tx_hash = tx_hash self.block_number = block_number ...
4889568
from datetime import datetime from elasticsearch_dsl import Document, Date, Integer, Keyword, Text, Nested, Long class PaperES(Document): # ES mappings original_title = Text(analyzer="standard") abstract = Text(analyzer="standard") year = Keyword() publication_date = Date() citations = Integer...
4889580
from __future__ import print_function import functools import numpy as np from scipy.stats import norm as ndist import regreg.api as rr from .query import gaussian_query from .randomization import randomization class screening(gaussian_query): def __init__(self, observed_data, ...
4889588
import matplotlib.pyplot as plt import pytest from qm.qua import * from qm.QuantumMachinesManager import QuantumMachinesManager from qm import SimulationConfig import numpy as np from qualang_tools.bakery.bakery import baking from copy import deepcopy def gauss(amplitude, mu, sigma, length): t = np.lin...
4889606
import sys import os try: from __builtin__ import basestring except ImportError: basestring = str # Always inherit from the "build_ext" in distutils since setuptools already imports # it from Cython if available, and does the proper distutils fallback otherwise. # https://github.com/pypa/setuptools/blob/9f182...
4889607
from __future__ import annotations import decimal import functools import hashlib import re import struct from datetime import date, datetime from decimal import Decimal from typing import Callable, List, Optional, Union, Dict from jinsi.exceptions import NoMergePossible def hash_complex( value, *, algo="sh...
4889619
import unittest import numpy as np from scipy.ndimage.filters import correlate import prml.nn as nn class TestConvolve2d(unittest.TestCase): def test_convolve2d_forward(self): img = np.random.randn(1, 5, 5, 1) kernel = np.random.randn(3, 3, 1, 1) output = nn.convolve2d(img, kernel) ...
4889641
import itertools from sympy import (MatrixExpr, Expr, ShapeError, ZeroMatrix, Add, Mul, MatMul, S, expand as _expand) from sympy.stats.rv import RandomSymbol, is_random from sympy.core.sympify import _sympify from sympy.stats.symbolic_probability import Variance, Covariance, Expectation class Exp...
4889663
lr = 0.0001 batch_size = 128 # don't set batch_size = 1 neg_samples = 2 dimensions = 30 walk_length = 40 num_walks = 10 window_size = 10 p = 1 q = 1 n_layers = 1 bidirectional = True # the first encoder is not a bidirectional one dropout = 0.0 # for BIGRU-MAX-RES-N2V epochs = 1 max_pad = False # you can remove the ...
4889724
import numpy as np import networkx as nx from gensim.models import Word2Vec, KeyedVectors import random import time from .. import base_model, register_model, alias_draw, alias_setup @register_model("node2vec") class Node2vec(base_model.BaseModel): @staticmethod def add_args(parser): """Add model-spec...
4889852
from __future__ import absolute_import # pylint: disable=wildcard-import from reinforceflow.core.optimizer import * from reinforceflow.core.policy import * from reinforceflow.core.replay import * from reinforceflow.core.space import * from reinforceflow.core.stats import Stats, flush_stats # pylint: enable=wildcard-i...
4889860
import asyncio import time import numpy as np import xlwings as xw @xw.func(async_mode='threading') @xw.arg("n", numbers=int) @xw.arg("m", numbers=int) @xw.ret(expand='table') def threading(n, m): print('1 - CALLED THREADING FUNCTION') time.sleep(1) return [ ["%s x %s : %s, %s" % (n, m, i, j) fo...
4889878
from typing import Callable, Iterable, Mapping, Tuple, Union Filter = Callable[..., str] Filters = Union[Iterable[Tuple[str, Filter]], Mapping[str, Filter]]
4889906
import re import functools from eth_utils import ( is_string, coerce_args_to_text, pad_left, to_checksum_address, ) from web3.utils.validation import ( validate_address, ) def pad_left_hex(value, num_bytes): return pad_left(value, num_bytes * 2, '0') def iso13616Prepare(iban): """ ...
4889939
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, HiddenField from wtforms.validators import DataRequired class OrganisationForm(FlaskForm): org_id = HiddenField('_id') name = StringField('Name', validators=[DataRequired()]) address = StringField('Ad...
4890046
from .t5 import T5Configuration, T5Model, T5Tokenizer from .gpt import GPT2Model, GPT2Tokenizer, GPTConfiguration
4890081
from ..constants import * from .abstract import Metadata from typing import List class EOF(Metadata): def __init__(self, sparse: List[int], itc: int, commit_sha: str): super().__init__(None, None, EOF_NAME) self.sparse_checkpoints = sparse self.iterations_count = itc self.commit_s...
4890138
n = int(input()) coord = [] for i in range(n): coord.append(tuple([int(number) for number in input().split()])) x = [c[0] for c in coord] y = [c[1] for c in coord] print(sum(x)/n, sum(y)/n)
4890188
import logging logging.basicConfig(level=logging.DEBUG) # export SLACK_API_TOKEN=<KEY> # pip3 install sanic # python3 integration_tests/samples/readme/async_function_in_framework.py import os from slack_sdk.web.async_client import AsyncWebClient from slack_sdk.errors import SlackApiError client = AsyncWebClient(tok...
4890197
from mpl_toolkits.basemap import Basemap,shiftgrid import matplotlib.pyplot as plt import numpy as np import glob, math import pandas as pd import warnings, matplotlib.cbook warnings.filterwarnings("ignore", category=FutureWarning) from rfsks_support.plotting_libs import shoot, equi, plot_topo, plot_events_loc, plot_me...
4890202
from django.contrib import messages from django.forms import ValidationError from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from allauth.account import app_settings as account_settings from allauth.account.adapter import get_adapter as get_account_adapt...
4890211
import pytest import os from unittest import mock from tfx.components.base.base_component import BaseComponent from fluent_tfx import PipelineDef, \ ExampleInputs, SchemaInputs, HyperParameterInputs from fluent_tfx.pipeline_def import build_step from tfx.components.base import executor_spec from tfx.extensions.g...
4890231
import sys, os, json, urllib.request, urllib.parse, urllib.error, argparse TEST_SOURCE = "{%22query%22:{%22filtered%22:{%22query%22:{%22query_string%22:{%22query%22:%221893-3211%22,%22default_field%22:%22index.issn.exact%22,%22default_operator%22:%22AND%22}},%22filter%22:{%22bool%22:{%22must%22:%5B{%22term%22:{%22_typ...
4890266
import argparse import glob import os import shutil parser = argparse.ArgumentParser() parser.add_argument("-root", "--root_path", type=str, required=True) args = parser.parse_args() def main(): for p in glob.glob(os.path.join(args.root_path, "oneflow/*/")): if p.endswith("python/") or p.endswith("includ...
4890331
import convertapi import os import tempfile convertapi.api_secret = os.environ['CONVERT_API_SECRET'] # your api secret # Example of saving Word docx to PDF and to PNG # https://www.convertapi.com/docx-to-pdf # https://www.convertapi.com/docx-to-png # Use upload IO wrapper to upload file only once to the API upload_i...
4890406
from leapp.libraries import stdlib from leapp.models import InstalledRPM def get_installed_rpms(): rpm_cmd = [ '/bin/rpm', '-qa', '--queryformat', r'%{NAME}|%{VERSION}|%{RELEASE}|%|EPOCH?{%{EPOCH}}:{0}||%|PACKAGER?{%{PACKAGER}}:{(none)}||%|' r'ARCH?{%{ARCH}}:{}||%|DSAHEADER...
4890447
import os import time import numpy as np import torch import torch.nn as nn import torch.optim.optimizer from torch.optim import lr_scheduler from torch.utils.tensorboard import SummaryWriter class RAKINetwork: # The base network """ Network class. An object to wrap the network with all the methods. ...
4890571
import pytest from cocopot.utils import ConfigDict, cached_property import copy import traceback def test_config_isdict(): d, m = dict(), ConfigDict() d['key'], m['key'] = 'value', 'value' d['k2'], m['k2'] = 'v1', 'v1' d['k2'], m['k2'] = 'v2', 'v2' assert d.keys() == m.keys() assert list(d.val...
4890580
import pandas as pd import numpy as np from PIL import Image, ImageDraw import math import copy from shapely.ops import transform from shapely.geometry import mapping, Polygon, box, shape from skimage.transform import resize from skimage import io, filters, measure, color, morphology from scipy import ndimage from scip...
4890582
import regex from itertools import zip_longest from common import bilarasortkey class Num: """ >>> Num(1) Num('1') >>> Num('2a') Num('2a') >>> Num('1-10') Num('1-10') >>> Num('1') - Num('0') Num('1') >>> Num('2a') - Num('1') Num('1') >>> Num('1-10') - Num('0') ...
4890607
from dataproperty import Format from ._cell import Cell from ._font import FontSize, FontStyle, FontWeight from ._style import Align, Style, ThousandSeparator, VerticalAlign from ._styler import ( DecorationLine, GFMarkdownStyler, HtmlStyler, LatexStyler, MarkdownStyler, NullStyler, ReStruc...
4890619
import json import logging import unittest from unittest.mock import patch from i3wmthemer.models.configuration import Configuration from i3wmthemer.models.i3 import I3Theme from i3wmthemer.utils.fileutils import FileUtils logging.disable(logging.ERROR) class TestI3(unittest.TestCase): """ Tests for i3 mode...
4890634
import test_import test_import.test() import test_simple_reload test_simple_reload.test() import trashtest trashtest.run()
4890663
from django.core.management.base import BaseCommand from openkamer.dossier import create_or_update_dossier class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('dossier_id', nargs='+', type=str) def handle(self, *args, **options): # dossier_id = 33885 dos...
4890695
import pytest from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) node1 = cluster.add_instance("node1") node2 = cluster.add_instance("node2") @pytest.fixture(scope="module") def start_cluster(): try: cluster.start() for node in [node1, node2]: node.qu...
4890753
import abc class StorageBackend: __metaclass__ = abc.ABCMeta @abc.abstractmethod def already_visited_url(self, url): ''' @return True if the url has been visited already, False otherwise ''' raise NotImplemented() @abc.abstractmethod def save_url(self, url, match_...
4890805
import mxnet as mx import numpy as np from config import config from rcnn.PY_OP import fpn_roi_pooling, proposal_fpn, mask_roi, mask_output, proposal_fpn_out, rpn_fpn_ohem FPN = False USE_DCN=False def conv_act_layer(from_layer, name, num_filter, kernel=(1,1), pad=(0,0), \ stride=(1,1), act_type="relu", bias_wd_mu...
4890830
import contextlib import subprocess import sys class _pyexePopen(subprocess.Popen): if sys.version_info >= (3, ): def __init__(self, args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=getattr(subprocess, '_PLATFORM_...
4890842
import asyncio import os import time from functools import lru_cache from caio.asyncio_base import AsyncioContextBase chunk_size = 16 * 1024 # 1024 context_max_requests = 512 @lru_cache(1024) def open_file_by_id(file_id): fname = f"data/{file_id}.bin" return open(fname, "rb"), os.stat(fname).st_size asy...
4890875
import FWCore.ParameterSet.Config as cms matchGenHFHadron = cms.EDProducer("GenHFHadronMatcher", genParticles = cms.InputTag('genParticles'), jetFlavourInfos = cms.InputTag("genJetFlavourInfos"), flavour = cms.int32(5), onlyJetClusteredHadrons = cms.bool(True), noBBbarResonances = cms.bool(False), ...
4890944
import matplotlib.pyplot as plt import re import tools from tools import get_array, dags, defines, names path = tools.results_prompt("copy_compdecomp_sm") # Styling plt.style.use("seaborn") #plt.rc("font", family="serif", size=56) #plt.rc("axes", labelsize=18) #plt.rc("legend", fontsize=12) plt.rc("font", family="...
4891034
import socket, os, struct from ctypes import * host = "192.168.56.101" #consider adding a sys.argv def banner(): print "Decoding ICMP p43 " print "Uses code from the sniffer_ipheader_decoder.py tool" class IP(structure): #our IP header _fields_ = [ ("ihl", c_ubyte, 4), ("version", c_ubyte, 4), ("...
4891045
import pytest @pytest.fixture(autouse=True) def ensure_diskless(): from veros import runtime_settings object.__setattr__(runtime_settings, "diskless_mode", True) def test_setup_acc(): from veros.setups.acc import ACCSetup sim = ACCSetup() sim.setup() with sim.state.settings.unlock(): ...
4891052
import torch import tensorrt as trt from torch.fx.experimental.fx2trt.converter_registry import tensorrt_converter from .converter_utils import extend_mod_attr_to_tuple, mark_as_int8_layer, to_numpy, get_dyn_range def common_conv(network, mod, dimension, input_val, layer_name, is_quantized): if mod.padding_mode !...
4891101
import requests # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''WordPress 'Drag & Drop Multiple File Upload - Contact Form 7' Plugin - Pre-auth RCE''', "description": '''The drag-and-drop-multiple-file-upload-contact-form-7 plugin before 1.3.3.3 for WordPress allow...
4891126
import numpy as np import os import torch from iflow.dataset.generic_dataset import CycleDataset from sklearn.decomposition import PCA import scipy.fftpack directory = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'data')) + '/DRUMS_dataset/' class DRUMS(): def __init__(self, device = torch.d...
4891127
import sqlite3 conn = sqlite3.connect(":memory:") c = conn.cursor() c.execute("CREATE TABLE tt (Val TEXT)") conn.commit() z = [('a',), ('ab',), ('abc',), ('b',), ('c',)] c.executemany("INSERT INTO tt VALUES (?)", z) conn.commit() c.execute("SELECT * FROM tt WHERE Val LIKE 'a%'").fetchall() conn.close()
4891128
import math import sys import random as rn from collections import defaultdict from Bio import SeqIO bases = ["A", "C", "T", "G"] indel_prob = 0.01 max_indel_length = 4 subs_prob = 0.1 def sample_sites(ref_id, ref_seq, num_sites): site_list = [] ## Remove ambiguous sites is_amb = lambda genome, pos : gen...
4891144
from utils import get_subtables, formalize_rules, is_mono from c45 import gain def mine_c45(table, result): """ An entry point for C45 algorithm. _table_ - a dict representing data table in the following format: { "<column name>': [<column values>], "<column name...
4891219
from app.notify_client import NotifyAdminAPIClient class BillingAPIClient(NotifyAdminAPIClient): def get_billable_units(self, service_id, year): return self.get( '/service/{0}/billing/monthly-usage'.format(service_id), params=dict(year=year) ) def get_service_usage(se...
4891247
import os from scipy.io import loadmat import numpy as np import pandas as pd import torch from sklearn.model_selection import train_test_split from datasets.SequenceDatasets import dataset from datasets.sequence_aug import * from tqdm import tqdm from itertools import islice #Digital data was collected...
4891298
import os.path from glob import glob from numpy.testing import * import numpy as np from supreme.io import * class TestImage: def setUp(self): self.image = Image(np.arange(100).reshape((10,10))) self.image2 = Image(np.arange(10), filename='foo.jpg') assert_equal(self.image2.filename, 'foo...
4891307
import unittest import numpy as np import PySeismoSoil.helper_hh_calibration as hhc import os from os.path import join as _join f_dir = _join(os.path.dirname(os.path.realpath(__file__)), 'files') class Test_Helper_HH_Calibration(unittest.TestCase): def test_calc_rho(self): h = np.array([2, 3, 4, 5]) ...
4891362
from django.db.backends.postgresql.introspection import DatabaseIntrospection from django.db.backends.base.introspection import TableInfo, FieldInfo from django.utils.encoding import force_text from . import _constraints class DatabaseSchemaIntrospection(DatabaseIntrospection): """ database schema i...
4891384
import pytest import os import shutil @pytest.fixture(scope="session", autouse=True) def temp_dir(request): os.mkdir(os.getcwd() + "/tests/temp") def after_tests(): shutil.rmtree(os.getcwd() + "/tests/temp") request.addfinalizer(after_tests)
4891438
from __future__ import print_function import sys import os os.environ['ENABLE_CNNL_TRYCATCH'] = "OFF" # pylint: disable=C0413 import copy import unittest import logging import torch import torch.nn.functional as F cur_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(cur_dir + "/../../") from common_...
4891464
class IllegalOperationError(Exception): """ Raised if performing an illegal operation with the ``devilry.devilry_account`` models. """ pass
4891467
from flask import Flask from flask import request, make_response, redirect app = Flask(__name__) @app.route('/setcookie') def cookie_insertion(): response = app.make_response("i set some cookies. haha!\n") response.set_cookie('ID',value='212392932') return response @app.route('/getcookie') def getcookie(...
4891474
from django.conf.urls import url from . import views urlpatterns = [ url(r'commit_hash/', views.commit_hash, name='commit_hash'), url(r'reveal/', views.reveal, name='reveal'), url(r'guess/', views.guess, name='guess'), url(r'proof/', views.proof, name='proof'), url(r'verifying_key/', views.verifyin...
4891481
def pre_user_cohort_demo(indir, patient_list): cad_user_cohort_demo = {} file = '{}/demo.csv'.format(indir) with open(file, 'r') as f: next(f) for row in f: row = row.split(',') id, db, sex = row[0], row[1], row[2] if id in patient_list: ca...
4891499
from .settings_base import * # Required settings that don't really matter, but need to exist for tests to run LOG_LOCATION = '/opt/openoni/log/' OCR_DUMP_STORAGE = '/tmp/ocr' PROJECT_NAME = 'Open Online Newspapers Initiative' SECRET_KEY = "FOO" SITE_TITLE = 'Open ONI' SOLR_BASE_URL = 'http://solr:8983' STORAGE_URL = '...
4891506
import collections from strictdoc.core.document_tree import DocumentTree from strictdoc.core.file_tree import File, Folder class DocumentTreeIterator: def __init__(self, document_tree): assert isinstance(document_tree, DocumentTree) self.document_tree = document_tree def iterator(self): ...
4891526
from mythic_payloadtype_container.MythicCommandBase import * import json from uuid import uuid4 from os import path from sRDI import ShellcodeRDI from mythic_payloadtype_container.MythicRPC import * import base64 class KeylogArguments(TaskArguments): def __init__(self, command_line): super().__init__(comm...
4891557
from aoc_wim.aoc2015 import q23 data = """\ inc a jio a, +2 tpl a inc a """ def test_simple_jump(): computer = q23.Computer(instructions=data) computer.compute() assert computer.registers["a"] == 2
4891571
import numpy as np import numpy.typing as npt from nuplan.common.actor_state.state_representation import Point2D, StateSE2 def rotate_2d(point: Point2D, rotation_matrix: npt.NDArray[np.float64]) -> Point2D: """ Rotate 2D point with a 2d rotation matrix :param point: to be rotated :param rotation_matr...
4891625
from flask.cli import FlaskGroup from project import create_app, db from project.api.models import User app = create_app() cli = FlaskGroup(create_app=create_app) @cli.command() def recreate_db(): db.drop_all() db.create_all() db.session.commit() @cli.command() def seed_db(): """Seeds the database...
4891632
import unittest class Base(unittest.TestCase): """Use this base class for all tests. """ pass
4891655
from typing import List from loguru import logger from app import dataclasses, models from app.arq.tasks.classes.abstract import AbstractAsyncTask from app.factories.stylesheet import StylesheetFactory class StylesheetTask(AbstractAsyncTask): def __init__(self, snapshot: models.Snapshot): self.snapshot ...
4891660
import os def get_credentials(): """ Checks and returns if dependencies for running tests resolved or not :return: tuple(str,str) """ access_token = os.getenv('FORTNOX_ACCESS_TOKEN') client_secret = os.getenv('FORTNOX_CLIENT_SECRET') if not access_token: raise ValueError("You must...
4891665
from photons_canvas.points import helpers as php from textwrap import dedent def Space(width): return Character("_" * width) class Character: colors = {} def __init__(self, char, colors=None): if colors is not None: self.colors = colors char = dedent(char).strip() ...
4891669
class Port: def __init__(self, dtype:generic, direction:str, init=None, protocol:str='none') -> object: pass def rd(self) -> generic: pass @mutable def wr(self, v:generic) -> None: pass def __call__(self, v=None) -> generic: pass class Queue: def __init__(sel...
4891675
from .example import Example from .predicate import UnaryPredicate, BinaryPredicate from .rule import Rule from .kb import ExperimentKB from . import settings from . import load from .converters import convert_mapping_to_rdf __all__ = [ 'Example', 'UnaryPredicate', 'BinaryPredicate', 'Rule', 'ExperimentKB', 's...
4891711
import re from .common import InfoExtractor from ..utils import ( extract_attributes, ) class BostonGlobeIE(InfoExtractor): _VALID_URL = r'(?i)https?://(?:www\.)?bostonglobe\.com/.*/(?P<id>[^/]+)/\w+(?:\.html)?' _TESTS = [ { 'url': 'http://www.bostonglobe.com/metro/2017/02/11/tree-fi...
4891753
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, Group from django.db import models class Email(models.Model): email = models.EmailField(verbose_name="email address", max_length=255, unique=True) class CustomUserWithFKManager(BaseUserManager): def create_superuser(self, username, em...
4891785
from pathlib import Path from clld.db.meta import DBSession def test_Config_replacement_key(): from clld.db.models.common import Config assert Config.replacement_key('X', 'Y') == '__X_Y__' assert Config.replacement_key(None, 'Y') == '__NoneType_Y__' def test_Files(db, tmp_path): from clld.db.model...
4891788
import argparse import sys from collections import Counter from collections import defaultdict import itertools import time import numpy as np import math import pickle import setRank_TREC def string2dict(s): d = {ele.split(":")[0]: float(ele.split(":")[1]) for ele in s.split(",")} return d def dict2string(d): ...
4891821
def bob(): \ # pylint: disable=W9016 pass def bobtwo(): \ \ # some comment here pass # output def bob(): # pylint: disable=W9016 pass def bobtwo(): # some comment here pass
4891886
import pandas as pd import FINE as fn import numpy as np def test_DSM(dsm_test_esM): """ Given a one-node system with two generators, check whether the load and generation is shifted correctly in both directions with and without demand side management. """ esM_without, load_without_dsm, timestep_u...
4891903
from acq4.Manager import getManager, logExc, logMsg import numpy as np from scipy import stats from pyqtgraph.functions import siFormat from acq4.util import Qt import time from six.moves import range Ui_FilterWheelWidget = Qt.importTemplate('.FilterWheelTemplate') class FilterWheelDevGui(Qt.QWidget): def _...
4891966
import logging from xml.etree.cElementTree import fromstring from xmljson import yahoo import core from core.helpers import Url import re logging = logging.getLogger(__name__) def base_url(): url = core.CONFIG['Indexers']['Torrent']['torrentdownloads']['url'] if not url: url = 'https://www.torrentdown...
4892070
from kaldigrpc.recognize import transcribe_wav def local_transcribe_wav_cli(): transcribe_wav() if __name__ == "__main__": local_transcribe_wav_cli()
4892150
import hashlib import secrets import string import sqlalchemy as sa from h.db import Base def _generate_random_string(length=12): """Generate a random ascii string of the requested length.""" msg = hashlib.sha256() word = "" for _ in range(length): word += secrets.choice(string.ascii_letters...
4892167
import re import unittest import numpy from sklearn.utils.validation import check_random_state from classifiers.utils import split_train_data, iterate class TestUtils(unittest.TestCase): def setUp(self): self.random_state = check_random_state(0) self.y = numpy.array([0, 0, 0, 1, 1, 1, 1, 1, 0, 0...
4892174
from bibliopixel.drivers.network_receiver import NetworkReceiver from bibliopixel.drivers.visualizer import * from bibliopixel.led import Strip #must init with same number of pixels as sender driver = Visualizer(10) led = Strip(driver) receiver = NetworkReceiver(led) try: receiver.start(join = True) #join = True...
4892192
import marshal from types import CodeType from typing import Union def get_bytecode(source: str) -> CodeType: return compile(source, "<strings>", "exec") def get_bytecode_from_file(filename: str) -> CodeType: try: with open(filename, "r") as f: data = f.read() return get_bytecode...
4892235
import sys from pybindgen import * #------------------------------------------------------------------------------- # Add an object by name to a module/namespace, and publish it to the world. #------------------------------------------------------------------------------- def addObject(mod, name, *args, **kwargs): ...
4892242
import time import ray from ray.experimental import workflow @workflow.step def foo(x): print("Executing", x) time.sleep(1) if x < 20: return foo.step(x + 1) else: return 20 if __name__ == "__main__": ray.init(address="auto") wf = workflow.run(foo.step(0), workflow_id="cluste...
4892248
import abc from enum import Enum from typing import Sequence, Any, Iterator, List, Dict, Optional import attr from arsenic import constants from arsenic.session import Element @attr.s class Action: source = attr.ib() payload = attr.ib() class Tick: def __init__(self, *actions: Action): self.ac...
4892271
import sys from flask import Flask # This is just here for the sake of examples testing # to make sure that the imports work # (you don't actually need it in your code) sys.path.insert(1, ".") from flask_discord_interactions import (DiscordInteractions, Client, Message, ...