id
stringlengths
3
8
content
stringlengths
100
981k
430485
import time log_filename = '/code/log/django.log' # log_filename = 'log/django.log' with open(log_filename) as file: while 1: where = file.tell() line = file.readline() if not line: time.sleep(1) file.seek(where) else: print(line) # already has ...
430491
import secrets from typing import Tuple from urllib.parse import quote_plus import aiohttp from quart import Blueprint, g from quart import jsonify as json from quart import redirect, request, session auth = Blueprint("auth", __name__) API_BASE = "https://discordapp.com/api/v6" def redirect_url() -> Tuple[str, str]...
430547
from ._expquad_gauss import _kernel_mean_expquad_gauss, _kernel_variance_expquad_gauss from ._expquad_lebesgue import ( _kernel_mean_expquad_lebesgue, _kernel_variance_expquad_lebesgue, ) from ._kernel_embedding import KernelEmbedding
430554
from river import compose, preprocessing def test_left_is_pipeline(): group_1 = compose.Select("a", "b") group_2 = compose.Select("x", "y") | preprocessing.OneHotEncoder(sparse=True) product = group_1 + group_2 + group_1 * group_2 assert product.transform_one(dict(a=1, b=2, x=4, y=4, z=5)) == { ...
430571
from typing import Any import torch import numpy as np def herd_random(x: np.ndarray, y: np.ndarray, t: np.ndarray, z: Any, nb_per_class: int) -> np.ndarray: """Herd randomly examples for rehearsal. :param x: Input data (images, paths, etc.) :param y: Labels of the data. :param t: Task ids of the da...
430610
import subprocess,os,sys import tmp as sprint def main(): #import subprocess,os,sys print '' print "##############################################################################################" print '' print " SPRINT: SNP-free RNA editing Identification Toolkit" print "" print " ...
430623
import numpy as np import torch from torch.autograd import Variable import matplotlib.pyplot as plt from matplotlib.image import imread #from dataset_loader import * import skimage #load parameters theta from file def load_theta_npy(path, num_stages): theta = np.load(path) theta = np.reshape(theta, (num_stage...
430669
from typing import Any, Dict from uuid import UUID from eventsourcing.application import Application from eventsourcing.examples.aggregate5.domainmodel import Dog class DogSchool(Application): is_snapshotting_enabled = True def register_dog(self, name: str) -> UUID: event = Dog.register(name) ...
430696
import pymel.core as pm from pulse.buildItems import BuildAction, BuildActionError class DisplayLayerAction(BuildAction): def validate(self): if not len(self.name): raise BuildActionError('name cannot be empty') def run(self): layer = pm.ls(self.name) if len(layer) and i...
430732
from selenium import webdriver from selenium.webdriver import ActionChains from os import path #NOTE: this demo uses images under images subfolder to find by name. # Be sure to configure AutoPyDriverServer to use that folder for images by name driver = webdriver.Remote( command_executor='http://127.0.0.1:4723/wd/hub...
430743
import math from .conllu_wrapper import parse_conllu, serialize_conllu, parse_odin, conllu_to_odin, parsed_tacred_json from .converter import Convert, get_conversion_names as inner_get_conversion_names, init_conversions from spacy.language import Language from .spacy_wrapper import parse_spacy_sent, enhance_to_spacy_d...
430754
from abc import abstractmethod import numpy as np import pandas as pd from mizarlabs.static import EVENT_END_TIME from mizarlabs.transformers.utils import check_missing_columns from mizarlabs.transformers.utils import convert_to_timestamp from numba import jit from numba import prange from scipy.stats import norm from...
430784
import ptypes from ptypes import ptype,parray,pstruct,pint,pstr,dyn,pbinary ptypes.setbyteorder(ptypes.config.byteorder.littleendian) ### header markers class ElfXX_File(ptype.boundary): pass class ElfXX_Header(ptype.boundary): pass class ElfXX_Ehdr(ElfXX_Header): pass ### base class uchar(pint.uint8_t): pass class E...
430788
import pandas as pd import numpy as np import torch import matplotlib.pyplot as plt import os import sys sys.path.append(os.path.join("..", "..")) from torchid.ssfitter import NeuralStateSpaceSimulator from torchid.ssmodels import CartPoleStateSpaceModel from torchid.util import get_sequential_batch_idx if __name__ ...
430796
import os import nltk import pandas as pd from nltk.stem.lancaster import LancasterStemmer from sklearn.metrics.pairwise import cosine_similarity from sklearn.model_selection import train_test_split as tts from sklearn.preprocessing import LabelEncoder as LE from sklearn.svm import SVC from vectorizers.factory import...
430872
from oi import util def test_qsplit(): tests = [ ('one', ['one']), (' one ', ['one']), (' " one " ', ['one']), ('one two', ['one', 'two']), ('one two', ['one', 'two']), ('one "two three" four', ['one', 'two three', 'four']), ('1 2 "3 4" 5 6 "7 8"', ['1', '...
430911
import os import pytest import types from pnlp.piop import write_json, write_file from pnlp.piop import Reader, read_file, read_lines, read_json, read_yaml, read_csv from pnlp.piop import check_dir DATA_PATH = os.path.join('tests', 'piop_data') @pytest.fixture(params=['*.md', '*.txt', '*.data', 'f*.*', '*c.*']) def...
430919
from django.contrib import admin from .models import Debtor, Invoice admin.site.register(Debtor) admin.site.register(Invoice)
430932
from setuptools import setup with open("../README.md", 'r') as f: long_description = f.read() setup( name='tensor_classification', version='0.0.1', description='Code for tensor classification', license="MIT", long_description=long_description, author='<NAME> and <NAME>', ...
430951
import torch import torch.nn as nn import numpy as np from .base import Learner from .aggregator import SSARAggregator, FrameStackPreprocessor from surreal.model.ddpg_net import DDPGModel from surreal.session import BASE_LEARNER_CONFIG, ConfigError import surreal.utils as U import torchx as tx class DDPGLearner(Learn...
431029
from django.db import models # Create your models here. class Model_example(models.Model): id = models.AutoField(primary_key=True) subject = models.CharField(max_length=100) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.su...
431047
import csv import sqlite3 from path import Path # this script sorts the images in one folder using the output of the NIMA scripts # you need to have a csv file containing the results (RESULTS_CSV) # and a collection in lightroom containing the images of the folder you # analyzed DEFAULT_CATALOG = r's:\Pictures\Lightr...
431059
from pyapproxmc import Counter def minimal_test(): counter = Counter(seed=2157, epsilon=0.8, delta=0.2) counter.add_clause(list(range(1,100))) assert counter.count() == (512, 90) def sampling_set_test(): counter = Counter(seed=2157, epsilon=0.8, delta=0.2, sampling_set=list(range(1,50))) counter.a...
431081
import torch from torch.utils.data import Dataset class LatentsDataset(Dataset): def __init__(self, latents, opts, transforms=None): self.latents = latents self.transforms = transforms self.opts = opts def __len__(self): return self.latents.shape[0] def __getitem__(self, index): if self.transforms is ...
431114
from insights.tests import context_wrap from insights.parsers.httpd_log import HttpdSSLErrorLog, HttpdErrorLog from insights.parsers.httpd_log import HttpdSSLAccessLog, HttpdAccessLog from datetime import datetime SSL_ACCESS_LOG = """ 10.68.5.20 - - [29/Mar/2017:05:57:21 -0400] "GET / HTTP/1.1" 403 202 "-" "Mozilla/5...
431158
import spacy # from spacy.lang.en.stop_words import STOP_WORDS # Imports Default List of Stop Words # STOP_WORDS.add("ORION") # This adds # Imports List of Custom Stop Words with open("watchfilter.txt", "r") as filter: custom_stop_words = filter.read().splitlines() # Init spaCy Language Model + Example Title nl...
431177
from .exportacquisitioncsv import export_acquisition_csv from .mcdfolder2imcfolder import mcdfolder_to_imcfolder from .ome2analysis import omefile_2_analysisfolder, omefolder_to_analysisfolder from .ome2histocat import ( omefile_to_histocatfolder, omefile_to_tifffolder, omefolder_to_histocatfolder, ) from ....
431189
from copy import deepcopy import numpy as np from const import * from data_loader import to_tensor, to_numpy class TreeNode(object): def __init__(self, action=None, props=None, parent=None): self.parent = parent self.action = action sel...
431225
from __future__ import annotations from enums.embedtype import EmbedType from pydantic import BaseModel from ..color import Color class EmbedFooter(BaseModel): icon_url: str proxy_icon_url: str text: str class EmbedField(BaseModel): inline: bool name: str value: str class EmbedThumbnail(...
431258
img_norm_cfg = dict( mean=[127.5, 127.5, 127.5], std=[127.5, 127.5, 127.5], to_rgb=False) crop_size = (288, 960) # KITTI config kitti_train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', sparse=True), dict( type='ColorJitter', asymmetric_prob=0.0, bri...
431306
YOLO = dict() # Datasets Parameter YOLO['classes'] = ["aeroplane", "bicycle", "bird", "boat", "bottle"] YOLO['datasets_path'] = '/home/tshzzz/disk_m2/jinnan_round2/datasets/round1_train/' YOLO['anno_path'] = '/home/tshzzz/disk_m2/jinnan_round2/datasets/round1_train/jinnan_round1_train.json' YOLO['val_path'] = '/home/...
431341
import inspect import re import time from types import FunctionType from typing import List from dataframe_sql.tests.pandas_sql_functionality_test import * # noqa DONT_TEST = [ test_add_remove_temp_table, # noqa test_for_valid_query, # noqa test_for_non_existent_table, # noqa ] INDENT_REGEX = re.compi...
431348
from data import payloads def breakline(): print("------------------------------------------------------------") def payloadReplace(llist,lvar,rvar): rlist = [] for i in llist: rlist.append(i.replace(lvar, rvar)) return rlist
431351
from django import forms from ... import models from wazimap_ng.general.admin.forms import HistoryAdminForm class IndicatorAdminForm(HistoryAdminForm): groups = forms.ChoiceField(required=True) class Meta: model = models.Indicator fields = '__all__' def __init__(self, *args, **kwargs): ...
431356
from django.core.management.base import BaseCommand, CommandError from register.models import RegistrationCenter class Command(BaseCommand): help = """ Set the reg_open parameter for 1 or more subconstituencies. Open all centers: set_reg_open --all Close all centers: set_reg_open --fals...
431384
import os from datetime import timedelta from airflow import DAG from airflow.contrib.operators.emr_add_steps_operator import EmrAddStepsOperator from airflow.contrib.operators.emr_create_job_flow_operator import EmrCreateJobFlowOperator from airflow.contrib.sensors.emr_step_sensor import EmrStepSensor from airflow.mo...
431420
from .combine_slices import combine_slices, sort_by_slice_position from .exceptions import DicomImportException from .version import __version__ __all__ = [ 'combine_slices', 'sort_by_slice_position', 'DicomImportException', '__version__' ]
431535
import os from typing import Callable, List import pickle import multiprocessing as mp from functools import partial from .._logger import progress_bar __all__ = [ 'load_pickle', 'save_pickle', ] def load_pickle(path: str): """ Load pickle from path. Args: path (str): Path to the pickle...
431559
import argparse import json import os from stix2.v20 import Bundle import requests def save_bundle(bundle, path): """helper function to write a STIX bundle to file""" print(f"{'overwriting' if os.path.exists(path) else 'writing'} {path}... ", end="", flush=True) with open(path, "w", encoding="utf-8") as ...
431581
import os import urllib.request import librosa import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from torchlibrosa.augmentation import SpecAugmentation from torchlibrosa.stft import Spectrogram, LogmelFilterBank from rainforest.config import SAMPLE_RATE, N_FFT, ...
431602
from typing import Optional from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.orm import column_property from sqlalchemy.orm import deferred from sqlalchemy.orm import registry from sqlalchemy.orm import Session from sqlalchemy.orm import synonym from sqlalchemy...
431613
import discord from discord.ext import commands from random import randint, sample, shuffle, choice import os import json from typing import List, Dict, Optional, Any, Union import asyncio from extra import utils from extra.slothclasses.player import Player from extra.minigames.connect_four import ConnectFour from ex...
431629
import unittest try: from unittest import mock except ImportError: import mock from betamax.adapter import BetamaxAdapter from requests.adapters import HTTPAdapter class TestBetamaxAdapter(unittest.TestCase): def setUp(self): http_adapter = mock.Mock() self.adapters_dict = {'http://': ht...
431713
from builtins import complex import pytest from json_to_models.dynamic_typing import DUnion, StringLiteral, get_hash_string # *args | MetaData test_dunion = [ pytest.param( [int, int], DUnion(int), id="unique_types" ), pytest.param( [int, DUnion(int)], DUnion(int),...
431798
import torch import torch.nn as nn """ @article{vandeven2019three, title={Three scenarios for continual learning}, author={<NAME>, <NAME> and <NAME>}, journal={arXiv preprint arXiv:1904.07734}, year={2019} } @article{vandeven2018generative, title={Generative replay with feedback connections as a general str...
431829
from DemoApp import App import wx #from gui import skin as skincore from gui.uberwidgets.simplemenu import SimpleMenu,SimpleMenuItem from gui.uberwidgets.UberButton import UberButton class Frame(wx.Frame): def __init__(self): wx.Frame.__init__(self,None,title='Simple Menu Test') self.panel=wx.Panel...
431853
from zentral.utils.apps import ZentralAppConfig class ZentralAccountsAppConfig(ZentralAppConfig): name = "accounts" verbose_name = "Zentral accounts app" permission_models = ("user",)
431911
import os.path as osp from PIL import Image from torch.utils.data import Dataset from torchvision import transforms import os import torch import random import numpy as np class MiniImageNet(Dataset): def __init__(self, setname, args): IMAGE_PATH = os.path.join(args.data_dir, 'miniimagenet/images') ...
431914
import argparse import hashlib from functools import partial import aioredis async def redis_create_connection(connection_string: str): async def redis_create_index(connection): try: await connection.execute( "FT.CREATE", "s3_index", "SCHEMA", ...
431916
from smol_evm.constants import MAX_UINT256 from smol_evm.context import ExecutionContext, Calldata from smol_evm.opcodes import CALLDATALOAD, CALLDATASIZE from shared import with_stack_contents, with_calldata import pytest @pytest.fixture def calldata() -> Calldata: return Calldata() @pytest.fixture def context(...
431920
import numpy as np from brancher.standard_variables import DirichletVariable, GeometricVariable, Chi2Variable, \ GumbelVariable, HalfCauchyVariable, HalfNormalVariable, NegativeBinomialVariable, PoissonVariable, StudentTVariable, UniformVariable, BernoulliVariable ## Distributions and samples ## a = DirichletVari...
431925
import os from datetime import datetime from typing import Any, Optional def load_file( file_path: Optional[str] = None, mode: str = "r", loader: Any = None ) -> Any: """ Safely load a file. :param file_path: The path to the file to load. :type file_path: [type] :param mode: The mode to use w...
431946
import tensorflow as tf import numpy as np from .NeuronLayer import * from .DenseLayer import * #inverse softplus transformation def softplus_inverse(x): return x + np.log(-np.expm1(-x)) #radial basis function expansion class RBFLayer(NeuronLayer): def __str__(self): return "radial_basis_function_laye...
431958
from typing import Optional from pydantic import BaseModel, validator from pydantic.fields import ModelField from app.model.recursive_data import RecursiveDataModel, PotentialDataModelKeysMixin class InvalidEligiblityError(ValueError): """Exception thrown in case the eligibility check failed.""" pass def ...
431961
from qupulse.hardware.dacs.dac_base import * try: from qupulse.hardware.dacs.alazar import * except ImportError: pass
431967
import numpy as np import os.path as osp from torch_geometric.utils.num_nodes import maybe_num_nodes import torch import unittest from pd_mesh_net.nn import DualPrimalEdgePooling from pd_mesh_net.utils import create_graphs, create_dual_primal_batch current_dir = osp.dirname(__file__) class TestDualEdgePooling(unitt...
432002
import numpy as np from sklearn.metrics import f1_score, confusion_matrix """ Evalution Metrics: F1 score, accuracy and CCC borrow from https://github.com/wtomin/Multitask-Emotion-Recognition-with-Incomplete-Labels/ """ epsilon = 1e-5 def averaged_f1_score(input, target): N, label_size = input.shap...
432038
from mongoengine import * from datetime import datetime class BaseDocument(Document): meta = { 'abstract': True } # last updated timestamp updated_at = DateTimeField(default=datetime.now) # timestamp of when entry was created created_at = DateTimeField(default=datetime.now) def ...
432052
import os import sys import datetime from functools import partial from multiprocessing.dummy import Pool from subprocess import call command_file = sys.argv[1] commands = [line.rstrip() for line in open(command_file)] report_step = 32 pool = Pool(report_step) for idx, return_code in enumerate(pool.imap(partial(call,...
432104
import subprocess import os import optparse # This script changes test run classpath by unpacking tests.jar -> tests-dir. The goal # is to launch tests with the same classpath as maven does. def parse_args(): parser = optparse.OptionParser() parser.disable_interspersed_args() parser.add_option('--jar-bi...
432201
import io import logging import matplotlib.pyplot as plt import numpy as np try: from pygifsicle import optimize except ImportError: pass try: import imageio except ImportError: pass logger = logging.getLogger(__name__) def kwargs_log_scale(unique_val, mode="equidistant", base=None): """Retur...
432221
from abc import ABC import json import inspect import logging from hashlib import sha1 import attr from dateutil import parser as DateTimeParser from ..utils import SmartJSONEncoder from ..exceptions import EndpointFactoryException @attr.s(cmp=False, hash=False) class AttrSerializable(ABC): """ Provides id, h...
432251
from rest_framework import permissions from tacticalrmm.permissions import _has_perm class ManageClientsPerms(permissions.BasePermission): def has_permission(self, r, view): if r.method == "GET": return True return _has_perm(r, "can_manage_clients") class ManageSitesPerms(permissio...
432261
from flask import Flask, request, jsonify import paramiko import time import telepot from librouteros import connect import MySQLdb as mdb app = Flask(__name__) @app.route('/configure', methods=['POST']) def configure(): dats = request.get_json() ip = dats['ip_router'] username = 'admin' password = '...
432336
import numpy as np import pytest from sklearn.datasets import make_blobs from incdbscan import IncrementalDBSCAN EPS = 1.5 @pytest.fixture def incdbscan3(): return IncrementalDBSCAN(eps=EPS, min_pts=3) @pytest.fixture def incdbscan4(): return IncrementalDBSCAN(eps=EPS, min_pts=4) @pytest.fixture def bl...
432339
import unittest import at_checks import daemons_check import modem_checks import python_checks import sim_checks import simple_cmd_checks from plmn.utils import * from plmn.results import * if __name__ == '__main__': nargs = process_args() suite = unittest.TestSuite() # Add all regression test-cases to...
432350
from enum import Enum class triggerConditions(Enum): # values over 1000 are initiated by the player (e.g. 'WHENEVER a creature etb...') # 2000+ are controller specific; 1000+ are game/any-player specific # otherwise the conditions refer to the card itself # e.g. onDiscard means when THIS card is disc...
432365
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import h5py import argparse from tqdm import tqdm def merge(config): dir_name = os.path.join('datasets/', config.dir_name) check_path(dir_name) f = h5py.File(os.path.join(dir_name, 'da...
432370
def main(request, response): allow = request.GET.first(b"allow", b"false") headers = [(b"Content-Type", b"application/javascript")] if allow != b"false": headers.append((b"Access-Control-Allow-Origin", b"*")) body = b""" function handleRejectedPromise(promise) { promise.catch(() => ...
432378
import os, argparse, glob import numpy as np import cv2 from scipy.misc import imread, imsave from skimage.measure import compare_ssim import psnr import fastaniso import py_utils as utils parser = argparse.ArgumentParser() parser.add_argument('--input_root', default='') parser.add_argument('--dir_list', default='di...
432458
from .property import LiteralProperty import packaging.version as pv import rdflib class VersionProperty(LiteralProperty): def convert_to_user(self, value): result = str(value) if result == '': # special case, empty strings are equivalent to None return None return...
432507
CASSANDRA_VERSION = "3.11.11" CASSANDRA_DEB_VERSION = CASSANDRA_VERSION + "_all" DNSMASQ_VERSION = "2.80-1" DNSMASQ_DEB_VERSION = DNSMASQ_VERSION + "+deb10u1" ELASTICSEARCH_VERSION = "7.3.1" ENVOY_VERSION = "1.15.5" ERLANG_VERSION = "22.3.4.9-1" ERLANG_DEB_VERSION = ERLANG_VERSION + "" GERRIT_VERSION = "3.4.0" GR...
432515
import itertools import os import pickle from soap import logger from soap.common import timeit from soap.flopoco.common import ( flopoco_operators, operators_map, we_range, wf_range, wi_range, flopoco_key, flopoco, xilinx, default_file ) from soap.semantics import IntegerInterval, ErrorSemantics INVALID = -...
432533
from builtins import object import json import logging import ckanext.harvest.model as harvest_model import mock_static_file_server from ckan import model from ckanext.geodatagov.harvesters.base import GeoDataGovWAFHarvester from factories import HarvestJobObj, WafHarvestSourceObj from ckan.tests.helpers import reset...
432546
import sys import numpy as np from vispy import scene from .axes import AxesVisual3D from ..utils import NestedSTTransform from matplotlib.colors import ColorConverter from glue.config import settings rgb = ColorConverter().to_rgb LIMITS_PROPS = [coord + attribute for coord in 'xyz' for attribute in ['_min', '_ma...
432547
import logging from datetime import datetime from pathlib import Path from bs4 import BeautifulSoup from .. import utils from ..cache import Cache __authors__ = [ "zstumgoren", "Dilcia19", "stucka", ] __tags__ = ["html"] __source__ = { "name": "Connecticut Department of Labor", "url": "https://ww...
432549
import system def solver(n, node): node.sort() queue = node[0] while queue: curNode = queue.pop() count = 1 for n in node: pass
432588
import algopy, numpy def house(x): """ computes the Householder vector v and twice its norm beta (v,beta) = house(x) Parameters ---------- x: array_like len(x) = N Returns ------- v: array_like len(v) = N beta: Float two times the 2-norm o...
432598
from magma import * from .logic import DefineInvert, Not from .fulladder import FullAdder __all__ = ['DefineAdd'] __all__ += ['DefineSub'] __all__ += ['DefineNegate'] def _AdderName(basename, n, cin, cout): name = f"{basename}{n}" if cin: name += '_CIN' if cout: name += '_COUT' return name def _Add...
432618
import i2c_bus, unit from micropython import const import ustruct _ADDR = const(0x27) _INPUT_REG = const(0x00) _OUTPUT_REG = const(0x01) _POLINV_REG = const(0x02) _CONFIG_REG = const(0x03) class Ext_io: ALL_OUTPUT = const(0x00) ALL_INPUT = const(0xff) OUTPUT = const(0x00) INPUT = const(0x01) def...
432627
import os.path import numpy as np import base64 __all__ = ['data'] class Data(object): BASE_DIR = os.path.join(os.path.dirname(__file__), 'data') def __init__(self): self._dt = {} def __getitem__(self, item): if item in self._dt: return self._dt[item] file_path = os...
432648
from django.shortcuts import render, redirect from . import forms from .models import District, Upazilla, Union, PersonalInfo # Create your views here. def load_upazilla(request): district_id = request.GET.get('district') upazilla = Upazilla.objects.filter(district_id=district_id).order_by('name') upazi...
432655
from io import StringIO from OpenGL.GL import * import gl import gx MATRIX_INDEX_ATTRIBUTE_LOCATION = 0 POSITION_ATTRIBUTE_LOCATION = 1 NORMAL_ATTRIBUTE_LOCATION = 2 BINORMAL_ATTRIBUTE_LOCATION = 3 TANGENT_ATTRIBUTE_LOCATION = 4 COLOR_ATTRIBUTE_LOCATION = 5 TEXCOORD_ATTRIBUTE_LOCATIONS = [6,7,8,9,10,11,12,13] ATTRIB...
432705
import unittest from conda_env import env from conda_env.specs.notebook import NotebookSpec from ..utils import support_file class TestNotebookSpec(unittest.TestCase): def test_no_notebook_file(self): spec = NotebookSpec(support_file('simple.yml')) self.assertEqual(spec.can_handle(), False) d...
432727
import torch import torch.nn as nn import torchvision.models as backbone_ class EncoderCNN(nn.Module): def __init__(self, hp=None): super(EncoderCNN, self).__init__() self.feature = Unet_Encoder(in_channels=3) self.fc_mu = nn.Linear(512, 128) self.fc_std = nn.Linear(512, 128) ...
432840
from geth.accounts import parse_geth_accounts raw_accounts = b"""Account #0: {<KEY>} Account #1: {<KEY>}\n""" accounts = (b"<KEY>", b"0x6f137a71a6f197df2cbbf010dcbd3c444ef5c925") def test_parsing_accounts_output(): assert parse_geth_accounts(raw_accounts) == accounts
432884
import os from PIL import Image, ImageDraw, ImageFont from django.conf import settings def saveTargetImage(letters, pk): height = 300 width = 300 image = Image.new(mode='L', size=(height, width), color=255) draw = ImageDraw.Draw(image) x = 0 y_start = 0 y_end = image.height line = ((x...
432906
from invoke import run, task @task def clean(): run('cd docs && make clean') @task def docs(): run('cd docs && make html') @task def package(): run('python setup.py sdist') run('python setup.py bdist_wheel') @task def package_upload(): run('python setup.py sdist upload') run('python setu...
432922
import copy from pybbn.graph.jointree import JoinTreeListener from pybbn.pptc.initializer import Initializer from pybbn.pptc.moralizer import Moralizer from pybbn.pptc.potentialinitializer import PotentialInitializer from pybbn.pptc.propagator import Propagator from pybbn.pptc.transformer import Transformer from pybbn...
432999
import asyncio import asynctnt def get_push_iterator(connection): fut = connection.call("infinite_push_loop", push_subscribe=True) return fut, asynctnt.PushIterator(fut) async def main(): async with asynctnt.Connection(port=3301) as conn: fut, it = get_push_iterator(conn) transport_id =...
433045
from pyspark import since, keyword_only, SparkContext from pyspark.ml.param import Param, Params, TypeConverters from pyspark.ml.param.shared import HasInputCol, HasOutputCol, HasHandleInvalid from pyspark.ml.util import JavaMLReadable, JavaMLWritable from pyspark.ml.wrapper import _jvm from pyspark.ml.wrapper import J...
433087
import logging from py2neo import Graph class GraphDao: def __init__(self): self.g = Graph( host="127.0.0.1", # neo4j 搭载服务器的ip地址,ifconfig可获取到 http_port=7474, # neo4j 服务器监听的端口号 user="neo4j", # 数据库user name,如果没有更改过,应该是<PASSWORD>4j password="<PASSWORD>") ...
433094
import os import uuid import pytest import requests.exceptions from django_webdav_storage import storage def test_listdir_raises_not_implemented(settings): del settings.WEBDAV_LISTING_BACKEND webdav_storage = storage.WebDavStorage() with pytest.raises(NotImplementedError): webdav_storage.listd...
433123
import importlib.resources import pendulum import plotman.job import plotman.plotters.bladebit import plotman._tests.resources def test_byte_by_byte_full_load() -> None: read_bytes = importlib.resources.read_binary( package=plotman._tests.resources, resource="bladebit.plot.log", ) parse...
433170
from transformers.modeling_bert import BertLMPredictionHead, BertPreTrainedModel, BertModel from BERT.lm_finetune.grad_reverse_layer import GradReverseLayerFunction from BERT.bert_text_dataset import BertTextDataset from BERT.bert_pos_tagger import BertTokenClassificationDataset from torch.nn import CrossEntropyLoss im...
433172
from typing import Callable, List, Optional, Tuple, Union import numpy as np from scipy.interpolate import CubicSpline from .base import _Augmenter, _default_seed class Drift(_Augmenter): """ Drift the value of time series. The augmenter drifts the value of time series from its original values rand...
433179
import time import threading import os import playsound import random import json ftime=0 ptime=0 start = -1 with open('./config.json') as f: config = json.load(f) TIME = config['time']*60 a_files=os.listdir("./Audio_Files/") def input_func(): global ftime,ptime,start startevent.set() print(f"Welc...
433219
from django.core.mail import EmailMultiAlternatives from django.conf import settings from django.http import HttpResponse from django.template import Context from django.template.loader import render_to_string, get_template import json def sendEmailToken(request, token): variables = Context({ 'request': r...
433220
import sys import collections import random import string from io import StringIO from itertools import tee def import_class(cls): module = '.'.join(cls.split('.')[:-1]) cls = cls.split('.')[-1] module = __import__(module, fromlist=[module]) return getattr(module, cls) def random_ascii(length): ...
433224
class Solution: def letterCombinations(self, digits: str) -> List[str]: d = { 2:"abc", 3:"def", 4:"ghi", 5:"jkl", 6:"mno", 7:"pqrs", 8:"tuv", 9:"wxyz" } if digits == "": retu...