id
stringlengths
3
8
content
stringlengths
100
981k
9825559
import re from ..slack.slackbot import SlackerAdapter from ..utils.data_handler import DataHandler class Member(object): def __init__(self): self.data_handler = DataHandler() self.slackbot = SlackerAdapter() def get_names(self, text): user_ids = self.__parse_user_ids(text) m...
9825565
import pytest from torrentool.exceptions import RemoteUploadError, RemoteDownloadError from torrentool.utils import get_app_version, humanize_filesize, get_open_trackers_from_local, \ get_open_trackers_from_remote, upload_to_cache_server def test_get_app_version(): assert 'torrentool' in get_app_version() ...
9825568
default_path = "../src/" service_path = "../src/service/" import sys sys.path.insert(0, default_path) sys.path.insert(0, service_path) import unittest from docker_connector import ConnectToDocker, BuildRunDocker class _Config: SKIP_SLOW = False class Test_DockerDB(unittest.TestCase): def setUp(self): ...
9825584
from pylearn2.datasets import cache import numpy as np import sys,os import cPickle import general_tools import logging logger_prepLip = logging.getLogger('lipreading.prep') logger_prepLip.setLevel(logging.DEBUG) def unpickle(file): fo = open(file, 'rb') a = cPickle.load(fo) fo.close() return a def...
9825614
from portality.dao import DomainObject from datetime import datetime class Preserve(DomainObject): """Model class for preservation feature""" __type__ = "preserve" @property def status(self): return self.data.get("status") @status.setter def status(self, value): self.data["st...
9825622
import numpy as np import sys import torch import pickle import string import os # =============================== INFERSENT =============================== class InferSentFeatures: def __init__(self, lang_enc_dir, sentences): sys.path.insert(0, os.path.join(lang_enc_dir, 'InferSent/')) from model...
9825694
from typing import Dict from .errors import HeaderTypeDescriptorError class HeaderTypeDescriptor: """ This class is responsible for defining the stream type in bytes. """ def __get__(self, instance, owner) -> bytes: """ Gets the type in bytes based off the instance.stream_type. ...
9825728
import abc import asyncio import gzip import io import zlib from enum import Enum, unique from typing import BinaryIO class GZIPCompressedStream(io.RawIOBase): def __init__(self, stream: BinaryIO, *, compression_level: int, filename: str = None): assert 1 <= compression_level <= 9 ...
9825741
import info class subinfo(info.infoclass): def setDependencies(self): # This Package provides the binaries for uactools-bin but virtual/base can # not depend on it because it needs a compiler itself. self.runtimeDependencies["virtual/base"] = None def setTargets(self): self.sv...
9825755
from abc import ABCMeta, abstractmethod import mmcv import numpy as np import pycocotools.mask as maskUtils import torch.nn as nn from mmdet.core import auto_fp16, get_classes, tensor2imgs import json import cv2 import os # def show_result(data, result, dataset=None, score_thr=0.3): def show_result(dataset=None, ...
9825756
from django import template import datetime from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.rich_text import LINK_HANDLERS from wagtail.wagtailimages.models import get_image_model try: from wagtail.wagtailimages.models import get_upload_to except ImportError: def get_upload_to(instance, pa...
9825776
from django.conf import settings from src.wall.models import Post class Feed: """ Service feeds """ def get_post_list(self, user: settings.AUTH_USER_MODEL): return Post.objects.filter(user__owner__subscriber=user).order_by('-create_date')\ .select_related('user').prefetch_related('comm...
9825787
from mock import MagicMock import pytest try: from ignite.engine import Events _ignite_installed = True except (ImportError, TypeError): _ignite_installed = False import chainerui if _ignite_installed: from chainerui.contrib.ignite.handler import ChainerUILogger from chainerui.contrib.ignite.ha...
9825795
import os import logging import configargparse from utils.logging_utils import init_logger from utils.parse_action import StoreLoggingLevelAction class ConfigurationParer(): """This class defines customized configuration parser """ def __init__(self, config_file_parser_class=configargpa...
9825802
import sys import asyncio from aiohttp import web from bunny_storm import AsyncAdapter, RabbitMQConnectionData rabbit_adapter = None async def handle(request): await rabbit_adapter.publish(body=b"Second test message", exchange="test_2") num = request.match_info.get("num", "10") rpc_result = await rabbit...
9825882
class Demultiplexer(WebsocketDemultiplexer): # Wire your async JSON consumers here: {stream_name: consumer} consumer_classes = { "echo": EchoConsumer, "other": AnotherConsumer, }
9825898
from django.utils import timezone from rest_framework import serializers from backend.api.utils import user_allowed_folders_ids from backend.models import Folder, Ticket, Connection from users.models import User class UserSerializer(serializers.ModelSerializer): full_name = serializers.SerializerMethodField() ...
9825943
from pyecore.resources import global_registry from .datasources import getEClassifier, eClassifiers from .datasources import name, nsURI, nsPrefix, eClass from .datasources import DataSource, DataSourceLibraryConfiguration, Query, ProcessQuery, SimpleQuery, CompoundQuery, CompoundRefQuery, QueryResults, RunnableQuery, ...
9825969
from __future__ import ( annotations, ) from collections.abc import ( Iterable, ) from datetime import ( datetime, ) from typing import ( Optional, ) from uuid import ( UUID, ) from minos.aggregate import ( TransactionDatabaseOperationFactory, TransactionStatus, ) from minos.common import ...
9825991
from rest_framework.serializers import HyperlinkedModelSerializer from src.apps.runs.models import Run class RunSerializer(HyperlinkedModelSerializer): """ RunSerializer serializes one or several run for create, list and detail display on the api """ class Meta: model = Run fields = ...
9826000
from __future__ import absolute_import import os from django.conf import settings from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'apps.config.settings') app = Celery('quest_bot') # Using a string here means the worker do...
9826013
import _pickle as cPickle import collections import operator import os import pdb import random from functools import reduce from typing import List import h5py import joblib import matplotlib.pyplot as plt import numpy as np from skimage.util import view_as_windows from sklearn.preprocessing import StandardScaler, On...
9826030
import pytest from typhoon.connections import Connection from typhoon.core.settings import Settings from typhoon.metadata_store_impl.sqlite_metadata_store import SQLiteMetadataStore from typhoon.variables import Variable, VariableType @pytest.fixture def typhoon_home(tmp_path): Settings.typhoon_home = tmp_path ...
9826039
import os import sys import re import platform import gevent from gevent import monkey monkey.patch_all() import requests from lxml import etree from more_itertools import chunked from .utils import get_image_info, parse_url from .exceptions import URLParseError REQUEST_HEADERS = {'User-agent': 'Mozilla/5.0 (Maci...
9826040
import inspect import warnings from collections import namedtuple from functools import wraps from traceback import format_stack import numpy as np INTEGER_TYPES = (int, np.integer) __all__ = ('assign_only_single_slice', 'astro_data_descriptor', 'AstroDataDeprecationWarning', 'astro_data_tag', 'deprecated...
9826060
from __future__ import absolute_import import json import decimal import datetime from . import models class JSONEncoder(json.JSONEncoder): def default(self, value): # The following types should simply be cast to strings str_types = ( datetime.date, datetime.datetime, ...
9826065
from datetime import datetime from os.path import dirname, join import pytest # noqa from city_scrapers_core.constants import COMMITTEE, PASSED from city_scrapers_core.utils import file_response from freezegun import freeze_time from city_scrapers.spiders.cle_transit import CleTransitSpider test_response = file_res...
9826102
import torch import torch.nn as nn from torchvision import models import torch.nn.functional as F import math from utils.tools import initialize_weights class PyramidPoolingModule(nn.Module): def __init__(self, in_size, in_channels, out_channels, setting): super(PyramidPoolingModule, self).__init__() ...
9826104
import datetime import os import subprocess import numpy as np import tensorflow as tf import time import quaternion try: from pyglet.gl import * except: print("WARNING: pyglet cannot be imported but might be required for visualization.") from scipy.ndimage import filters as filters BLACK = (0, 0, 0) WHITE ...
9826111
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import math from functools import partial import pdb class ICNet3D(nn.Module): def __init__(self, opt): super(ICNet3D, self).__init__() self.residual = opt.residual self.scaledown = opt....
9826156
import numpy as np import pytest from espnet.utils.cli_readers import file_reader_helper from espnet.utils.cli_utils import assert_scipy_wav_style from espnet.utils.cli_writers import file_writer_helper @pytest.mark.parametrize("filetype", ["mat", "hdf5", "sound.hdf5", "sound"]) def test_KaldiReader(tmpdir, filetype...
9826216
import gzip import logging import re import shutil import tarfile import zipfile from pathlib import Path from typing import Union, Pattern, List, Tuple import requests from requests import Response from tqdm import tqdm from torchglyph import data_dir logger = logging.getLogger(__name__) __all__ = [ 'toggle_lo...
9826233
from __future__ import division from __future__ import print_function from __future__ import absolute_import from .tree import Tree from .token import parse def convert(code): codeNoComments = removeComments(code) tokenStack = parse(codeNoComments) root = Tree('Program') root.addChild(Tree('WhenRun')) while not...
9826246
from os.path import exists from os import stat def true_exists(fname): return exists(fname) and stat(fname).st_size > 100
9826263
from .custom import CustomDataset from .xml_style import XMLDataset from .coco import CocoDataset from .coco_rgb import CocoRGBDataset from .coco_rgb_2 import CocoDatasetRGB2 from .coco_3d import Coco3DDataset from .coco_3d_parcel import Coco3DParcelDataset from .coco_3d_2scales import Coco3D2ScalesDataset from .coco_3...
9826286
from typing import Iterator, List from chemprop.data import MoleculeDataset, StandardScaler from chemprop.data.data import MoleculeDataLoader from chemprop.models import MoleculeModel from chemprop.uncertainty.uncertainty_calibrator import UncertaintyCalibrator from chemprop.uncertainty.uncertainty_predictor import bu...
9826320
from unittest import TestCase from pyinfra.api.util import ( format_exception, get_caller_frameinfo, try_int, underscore, ) class TestApiUtil(TestCase): def test_try_int_number(self): assert try_int('1') == 1 def test_try_int_fail(self): assert try_int('hello') == 'hello' ...
9826347
import numpy as np from bayesnet.tensor.tensor import Tensor from bayesnet.function import Function from bayesnet.image.util import img2patch, patch2img class Convolve2d(Function): def __init__(self, stride, pad): """ construct 2 dimensional convolution function Parameters ------...
9826380
import json import random from decimal import Decimal from django.test import TestCase from django.test import RequestFactory from django.test import Client from django.db.models import Q, Avg, Count, Min, Max, Sum, FloatField, F from django.db import connections from django.contrib.auth.models import User import fac...
9826386
import json from api.core.profile import Profile from api.db.models.v1.governance import CredentialTemplate from api.db.session import async_session from api.endpoints.models.v1.errors import NotFoundError from api.protocols.v1.endorser import CreateCredDefProcessor class CreateCredDefRevocationProcessor(CreateCredD...
9826393
from vpython import * scene.caption = """In GlowScript programs: Right button drag or Ctrl-drag to rotate "camera" to view scene. To zoom, drag with middle button or Alt/Option depressed, or use scroll wheel. On a two-button mouse, middle is left + right. Touch screen: pinch/extend to zoom, swipe or two-finger rotate...
9826394
from random import choice class UserAgent: def __init__(self): self.user_agents = [ 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11', 'Opera/9.25 (Windows NT 5.1; U; en)', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1...
9826459
from flask import jsonify, request from . import api from app.models import * from ..util.custom_decorator import login_required from ..util.utils import * from flask_login import current_user @api.route('/config/add', methods=['POST']) @login_required def add_scene_config(): """ 添加配置 """ data = request.json ...
9826462
import torch from torch import Tensor from torch.nn import Sequential, Sigmoid, Tanh from tha.batch_input_module import BatchInputModule, BatchInputModuleSpec from nn.conv import Conv7 from nn.u_net_module import UNetModule class Combiner(BatchInputModule): def __init__(self, image_size: int = 2...
9826470
from iconservice import * from . import utils # @dev Library for computing Tendermint's block header hash from app hash, time, and height. # # In Tendermint, a block header hash is the Merkle hash of a binary tree with 14 leaf nodes. # Each node encodes a data piece of the blockchain. The notable data leaves are: [A] ...
9826504
from functools import wraps from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.utils.translation import ugettext_lazy as _ from core.models import Event from core.utils import login_redirect from .views.menu_items import intra_admin_menu_items, intra_organizer_me...
9826535
from yt.testing import assert_array_equal, assert_equal, requires_file from yt.utilities.answer_testing.framework import ( GenericArrayTest, data_dir_load, requires_ds, ) out = "ExodusII/out.e" @requires_file(out) def test_out(): ds = data_dir_load(out) field_list = [ ("all", "conv_indica...
9826561
from numbers import Real from unittest import TestCase from diffprivlib.mechanisms import ExponentialHierarchical, Laplace from diffprivlib.mechanisms.transforms import DPTransformer class TestDPTransformer(TestCase): def test_not_none(self): mech = DPTransformer(ExponentialHierarchical(epsilon=1, hierar...
9826599
crra_util_data = [ ('β', float64), ('σ', float64), ('γ', float64) ] @jitclass(crra_util_data) class CRRAutility: def __init__(self, β=0.9, σ=2, γ=2): self.β, self.σ, self.γ = β, σ, γ # Utility function def U(self, c, l): # No...
9826610
import sympy as sp import numpy as np import math import random from AircraftIden import FreqIdenSIMO import matplotlib.pyplot as plt from scipy.optimize import minimize import copy import multiprocessing from AircraftIden.StateSpaceParamModel import StateSpaceParamModel, StateSpaceModel import time import sys class ...
9826680
from autoflow.workflow.components.classification_base import AutoFlowClassificationAlgorithm __all__ = ["SVC"] class SVC(AutoFlowClassificationAlgorithm): class__ = "SVC" module__ = "sklearn.svm"
9826697
import argparse import json import boto3 def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("-p", "--profile", type=str, default="default", help="AWS Profile name") parser.add_argument("-e", "--endpoint_name", type=str, default="whylabs-sagemaker", help="SageMaker endpoint name") ...
9826749
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.auxiliary_tasks.auxiliary_tasks import AuxiliaryTask class PPO: def __init__(self, model, optimizer, buffer, algo_params, aux_tasks...
9826767
from office365.runtime.client_value import ClientValue from office365.runtime.client_value_collection import ClientValueCollection class EmailProperties(ClientValue): def __init__(self, body, subject, to, from_address=None, cc=None, bcc=None, additional_headers=None): """ :param str body: ...
9826778
from ghidra.app.services import DataTypeManagerService from ghidra.program.model.symbol import SourceType,SymbolTable,Namespace,RefType from ghidra.app.services import BlockModelService from ghidra.app.cmd.function import ApplyFunctionSignatureCmd from ghidra.app.decompiler import DecompileOptions,DecompInterface from ...
9826800
import os import json from tkinter import colorchooser import tkinter.ttk as ttk from tkinter import * from tkinter import filedialog from numpy import True_ from screen_translate.Public import CreateToolTip, fJson, _StoredGlobal from screen_translate.Public import startfile, optGoogle, optDeepl, optMyMemory, optPons...
9826815
from .coco_evaluation import COCOEvaluator from .pascal_voc_evaluation import PascalVOCDetectionEvaluator from .evaluator import DatasetEvaluator, DatasetEvaluators, inference_context, inference_on_dataset from .testing import print_csv_format, verify_results __all__ = [k for k in globals().keys() if not k.startswith(...
9826851
import argparse, sys # local imports from src import actions def main(): parser = argparse.ArgumentParser(description='Spotify downloader V1') required = parser.add_mutually_exclusive_group(required=True) required.add_argument('-auto', action='store_true', help='Runs the downloader in automatic mode') ...
9826870
from http import HTTPStatus from typing import Dict, List import tornado from adserver.protocols.request_handler import ( RequestHandler, ) # pylint: disable=no-name-in-module class TensorflowRequestHandler(RequestHandler): def __init__(self, request: Dict): # pylint: disable=useless-super-delegation ...
9826893
import tensorflow as tf import yaml import os,sys import numpy as np # sys.path.append(os.path.abspath('/EEG_Riemannian')) # print(sys.path[0]) import utils def load_config(name): with open(os.path.join(sys.path[0], name)) as file: config = yaml.safe_load(file) return config config = load_config('da...
9826927
import re from itertools import zip_longest import six from django.apps import apps from django.conf import settings from django.db import connection, ProgrammingError from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.graph import MigrationGraph from django_db_views.db_view...
9826961
import math import random import numpy as np def chunks(arr, m): n = int(math.ceil(len(arr) / float(m))) return [arr[i:i + n] for i in range(0, len(arr), n)] def get_probability(src,arr): diff = [abs(i-src)+0.001 for i in arr] return [1/i if 1/i<1 else 1 for i in diff] def norm(arr): return [i/s...
9826971
from django.contrib import admin from .models import Display from .models import Slide admin.site.register(Display) admin.site.register(Slide)
9826997
import weakref import UserDict class MultiWeakKeyDictionary(UserDict.DictMixin): def __init__(self): self._bylength = {} def __getitem__(self, key): key = (len(key),) + key d = self._bylength for step in key: d = d[step] return d def __setitem__(self,...
9827009
import datetime import uuid import cryptography.hazmat.backends from collections import OrderedDict from cryptography import x509 from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa from cryptograp...
9827040
from typing import Optional, Union, List from ..math.matrix import Matrix from ..dynamics.body import Body from ..common.random import RandomGenerator from .joint.joint import Joint from .joint.distance import DistanceJoint, DistanceJointPrimitive from .joint.point import PointJoint, PointJointPrimitive from .joint.pu...
9827045
from automat import MethodicalMachine class Led(object): _machine = MethodicalMachine() @_machine.state() def led_on(self): "led is on" @_machine.state(initial=True) def led_off(self): "led is off" @_machine.input() def turn_on(self): "turn the led on" @_mac...
9827049
from typing import ( # type: ignore Any, Dict, Protocol, Tuple, Type, TypeVar, TypedDict, Union, _TypedDictMeta, ) from dbdaora.data_sources.memory import GeoMember, GeoRadiusOutput from dbdaora.entity import init_subclass GeoSpatialData = Union[GeoMember, GeoRadiusOutput] clas...
9827055
import xlsxwriter import os import sys def process_layout_data(filename = "TextLayout.txt"): workbook = xlsxwriter.Workbook(filename.split('.')[0] + ".xlsx") worksheet = workbook.add_worksheet() worksheet.add_table('A1') data = open(filename) lines = data.readlines() lines = map(lambda x: ...
9827102
from __future__ import unicode_literals # encoding: utf-8 from django.db import models class CepManager(models.Manager): def get_or_create(self, codigo): try: return Cep.objects.get(codigo=codigo) except Cep.DoesNotExist: return Cep(codigo=codigo) class Cep(models.Model)...
9827143
import pandas as pd import networkx as nx from postman_problems.viz import add_node_attributes # ################### # PARAMETERS / DATA # # ################### GRAPH = nx.MultiGraph([ ('a', 'b', {'id': 1, 'distance': 5}), ('a', 'c', {'id': 2, 'distance': 20}), ('b', 'c', {'id': 3, 'distance': 10}), ...
9827149
import discord import asyncio from discord.ext import commands from typing import Optional async def wait_for_msg(ctx: commands.Context, timeout: int, msg_to_edit: discord.Message) -> Optional[discord.Message]: def c(m): return m.author == ctx.author and m.channel == ctx.channel try: msg: disc...
9827163
from io import open import tempfile import os import shutil import uuid import PIL.Image from django.core.files.storage import default_storage from django.core.files.base import ContentFile from django.test import override_settings from .utils import repr_rgb PATH = os.path.split(__file__)[0] ORIG_IMG_PATH = os.pa...
9827171
import unittest from rekcurd_dashboard.models import DataServerModel, DataServerModeEnum from rekcurd_dashboard.data_servers import CephHandler from . import patch_predictor class CephHandlerTest(unittest.TestCase): """Tests for CephHandlerTest. """ def setUp(self): self.data_server_model = Dat...
9827256
from typing import AnyStr, Dict, List from rating_operator.api.check import date_checker_start_end, multi_tenant from rating_operator.api.db import db from rating_operator.api.utils import process_query from rating_operator.api.utils import process_query_get_count import sqlalchemy as sa from sqlalchemy.sql.expressio...
9827265
POSETRACK_KEYPOINTS = [ 'nose', 'head_bottom_pt', 'headtop', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle' ]
9827283
import logging import pprint import requests import os GITHUB_REPO_PREFIX = 'https://github.com/' GITHUB_API = 'https://api.github.com/repos/' class Repository(object): all = [] def __init__(self, url): self.url = url self.categories = [] self.data = dict() self.all.append(se...
9827316
import argparse from .defaults.sampler_defaults import HparamsAbsorbing, HparamsAutoregressive, add_sampler_args from .defaults.vqgan_defaults import HparamsVQGAN, add_vqgan_args from .defaults.experiment_defaults import add_PRDC_args, add_sampler_FID_args, add_big_sample_args # args for training of all models: datas...
9827390
from dataclasses import dataclass @dataclass class CacheBackend: """The Backend adapters available for the caching.""" sqlite: str = "sqlite" redis: str = "redis" mongodb: str = "mongodb" memory: str = "memory"
9827417
import sys from collections import defaultdict _, outgroupfile, window_size, callablefile, outfile = sys.argv window_size = int(window_size) derived_found = defaultdict(int) with open(outgroupfile) as data: for line in data: if 'N_ALLELES' not in line: chrom, pos, _, total, ref, alt = line.strip().split() ...
9827425
from .. import query_processor from nose.tools import assert_true, assert_equal from numpy import random import ast # Ten tracts traversing random labels another_set = True while (another_set): tracts_labels = dict([(i, set(random.randint(100, size=2))) for i in range(100)]) labels_tracts = query_processor.la...
9827466
from distutils.core import setup setup( name = 'webagent-scanner', packages = ['webagent-scanner'], # this must be the same as the name above version = 'v1.0', description = 'Web-agent scanner allowing web applications to take advantage of USB scanners via TWAIN', author = '<NAME>', author_email = '<EMAIL>...
9827499
import sys import traceback from io import StringIO from PySide2.QtCore import Qt from PySide2.QtWidgets import QMessageBox from node_launcher.constants import NODE_LAUNCHER_RELEASE def except_hook(exception_type, exception_value, traceback_object): notice = f'''Wild bug appears! <br> Please copy this text and ...
9827502
from clusteringnmap.vectorize import Vectorizer, vectorize from clusteringnmap.clustering import cluster_with_dbscan, cluster_with_kmeans, precompute_distances, cluster_with_agglomerative, cluster_interactive from clusteringnmap.validation import validate_clusters, get_average_distance_per_cluster from clusteringnmap.a...
9827520
import pytest import itertools as it import stk from stk.molecular.reactions.reactions.reaction import ReactionResult from ..case_data import CaseData from .utilities import MockConstructionState, MockEdge @pytest.fixture def one_two_reaction( periodicity, functional_group1, functional_group2, bond_o...
9827584
class Program: procedures = [] variables = ["\n\t.data"] defining_proc = False def __init__(self, external_prog = False): self.external_prog = external_prog if self.external_prog: self.main = ["\t.text"] else: self.main = ["\t.global _main\n\t.text\n_main:"] def emit(self, *instructions, tab = True,...
9827650
from typing import List, Dict, Union, Callable from transformers import PreTrainedModel, PreTrainedTokenizerBase from .base import DoolyTaskConfig, SequenceTagging from ..tokenizers import Tokenizer as _Tokenizer Tokenizer = Union[_Tokenizer, PreTrainedTokenizerBase] class MachineReadingComprehension(SequenceTaggi...
9827651
import json import requests def send_reading_requests(point_id_readable): ''' Purpose: receive responses of http-reading-requests for Haystack point Inputs: point_id_readable Returns: http-reading-request status Notes: url ="http://localhost:80/api/read"; header and data need to follow Haystack s...
9827712
from progressbar import utils from progressbar.widgets import FormatWidgetMixin, TimeSensitiveWidgetBase class Rate(FormatWidgetMixin, TimeSensitiveWidgetBase): ''' WidgetBase for showing the change per second == rate ''' def __init__( self, format='%(scaled)5.1f/s', **kwargs): Fo...
9827782
import time import asyncio import asyncbg def background_work(): print('Background sleep for 3 seconds.') time.sleep(3) print('Background sleep done.') async def foreground_work(): for i in range(5): print('Foreground sleep for 1 second.') await asyncio.sleep(1) print('Foregr...
9827790
try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse from bs4 import BeautifulSoup import yaml __CONFIG__ = '' with(open('./trawler/config.yml', 'r')) as ymlfile: __CONFIG__ = yaml.load(ymlfile, Loader=yaml.BaseLoader) class Generator(object): def __init__(self,...
9827804
from click.testing import CliRunner from rony.cli import cli, logo import os def test_installation_ok(): runner = CliRunner() res = runner.invoke(cli) assert res.exit_code == 0 def test_info(): runner = CliRunner() res = runner.invoke(cli, ['info']) assert logo in res.output
9827868
n1 = 10 n2 = 20 def calculadora (n1, n2): return n1 + n2 n1 = 10 n2 = 20 print(calculadora(1, 2)) #https://pt.stackoverflow.com/q/483477/101
9827909
import FWCore.ParameterSet.Config as cms hltTrackClusterRemover = cms.EDProducer( "HLTTrackClusterRemoverNew", trajectories = cms.InputTag( "hltPFlowTrackSelectionHighPurity" ), doStrip = cms.bool( True ), doPixel = cms.bool( True ), stripClusters = cms.InputTag...
9827955
try: from . coretypes import * except SystemError: from coretypes import * """ resPQ#05162463 nonce:int128 server_nonce:int128 pq:bytes server_public_key_fingerprints:Vector<long> = ResPQ """ ResPQ_t = MTPType('ResPQ_t') resPQ_c = BareType(name='resPQ_c', number=0x05162463, params=('nonce', '...
9827956
import warnings from json import JSONDecodeError import requests from requests.exceptions import RequestException from .exc import StackExchangeError, StackExchangeNoKeyWarning API_URL = 'https://api.stackexchange.com/2.2/questions' class StackExchange: """ Wrapper class for Stack Exchange API calls ...
9828006
from setuptools import setup, find_packages setup( name = 'aiojson', version = '0.1', author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/ethanfrey/aiojson', license = 'BSD', description = 'Iterative JSON parser for asyncio streams', long_description = open('README.rs...
9828017
import RPi.GPIO as GPIO from hardware import PINS_PROFILES from application import Application from . import State from hardware import PIN_BUTTON_PROG, PIN_BUTTON_ERASE, PIN_RESET_ATMEGA from .hat_button import SinglePinButton, DoublePinButton import time class WaitForButtonState(State): def _do_erase(self): ...
9828028
from photons_canvas.points import containers as cont from photons_canvas.orientation import Orientation from photons_app import helpers as hp from photons_products import Products import pytest @pytest.fixture def V(): class V: device = cont.Device("d073d5001337", Products.LCM3_TILE.cap) other_...
9828033
import json import pickle from PIL import Image, features # from torchpie.logging import logger import logging logger = logging.getLogger(__name__) logger.info(f'pillow version: {Image.PILLOW_VERSION}') logger.info( 'Using jpeg-turbo: {}'.format(features.check_feature('libjpeg_turbo'))) def load_json(filename: ...