id
stringlengths
3
8
content
stringlengths
100
981k
60026
import json import os import shutil import subprocess import sys import tempfile import unittest sys.path.append("../main") from algorithms import * port = 2222 def sshd(**kwargs): dirname = tempfile.mkdtemp() confname = dirname + "/sshd_config" logname = dirname + "/sshd.log" with open(confname,...
60042
from string import ascii_uppercase as alphabet def codes_table(char): table = { "A": 11, "B": 21, "C": 31, "D": 41, "E": 51, "F": 12, "G": 22, "H": 32, "I": 42, "K": 52, "L": 13, "M": 23, "N": 33, "O": 43, "P": 53, "Q": 14, "R": 24, "S": 34, "T": 44, "U": 54, "V": 15, "W": ...
60058
from pydantic import BaseModel, constr def other_func(regex): pass class Model(BaseModel): abc: str = other_func(regex='<caret>[^a-zA-Z]+')
60098
from pyecharts import options as opts from pyecharts.charts import Scatter from pyecharts.commons.utils import JsCode from pyecharts.faker import Faker c = ( Scatter() .add_xaxis(Faker.choose()) .add_yaxis( "商家A", [list(z) for z in zip(Faker.values(), Faker.choose())], label_opts=op...
60106
from bluetooth_communication import AndroidAPI, AndroidThread, AndroidExploreRunThread from pc_communication import PcThread, PcExploreRunThread from serial_stub import SerialAPIStub __author__ = 'Danyang' if __name__=="__main__": print "Executing main flow" serial_api = SerialAPIStub() android_api = Andr...
60179
import os import subprocess import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.nn.functional import interpolate from loguru import logger from tqdm import tqdm import numpy as np import wandb from draw_concat import draw_concat from generate_noise import generate...
60223
from __future__ import print_function import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials import sys import json SCOPES = ['https://www.googleapis.com/auth/d...
60247
class Leapx_org(): mul_num = 1.20 mul_num2 = 1.30 def __init__(self,first,last,pay): self.f_name = first self.l_name = last self.pay_amt = pay self.full_name = first+" "+last @staticmethod def check_amt(amt): if amt <50000: return True else : return False def incrementpay(self): ...
60262
from pathlib import Path from .build import DocBuilder def finalize_builddir(repo_name): 'Bookkeeping on the docs build directory' root = Path('_build') / repo_name with open(root / '.nojekyll', 'w') as fh: fh.write('') def build_root(repo_name): '''Build the top-level documentation. Se...
60337
import script from script import * import shlex import edition import layout import query import player import test import graph import opendns class Color(script.Script): def __init__(self, console): super(Color, self).__init__(console) self.colors = { "red" : [ 1.0, 0.0, 0.0, 1.0 ], "green" : [ 0.0, ...
60344
from sklearn.base import BaseEstimator import yake from ._prep import TextPrep class YakeTextPrep(TextPrep, BaseEstimator): """ Remove all text except meaningful key-phrases. Uses [yake](https://github.com/LIAAD/yake). Arguments: top_n: number of key-phrases to select unique: only return...
60352
from flask import Blueprint from ctflorals.controllers import HomeController from ctflorals.controllers import AboutController from ctflorals.controllers import GalleryController from ctflorals.controllers import TestimonialsController ctflorals = Blueprint('ctflorals', __name__, template_folder...
60357
from django.core.management.base import BaseCommand from orcamentos.crm.models import Employee class Command(BaseCommand): help = ''' Cria um usuário admin. ''' def handle(self, *args, **kwargs): ''' Cria um Employee. Precisamos de Employee para fazer todas as transações no sistema. ...
60385
from .decorators import endpoint from ..definitions.types import ClientExtensions from ..definitions.types import InstrumentName from ..definitions.types import StopLossDetails from ..definitions.types import TakeProfitDetails from ..definitions.types import TradeID from ..definitions.types import TradeSpecifier from ....
60412
from simple_rl.mdp.oomdp.OOMDPStateClass import OOMDPState class TrenchOOMDPState(OOMDPState): ''' Class for Trench World States ''' def __init__(self, objects): OOMDPState.__init__(self, objects=objects) def get_agent_x(self): return self.objects["agent"][0]["x"] def get_agent_y(sel...
60436
from node import Node class Stack: def __init__(self): self.head = None def __str__(self): node = self.head list = [] while node: list.append(node.get_item()) node = node.get_next() return str(list) def is_empty(self): return not self.head def push(self, item): if not self.head: self.hea...
60453
import sys import typing from metal.serial import Engine from metal.serial.hooks import MacroHook from metal.serial.preprocessor import MacroExpansion class Argv(MacroHook): identifier = 'METAL_SERIAL_INIT_ARGV' def invoke(self, engine: Engine, macro_expansion: MacroExpansion): engine.write_int(len...
60495
from collections import Counter, defaultdict def fizz_buzz_counter(): values = [] for i in range(1, 101): if i % 3 == 0 and i % 5 == 0: values.append("fizzbuzz") elif i % 3 == 0: values.append("fizz") elif i % 5 == 0: values.append("buzz") els...
60511
import unittest # Run tests without using GPU import os os.environ["CUDA_VISIBLE_DEVICES"] = "-1" os.environ['TEST'] = "1" import sys from pathlib import Path TEST_DIR = str(Path(__file__).parent.resolve()) BASE_DIR = str(Path(__file__).parent.parent.resolve()) sys.path.append(BASE_DIR) from core.filters import Publ...
60552
import sublime, sublime_plugin import os try: # ST3 from ..apis.core import Core except (ImportError, ValueError): # ST2 from apis.core import Core # Completion class ERBAutocompleteListener(sublime_plugin.EventListener): def on_query_completions(self, view, prefix, locations): core = Core(...
60628
import os import numpy as np import random import numbers import skimage from skimage import io, color import torch # read uint8 image from path def imread_uint8(imgpath, mode='RGB'): ''' mode: 'RGB', 'gray', 'Y', 'L'. 'Y' and 'L' mean the Y channel of YCbCr. ''' if mode == 'RGB': img = io....
60678
import os import unittest import tempfile import fcntl import struct from ffrecord import checkFsAlign FS_IOCNUM_CHECK_FS_ALIGN = 2147772004 def checkFsAlign2(fd): buf = bytearray(4) try: fcntl.ioctl(fd, FS_IOCNUM_CHECK_FS_ALIGN, buf) except OSError as err: return False fsAlign = s...
60690
import re from configparser import ConfigParser from tadataka.camera.model import CameraModel def parse_(line): camera_id, model_params = re.split(r"\s+", line, maxsplit=1) try: camera_id = int(camera_id) except ValueError: raise ValueError("Camera ID must be integer") return camera_id...
60725
import os import shutil def ensure_folder_exists_and_is_clear(folder): if not os.path.exists(folder): os.makedirs(folder) for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path)...
60777
import os import logging import re from copy_reg import pickle from multiprocessing import Pool from subprocess import check_output from types import MethodType from RsyncUploadThread import RsyncUploadThread from mongodb_consistent_backup.Common import config_to_string from mongodb_consistent_backup.Errors import O...
60782
import time import os import psycopg2 import psycopg2.extras from pyinfraboxutils import get_logger logger = get_logger('infrabox') def connect_db(): while True: try: conn = psycopg2.connect(dbname=os.environ['INFRABOX_DATABASE_DB'], user=os.environ['INFRABO...
60794
import os import numpy as np from pwtools.common import is_seq, file_write from .testenv import testdir def test_is_seq(): fn = os.path.join(testdir, 'is_seq_test_file') file_write(fn, 'lala') fd = open(fn , 'r') for xx in ([1,2,3], (1,2,3), np.array([1,2,3])): print(type(xx)) assert is...
60837
from __future__ import absolute_import from . import pubnub # noqa from . import requests # noqa
60866
import enum from rose.utils import * class VertexFormat(enum.IntEnum): POSITION = 1 << 1 NORMAL = 1 << 2 COLOR = 1 << 3 BONEWEIGHT = 1 << 4 BONEINDEX = 1 << 5 TANGENT = 1 << 6 UV1 = 1 << 7 UV2 = 1 << 8 UV3 = 1 << 9 UV4 = 1 << 10 class Vertex: def __init__(self): ...
60913
import unittest import hail as hl from lib.model.seqr_mt_schema import SeqrVariantSchema from tests.data.sample_vep import VEP_DATA, DERIVED_DATA class TestSeqrModel(unittest.TestCase): def _get_filtered_mt(self, rsid='rs35471880'): mt = hl.import_vcf('tests/data/1kg_30variants.vcf.bgz') mt = hl...
60921
from yaml import safe_load from hashlib import md5 from enum import Enum from box import Box class YamlType(Enum): BASE = 0 PIPELINE = 1 SERVICE = 2 def Yaml(path): """ Sudo class for managing a yaml as a python object. :param path: path to .yaml file """ __type__ = None __text_...
60924
from __future__ import absolute_import from __future__ import print_function import numpy as np import re from scipy import linalg import scipy.ndimage as ndi from six.moves import range import os import sys import threading import copy import inspect import types from keras import backend as K from keras.utils.gener...
60954
from string import Template from requests import get, post userInfoQuery = """ { viewer { login id } } """ createContributedRepoQuery = Template(""" query { user(login: "$username") { repositoriesContributedTo(last: 100, includeUserRepositories: true) { nodes { isFork...
60969
import os import setuptools from pathlib import Path directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'peg_in_hole', 'envs', 'assets') data_files = [] for root, dirs, files in os.walk(directory): for file in files: data_files.append(os.path.join(root, file)) setuptools.setup( name...
60984
import pytest import numpy as np from sklearn.ensemble import RandomForestClassifier from ..sequential import sequential import pkg_resources PATH = pkg_resources.resource_filename(__name__, 'test_data/') def test_sequential(): "Test sequential feature selection" # load data X = np.load(PATH+'featur...
60991
from django.urls import path from .views import ( change_password, login, logout, profile, register, register_email, reset_password, send_reset_password_link, verify_email, verify_registration ) app_name = 'rest_registration' urlpatterns = [ path('register/', register, name...
60998
from pymesh.TestCase import TestCase from pymesh import distance_to_mesh, BVH from pymesh.meshutils import generate_box_mesh import numpy as np class DistanceToMeshTest(TestCase): def test_boundary_pts_cgal(self): mesh = generate_box_mesh( np.array([0, 0, 0]), np.array([1, 1, 1]))...
61004
import torch import torch.nn as nn import numpy as np class IndexTranslator(object): def __init__(self, state): self.state = state self.px = self.state[:, 0].reshape(-1, 1) self.py = self.state[:, 1].reshape(-1, 1) self.vx = self.state[:, 2].reshape(-1, 1) self.vy = self.st...
61073
import os import KratosMultiphysics from KratosMultiphysics import Logger Logger.GetDefaultOutput().SetSeverity(Logger.Severity.WARNING) import KratosMultiphysics.KratosUnittest as KratosUnittest import KratosMultiphysics.DEMApplication.DEM_analysis_stage import numpy as np import auxiliary_functions_for_tests this_w...
61094
from flexinfer.misc import build_from_cfg, registry def build_converter(cfg): return build_from_cfg(cfg, registry, 'converter')
61104
def redis_key(project_slug, key, *namespaces): """ Generates project dependent Redis key >>> redis_key('a', 'b') 'a:b' >>> redis_key('a', 'b', 'c', 'd') 'a:c:d:b' >>> redis_key('a', 1, 'c', None) 'a:c:1' """ l = [project_slug] if namespaces: l.extend(namespaces) ...
61107
from .base_assigner import BaseAssigner from .max_iou_assigner import MaxIoUAssigner from .approx_max_iou_assigner import ApproxMaxIoUAssigner from .assign_result import AssignResult from .max_iou_assigner_hbb_cy import MaxIoUAssignerCy from .max_iou_assigner_rbbox import MaxIoUAssignerRbbox from .approx_max_iou_assign...
61114
import numpy as np import scipy import cv2 def get_pixel_neighbors(height, width): """ Estimate the 4 neighbors of every pixel in an image :param height: image height :param width: image width :return: pixel index - neighbor index lists """ pix_id = [] neighbor_id = [] for i in ra...
61118
import sqlite3 import os DB_SAVES_DIR = 'saves' class DB: def __init__(self, name): self.name = name self.path = '{}/{}.db'.format(DB_SAVES_DIR, self.name) if not os.path.isdir(DB_SAVES_DIR): os.makedirs(DB_SAVES_DIR) self.conn = sqlite3.connect(self.path) def sa...
61136
import unittest def setUpModule(): print("in module {} - setUpModule()".format(__name__)) def tearDownModule(): print("in module {} - tearDownModule()".format(__name__)) class TextFixtures(unittest.TestCase): @classmethod def setUpClass(cls): print('in class {} - setUpClass()'.format(cls.__...
61137
import os import numpy as np import torch from torchvision import models, transforms MODELS = {'densenet121': models.densenet121, 'resnet152': models.resnet152} DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') ANALYZERS = ['grad', 'smooth-grad', 'smooth-taylor', 'ig', 'lrp'] IG_BASELIN...
61138
import warnings import numpy as np from einsteinpy.integrators import GeodesicIntegrator from .utils import _P, _kerr, _kerrnewman, _sch class Geodesic: """ Base Class for defining Geodesics Working in Geometrized Units (M-Units), with :math:`c = G = M = k_e = 1` """ def __init__( ...
61190
from ksc.backends import common from ksc.backends import abstract from ksc.backends import jax from ksc.backends import jax_input_last
61198
from linz_logger import get_log from topo_processor.util import time_in_ms from .get_fs import get_fs def transfer_file(source_file: str, checksum: str, content_type, target_file: str): start_time = time_in_ms() with get_fs(source_file).open(source_file, "rb") as f1: data = f1.read() with ge...
61221
import json import time from typing import Dict from scrapy.exceptions import NotConfigured from scrapy.http.response.html import HtmlResponse from scrapy_cdr import CDRItem from dd_crawler.utils import get_domain class RequestLogMiddleware: def __init__(self, *, jl_logger, relevancy_threshold: float): ...
61226
import pandas as pd def lookup_dates(s): """ This is an extremely fast approach to datetime parsing. For large data, the same dates are often repeated. Rather than re-parse these, we store all unique dates, parse them, and use a lookup to convert all dates. """ dates_dict = {date:pd.to_date...
61235
from mongoengine import Document, StringField, BooleanField, IntField, ListField, ReferenceField, EmailField, LongField from mongoengine import NULLIFY, PULL class User(Document): ID = LongField(unique=True, required=True) Username = StringField(required=True) Password = StringField() IsLock = Boolean...
61247
import torch from torch import nn from torch.nn import functional as F from .resnet import resnet18, resnet34 from .segmentation import SegmentationHead from .attention import Attention from .erfnet import ERFNet class Normalize(nn.Module): """ ImageNet normalization """ def __init__(self, mean, std): ...
61265
import sqlite3 import argparse from os.path import join import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from keras.models import model_from_json import preprocessing.config as cfg import preprocessing.file_utils as futils from preprocessing.data import LightDataManager de...
61273
import FWCore.ParameterSet.Config as cms # BTagPerformanceAnalyzer configuration from Validation.RecoB.bTagAnalysis_cfi import * bTagValidationHarvest = bTagHarvestMC.clone() from DQMOffline.RecoB.bTagAnalysisData_cfi import * bTagValidationHarvestData = bTagHarvest.clone()
61294
from scapy.all import * import argparse parser = argparse.ArgumentParser(description="Simple SYN Flood Script") parser.add_argument("target_ip", help="Target IP address (e.g router's IP)") parser.add_argument("-p", "--port", help="Destination port (the port of the target's machine service, \ e.g 80 for HTTP, 22 for SS...
61340
import ee from zipfile import ZipFile from io import BytesIO import os import requests class S2indexes: def __init__(self, area, dir, date_from, date_end, scope): """ given an area defined by a geoJSON, it returns rasters of remote sensing indexes at the specified date at granularuity de...
61346
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """
61349
import pandas as pd import numpy as np from numpy import corrcoef import matplotlib.pyplot as plt from sklearn.feature_selection import chi2 from sklearn.feature_selection import f_classif from math import * plt.style.use('ggplot') fig = plt.figure() COUNTER = 1 #Return the category dictionary,categorical variables l...
61351
from qsearch import Project, solvers, unitaries, utils, multistart_solvers, parallelizers, compiler, options import scipy as sp import os try: from qsrs import BFGS_Jac_SolverNative, LeastSquares_Jac_SolverNative except ImportError: BFGS_Jac_SolverNative = None LeastSquares_Jac_SolverNative = None import p...
61356
import os import numpy as np def save_samples_truncted_prob(fname, points, prob): ''' Save the visualization of sampling to a ply file. Red points represent positive predictions. Green points represent negative predictions. Parameters fname: File name to save points: [N, 3] array o...
61386
from vulkan import vk, helpers as hvk class Renderer(object): def __init__(self, engine): self.engine = engine self.image_ready = None self.rendering_done = None self.render_fences = () self.render_cache = {} self.enabled = True self._setup_sync() ...
61435
import sys from collections import namedtuple, defaultdict import concrete from concrete.util import CommunicationReader import numpy as np import json Mention = namedtuple("Mention", "text start end sentence entityType confidence uuid") def get_entities(comm, entity_tool): """ Returns: list of concrete.Entity o...
61441
import os from koala.server import koala_host from koala.server.fastapi import * from sample.fastapi.http_api import * import sample.player koala_host.init_server(globals().copy(), f"{os.getcwd()}/sample/app.yaml") koala_host.use_pd() koala_host.listen_fastapi() koala_host.run_server()
61464
from pyspark.sql.types import ( ArrayType, IntegerType, StringType, StructField, StructType, ) from butterfree.extract.pre_processing import explode_json_column from butterfree.testing.dataframe import ( assert_dataframe_equality, create_df_from_collection, ) def test_explode_json_column(...
61470
ROTATED_PROXY_ENABLED = True PROXY_STORAGE = 'scrapy_rotated_proxy.extensions.file_storage.FileProxyStorage' PROXY_FILE_PATH = '' # PROXY_STORAGE = 'scrapy_rotated_proxy.extensions.mongodb_storage.MongoDBProxyStorage' PROXY_MONGODB_HOST = '127.0.0.1' PROXY_MONGODB_PORT = 27017 PROXY_MONGODB_USERNAME = None PROXY_MONGOD...
61540
import sys import os sys.path.append(os.path.abspath("./")) from nnst import downloader as downloader import pprint import argparse import nnst.nnst as nnst parser=argparse.ArgumentParser() parser.add_argument('--csv_path', help='csv파일 경로') parser.add_argument('--date', help='시작할 뉴스 일자') parser.add_argument('--num', ...
61554
import pytest import aos_version from collections import namedtuple Package = namedtuple('Package', ['name', 'version']) expected_pkgs = { "spam": { "name": "spam", "version": "3.2.1", "check_multi": False, }, "eggs": { "name": "eggs", "version": "3.2.1", "c...
61564
import torch import torch.nn.functional as F __all__ = ['kl_loss', 'huber_loss'] def kl_loss(x, y): x = F.softmax(x.detach(), dim=1) y = F.log_softmax(y, dim=1) return torch.mean(torch.sum(x * (torch.log(x) - y), dim=1)) def huber_loss(error, delta): abs_error = torch.abs(error) quadratic = tor...
61586
from . import BasicType class MaskPosition(BasicType): fields = { 'point': str, 'x_shift': str, 'y_shift': str, 'scale': str } def __init__(self, obj=None): super(MaskPosition, self).__init__(obj) @classmethod def a(cls, point: str, x_shift: str, y_shift: ...
61589
import os from setuptools import setup, find_packages base_dir = os.path.dirname(os.path.abspath(__file__)) setup( name='hcipy', version="0.0.1", description="A pure python library for Bluetooth LE that has minimal dependencies.", #long_description="\n\n".join([ # open(os.path.join(base_dir, "R...
61595
from chemeco.wrappers.database import sklearn_db from chemeco.wrappers.database import cheml_db from chemeco.wrappers.database import pandas_db import inspect def tshf(): """ tshf stands for the combination of task, subtask, host, and function :return: combination, dictionary of the aforementioned combinat...
61603
import logging import click from kfp import dsl from typing import List, Dict, Callable import kfp.dsl as dsl from hypermodel.hml.hml_pipeline import HmlPipeline from hypermodel.hml.hml_container_op import HmlContainerOp from hypermodel.platform.abstract.services import PlatformServicesBase @click.group(name="pipel...
61614
import os import requests from urllib.error import URLError from urllib.parse import urlparse from urllib.request import urlopen from luigi import Target, LocalTarget from hashlib import sha1 from tasks.util import (query_cartodb, underscore_slugify, OBSERVATORY_PREFIX, OBSERVATORY_SCHEMA) from tasks.meta import (OB...
61622
from flask_wtf import FlaskForm from wtforms import HiddenField, FloatField, SelectField, StringField, SubmitField, ValidationError from wtforms.ext.sqlalchemy.fields import QuerySelectField from wtforms.validators import Length, Optional, Required from .. models import EventFrameAttributeTemplate, Lookup, LookupValue,...
61645
from __future__ import print_function def one(a=123, b='234', c={'3': [4, '5']}): for i in range(1): # one a = b = c['side'] = 'effect' two() def two(a=123, b='234', c={'3': [4, '5']}): for i in range(1): # two a = b = c['side'] = 'effect' three() def three(a=123, b='234'...
61670
from __future__ import absolute_import, division, print_function, unicode_literals import os print("VAR is '{}'".format(os.environ["VAR"]))
61685
class CRSError(Exception): pass class DriverError(Exception): pass class TransactionError(RuntimeError): pass class UnsupportedGeometryTypeError(Exception): pass class DriverIOError(IOError): pass
61697
import pprint from pathlib import Path from typing import Optional import typer from embeddings.defaults import RESULTS_PATH from embeddings.evaluator.sequence_labeling_evaluator import SequenceLabelingEvaluator from embeddings.pipeline.flair_sequence_labeling import FlairSequenceLabelingPipeline app = typer.Typer()...
61805
import os from rlib.streamio import open_file_as_stream from rlib.string_stream import StringStream from som.compiler.class_generation_context import ClassGenerationContext from som.interp_type import is_ast_interpreter if is_ast_interpreter(): from som.compiler.ast.parser import Parser else: from som.compile...
61827
import numpy as np from opytimizer.optimizers.swarm import sso from opytimizer.spaces import search def test_sso_params(): params = { 'C_w': 0.1, 'C_p': 0.4, 'C_g': 0.9 } new_sso = sso.SSO(params=params) assert new_sso.C_w == 0.1 assert new_sso.C_p == 0.4 assert ne...
61830
import matplotlib.pyplot as plt import netomaton as ntm import numpy as np if __name__ == '__main__': # NKS page 443 - Rule 122R network = ntm.topology.cellular_automaton(n=100) # carefully chosen initial conditions previous_state = [1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, ...
61831
import argparse import csv import sys import os sys.path.append(os.path.dirname(os.path.dirname(__file__))) from modules.metric import mean_reciprocal_rank def main(csv_path): acc = 0 num = 0 with open(csv_path, "r") as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count ...
61838
class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: tasksDict = collections.Counter(tasks) heap = [] c = 0 for k, v in tasksDict.items(): heappush(heap, (-v, k)) while heap: i = 0 stack = [] while i <= n: ...
61886
import tensorflow as tf import numpy as np from blackbox_mpc.optimizers.optimizer_base import OptimizerBase class PSOOptimizer(OptimizerBase): def __init__(self, env_action_space, env_observation_space, planning_horizon=50, max_iterations=5, population_size=500, num_agents=5, c1=...
61906
import os from factory import create_app app = create_app() app.app_context().push() @app.teardown_request def teardown_request(*args, **kwargs): 'Expire and remove the session after each request' from database import db db.session.expire_all() db.session.remove() if 'Development' in os.environ.g...
61948
from bagua.torch_api.contrib.cached_dataset import CachedDataset from torch.utils.data.dataset import Dataset import numpy as np import logging import unittest from tests import skip_if_cuda_available logging.basicConfig(level=logging.DEBUG) class MyDataset(Dataset): def __init__(self, size): self.size =...
61970
from glyphNameFormatter.data.scriptPrefixes import scriptPrefixes def process(self): if self.has("LATIN"): self.scriptTag = scriptPrefixes['latin'] if self.has("ARMENIAN"): # self.scriptTag = scriptPrefixes['armenian'] self.processAs("Armenian") elif self.has("HEBREW"): # s...
62005
from .Setup import EngineSetup from Core.GlobalExceptions import Exceptions from Services.NetworkRequests import requests from Services.Utils.Utils import Utils class ClipDownloader(EngineSetup): def run(self): try: self.download() except: self.status.raiseError(Exception...
62011
from datetime import date from typing import Type import pytest import sympy from sympy import Interval, oo from nettlesome.entities import Entity from nettlesome.predicates import Predicate from nettlesome.quantities import Comparison, Q_, Quantity class TestComparisons: def test_comparison_with_wrong_comparis...
62033
from copy import deepcopy from hashlib import sha256 import os import unittest from google.protobuf.timestamp_pb2 import Timestamp from blindai.pb.securedexchange_pb2 import ( Payload, ) from blindai.client import ( RunModelResponse, UploadModelResponse, ) from blindai.dcap_attestation import Policy from ...
62036
from setuptools import find_packages, setup PACKAGE_NAME = "up-bank-api" VERSION = "0.3.2" PROJECT_URL = "https://github.com/jcwillox/up-bank-api" PROJECT_AUTHOR = "<NAME>" DOWNLOAD_URL = f"{PROJECT_URL}/archive/{VERSION}.zip" PACKAGES = find_packages() with open("README.md", "r", encoding="UTF-8") as file: LONG_...
62075
import numpy as np from scipy.stats import binom # import modules needed for logging import logging import os logger = logging.getLogger(__name__) # module logger def cummin(x): """A python implementation of the cummin function in R""" for i in range(1, len(x)): if x[i-1] < x[i]: x[i] = ...
62081
import io from flask import ( Blueprint, render_template, abort, current_app, make_response ) import numpy as np from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure client = Blueprint('client', __name__, template_folder='templates', ...
62104
from utils import * from block_descriptor import * from Crypto.Cipher import AES import hashlib import cStringIO import gzip import json import gzip_mod import os class Image: def __init__(self, image_data, read=True): self.stream = cStringIO.StringIO(image_data) self.stream_len = le...
62106
from .genoabc import AlleleContainer from .alleles import Alleles from .sparsealleles import SparseAlleles from .chromosometemplate import ChromosomeTemplate, ChromosomeSet from .labelledalleles import LabelledAlleles, InheritanceSpan, AncestralAllele
62147
from .exception import AuthFailedException from .client import default_client def init(client=default_client): """ Init configuration for SocketIO client. Returns: Event client that will be able to set listeners. """ from socketIO_client import SocketIO, BaseNamespace from . import ge...
62174
from datetime import datetime import logging from weconnect.addressable import AddressableAttribute, AddressableList from weconnect.elements.generic_settings import GenericSettings from weconnect.util import robustTimeParse LOG = logging.getLogger("weconnect") class ChargingProfiles(GenericSettings): def __init...
62213
import cv2 as cv import numpy as np from PIL import Image import os import time import os import concurrent.futures #used for resizing, it will resize the image maintaining aspect ratio # to the smallest dimension, my images were 5000 by 1000, so it gets shrunk to # 40 px tall and an unknown width. size = (...
62219
class Solution: def sortArray(self, nums: List[int]) -> List[int]: temp = [0] * len(nums) def mergeSort(start, end): if start < end: mid = (start + end) // 2 mergeSort(start, mid) mergeSort(mid + 1, end) i = k = start ...