id
stringlengths
3
8
content
stringlengths
100
981k
10679
import numpy as np import matplotlib.pyplot as plt TOTAL = 200 STEP = 0.25 EPS = 0.1 INITIAL_THETA = [9, 14] def func(x): return 0.2 * x + 3 def generate_sample(total=TOTAL): x = 0 while x < total * STEP: yield func(x) + np.random.uniform(-1, 1) * np.random.uniform(2, 8) x += STEP def...
10726
from guniflask.config import settings from guniflask.web import blueprint, get_route @blueprint class ConfigController: def __init__(self): pass @get_route('/settings/<name>') def get_setting(self, name): return {name: settings[name]}
10791
import unittest import numpy as np from openmdao.utils.assert_utils import assert_near_equal from wisdem.optimization_drivers.dakota_driver import DakotaOptimizer try: import dakota except ImportError: dakota = None @unittest.skipIf(dakota is None, "only run if Dakota is installed.") class Te...
10832
import base64 import requests class RemotePkcs1Signer(object): """ Client-side Signer subclass, that calls the Signing Service over HTTP to sign things """ # standard headers for request headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } def __init__(s...
10893
from pudzu.charts import * from pudzu.sandbox.bamboo import * import seaborn as sns # generate map df = pd.read_csv("datasets/euvotes.csv").set_index('country') palette = tmap(RGBA, sns.cubehelix_palette(11, start=0.2, rot=-0.75)) ranges = [20000000,10000000,5000000,2000000,1000000,500000,200000,100000,0] def voteco...
10959
import sys import unittest sys.path.append("../main") from sshtransport import * class FakeSocket(object): def __init__(self): self.recv_buffer = b"" self.send_buffer = b"" def recv(self, n): resp = self.recv_buffer[:n] self.recv_buffer = self.recv_buffer[n:] return r...
10982
import numpy as np types = ["int", "float", "double"] def randi(*args): return np.random.randint(-10, 10, size=args) rngs = {"int": randi, "float": np.random.randn, "double": np.random.randn} embodiments = { "function": "R.%s(A,B).AllClose(C)", "op": "(A %s B).AllClose(C)", "inline_op": "(R = A, R ...
11000
import os.path import tcprepl import BigWorld def echo(s): '''Send string to client''' if tcprepl.write_client is not None: tcprepl.write_client(s) def exec_file(filename, exec_globals=None): ''' Execute file Try to find file named `filename` and execute it. If `exec_globals` is spec...
11024
import os.path as osp import sys import subprocess subprocess.call(['pip', 'install', 'cvbase']) import cvbase as cvb import torch from torch.autograd import gradcheck sys.path.append(osp.abspath(osp.join(__file__, '../../'))) from biupdownsample import biupsample_naive, BiupsampleNaive from biupdownsample import bid...
11047
import torch from torch import nn from torch.nn import functional as F class BicubicDownSample(nn.Module): def bicubic_kernel(self, x, a=-0.50): """ This equation is exactly copied from the website below: https://clouard.users.greyc.fr/Pantheon/experiments/rescaling/index-en.html#bicubic ...
11052
import nose2.tools from typing import Union from app.util import has_attributes class SampleClass: pass class TestUtil: @nose2.tools.params( ('SET_VALUE', True), (None, False), ('NO_ATTRIBUTE', False), (False, True), ('', True), (0, True), ) def test...
11065
import os class config: host = 'zhangxuanyang.zhangxuanyang.ws2.hh-c.brainpp.cn' username = 'admin' port = 5672 exp_name = os.path.dirname(os.path.abspath(__file__)) exp_name = '-'.join(i for i in exp_name.split(os.path.sep) if i); test_send_pipe = exp_name + '-test-send_pipe' test_recv_p...
11067
from btypes.big_endian import * cstring_sjis = CString('shift-jis') class Header(Struct): string_count = uint16 __padding__ = Padding(2) class Entry(Struct): string_hash = uint16 string_offset = uint16 def unsigned_to_signed_byte(b): return b - 0x100 if b & 0x80 else b def calculate_hash(s...
11118
r"""Train a neural network to predict feedback for a program string.""" from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import sys import random import numpy as np from tqdm import tqdm import torch import torch.optim as optim import torch.utils....
11138
import os from os import getcwd #---------------------------------------------# # 训练前一定要注意修改classes # 种类顺序需要和model_data下的txt一样 #---------------------------------------------# classes = ["cat", "dog"] sets = ["train", "test"] wd = getcwd() for se in sets: list_file = open('cls_' + se + '.txt', 'w')...
11160
from nerwhal.backends.flashtext_backend import FlashtextBackend from nerwhal.recognizer_bases import FlashtextRecognizer def test_single_recognizer(embed): class TestRecognizer(FlashtextRecognizer): TAG = "XX" SCORE = 1.0 @property def keywords(self): return ["abc", "c...
11161
import boto3 import sys import time import logging import getpass def new_rdsmysql(dbname, instanceID, storage, dbInstancetype, dbusername): masterPass = getpass.getpass('DBMasterPassword: ') if len(masterPass) < 10: logging.warning('Password is not at least 10 characters. Please try again') ...
11163
import pytest import cudf import mock from cuxfilter.charts.core.non_aggregate.core_non_aggregate import ( BaseNonAggregate, ) from cuxfilter.dashboard import DashBoard from cuxfilter import DataFrame from cuxfilter.layouts import chart_view class TestCoreNonAggregateChart: def test_variables(self): ...
11175
import numpy as np import ROOT from dummy_distributions import dummy_pt_eta counts, test_in1, test_in2 = dummy_pt_eta() f = ROOT.TFile.Open("samples/testSF2d.root") sf = f.Get("scalefactors_Tight_Electron") xmin, xmax = sf.GetXaxis().GetXmin(), sf.GetXaxis().GetXmax() ymin, ymax = sf.GetYaxis().GetXmin(), sf.GetYax...
11184
import argparse import matplotlib.pyplot as plt import torch from pytorch_warmup import * def get_rates(warmup_cls, beta2, max_step): rates = [] p = torch.nn.Parameter(torch.arange(10, dtype=torch.float32)) optimizer = torch.optim.Adam([{'params': p}], lr=1.0, betas=(0.9, beta2)) lr_scheduler = torch....
11199
from __future__ import absolute_import from io import BytesIO import zstd from .base import BaseCompressor, BaseDecompressor from ..protocol import CompressionMethod, CompressionMethodByte from ..reader import read_binary_uint32 from ..writer import write_binary_uint32, write_binary_uint8 class Compressor(BaseCompr...
11206
import numpy as np import sys import os sys.path.append('utils/') from config import * from utils import * sys.path.append(pycaffe_dir) import time import pdb import random import pickle as pkl import caffe from multiprocessing import Pool from threading import Thread import random import h5py import itertools import m...
11216
from fuzzconfig import FuzzConfig import nonrouting import fuzzloops import re cfgs = [ FuzzConfig(job="SYSCONFIG40", device="LIFCL-40", sv="../shared/empty_40.v", tiles=["CIB_R0C75:EFB_0", "CIB_R0C72:BANKREF0", "CIB_R0C77:EFB_1_OSC", "CIB_R0C79:EFB_2", "CIB_R0C81:I2C_EFB_3", "CIB_R0C85:PMU", "CIB_...
11240
import unittest import numpy as np from astroNN.lamost import wavelength_solution, pseudo_continuum class LamostToolsTestCase(unittest.TestCase): def test_wavelength_solution(self): wavelength_solution() wavelength_solution(dr=5) self.assertRaises(ValueError, wavelength_solution, dr=1) ...
11302
import os import json STOPWORDS_JSON_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir, "corpora/stopwords.json" ) with open(STOPWORDS_JSON_PATH, "r", encoding="utf-8") as f: STOPWORD = json.load(f)["stopwords"]
11393
import FWCore.ParameterSet.Config as cms from RecoEgamma.ElectronIdentification.Identification.mvaElectronID_tools import * # Documentation of the MVA # https://twiki.cern.ch/twiki/bin/viewauth/CMS/MultivariateElectronIdentificationRun2 # https://rembserj.web.cern.ch/rembserj/notes/Electron_MVA_ID_2017_documentation ...
11404
from typing import Union, List import pexpect from figcli.utils.utils import Utils import sys class FiggyAction: """ Actions prevent cyclic dependencies, and are designed for leveraging FiggyCli for cleanup steps when running inside of tests. """ def __init__(self, command, extra_args=""): ...
11411
import contextlib import os import tempfile import warnings from enum import Enum import mip class IISFinderAlgorithm(Enum): DELETION_FILTER = 1 ADDITIVE_ALGORITHM = 2 class SubRelaxationInfeasible(Exception): pass class NonRelaxableModel(Exception): pass class ConflictFinder: """This class...
11416
from channels import Group # websocket.connect def ws_add(message): Group("chat").add(message.reply_channel) # websocket.receive def ws_message(message): Group("chat").send({ "text": message.content['text'], }) # websocket.disconnect def ws_disconnect(message): Group("chat").discard(message.r...
11469
import re regex = re.compile('[^a-zA-Z]') def score_word(word, corpus=None): word = regex.sub('', word) # leave only alpha score = 0 consec_bonus = 2 for i, letter in enumerate(word): if letter.islower(): continue if i > 0 and word[i-1].upper(): score += conse...
11474
from pypy.module.cpyext.test.test_api import BaseApiTest class TestIterator(BaseApiTest): def test_check_iter(self, space, api): assert api.PyIter_Check(space.iter(space.wrap("a"))) assert api.PyIter_Check(space.iter(space.newlist([]))) assert not api.PyIter_Check(space.w_type) ass...
11483
import argparse import json import numpy as np import os import torch import data_ import models import utils from matplotlib import cm, pyplot as plt from tensorboardX import SummaryWriter from torch import optim from torch.utils import data from tqdm import tqdm from utils import io parser = argparse.ArgumentPars...
11502
import logging import os.path as path from typing import List, Optional, Tuple from psychopy import core, visual from bcipy.acquisition.marker_writer import NullMarkerWriter, MarkerWriter from bcipy.helpers.task import SPACE_CHAR from bcipy.helpers.stimuli import resize_image from bcipy.helpers.system_utils import ge...
11540
from __future__ import division import itertools import json import math import os import random import shutil import subprocess import sys durationA = str(5) durationB = str(4) durationC = str(1) def main(): if len(sys.argv) > 1: nbDepth = int(sys.argv[1]) if nbDepth < 2 : nbDept...
11543
import decimal from django import template register = template.Library() @register.simple_tag def can_change_status(payment_request, user): return payment_request.can_user_change_status(user) @register.simple_tag def can_delete(payment_request, user): return payment_request.can_user_delete(user) @regist...
11564
class _FuncStorage: def __init__(self): self._function_map = {} def insert_function(self, name, function): self._function_map[name] = function def get_all_functions(self): return self._function_map
11587
from typing import List, Type from apiron.service.base import ServiceBase class DiscoverableService(ServiceBase): """ A Service whose hosts are determined via a host resolver. A host resolver is any class with a :func:`resolve` method that takes a service name as its sole argument and returns a l...
11594
import pytest from apostello import models @pytest.mark.slow @pytest.mark.django_db class TestContactForm: """Test the sending of SMS.""" def test_number_permissions_staff_exception(self, recipients, users): """Test sending a message now.""" calvin = recipients["calvin"] # check good...
11636
import re import types from functools import partial LITERAL_TYPE = types.StringTypes + (int, float, long, bool, ) class Spec(object): """ This object, when overridden with an object that implements a file format specification, will perform validation on a given parsed version of the format input. ...
11639
import json import logging from http import HTTPStatus from typing import Any, Dict, List, Optional, Tuple, Type, Union import werkzeug from flask import Blueprint, Flask, Response, abort, jsonify from flask.views import MethodView from flask_cors import CORS from gevent.pywsgi import WSGIServer from geventwebsocket i...
11644
from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, AbstractUser from django.utils import timezone from django.utils.translation import gettext as _ from django import forms from django.contrib.auth.hashers import make_password from django.contrib.auth import get_user...
11671
import threading, queue, time, os, pickle # from queue import Queue import numpy as np import tensorflow as tf import sarnet_td3.common.tf_util as U from tensorflow.python.keras.backend import set_session lock = threading.Lock() class MultiTrainTD3(threading.Thread): def __init__(self, input_queue, output_queue, ...
11690
import numpy as np from stable_baselines import PPO2 from stable_baselines.common.policies import CnnPolicy from stable_baselines.a2c.utils import conv, linear, conv_to_fc from src.envs import CMDP, FrozenLakeEnvCustomMap from src.envs.frozen_lake.frozen_maps import MAPS from src.students import LagrangianStudent, i...
11716
import numpy import pytest import os from shutil import rmtree from numpy.testing import assert_allclose import scipy.stats import scipy.integrate import scipy.special from fgivenx.mass import PMF, compute_pmf def gaussian_pmf(y, mu=0, sigma=1): return scipy.special.erfc(numpy.abs(y-mu)/numpy.sqrt(2)/sigma) def...
11734
import re import time from lemoncheesecake.events import TestSessionSetupEndEvent, TestSessionTeardownEndEvent, \ TestEndEvent, SuiteSetupEndEvent, SuiteTeardownEndEvent, SuiteEndEvent, SteppedEvent from lemoncheesecake.reporting.report import ReportLocation DEFAULT_REPORT_SAVING_STRATEGY = "at_each_failed_test" ...
11750
import pyblish.api import avalon.api from openpype.api import version_up from openpype.action import get_errored_plugins_from_data class IncrementCurrentFile(pyblish.api.InstancePlugin): """Increment the current file. Saves the current scene with an increased version number. """ label = "Increment...
11773
import unittest, tempfile from pygromos.simulations.hpc_queuing.job_scheduling.schedulers import simulation_scheduler from pygromos.data.simulation_parameters_templates import template_md from pygromos.data.topology_templates import blank_topo_template from pygromos.simulations.hpc_queuing.submission_systems import D...
11785
import unittest import unittest.mock from programy.storage.entities.nodes import NodesStore class NodesStoreTest(unittest.TestCase): def test_load(self): store = NodesStore() with self.assertRaises(NotImplementedError): collector = unittest.mock.Mock() store.load(collecto...
11788
import unittest class PrefixNotIncluded(unittest.TestCase): def test_not_included(self): pass if __name__ == '__main__': unittest.main()
11836
from django.contrib.auth import get_user_model from rest_auth.registration.serializers import ( RegisterSerializer as BaseRegisterSerializer, ) from rest_auth.registration.serializers import ( SocialLoginSerializer as BaseSocialLoginSerializer, ) from rest_auth.serializers import LoginSerializer as BaseLoginSer...
11838
import os import shutil import sys import tarfile def include_package(envoy_api_protos, rst_file_path, prefix): # `envoy_api_rst_files` is a list of file paths for .proto.rst files # generated by protodoc # # we are only interested in the proto files generated for envoy protos, # not for non-envoy...
11866
from mock.mock import patch import os import pytest import ca_test_common import ceph_volume_simple_activate fake_cluster = 'ceph' fake_container_binary = 'podman' fake_container_image = 'quay.ceph.io/ceph/daemon:latest' fake_id = '42' fake_uuid = '0c4a7eca-0c2a-4c12-beff-08a80f064c52' fake_path = '/etc/ceph/osd/{}-{}...
11871
import System dataKey, _ = IN OUT = System.AppDomain.CurrentDomain.GetData("_Dyn_Wireless_%s" % dataKey)
11920
from typing import Any, Dict, Tuple import torch from torch_geometric.nn import GATConv from torch_sparse import SparseTensor, set_diag from rgnn_at_scale.aggregation import ROBUST_MEANS from rgnn_at_scale.models.gcn import GCN class RGATConv(GATConv): """Extension of Pytorch Geometric's `GCNConv` to execute a...
11957
import os from pathlib import Path import requests import shutil import sys from distutils.version import LooseVersion import time from tqdm import tqdm from docly.parser import parser as py_parser from docly.tokenizers import tokenize_code_string from docly import __version__ # from c2nl.objects import Code UPDATE_...
12008
import os import cv2 import time import json import random import inspect import argparse import numpy as np from tqdm import tqdm from dataloaders import make_data_loader from models.sync_batchnorm.replicate import patch_replication_callback from models.vs_net import * from utils.loss import loss_dict from utils.lr_s...
12009
import numpy as np import gzip import pickle import os import urllib.request class MNIST: host = 'http://yann.lecun.com/exdb/mnist/' filenames = { 'train': ('train-images-idx3-ubyte.gz', 'train-labels-idx1-ubyte.gz'), 'test': ('t10k-images-idx3-ubyte.gz', 't10k-labels-idx1-ubyte.gz'), } dataset_filen...
12038
from amitools.binfmt.BinImage import * from .ELFFile import * from .ELF import * from .ELFReader import ELFReader from .DwarfDebugLine import DwarfDebugLine class BinFmtELF: """Handle Amiga m68k binaries in ELF format (usually from AROS)""" def is_image(self, path): """check if a given file is a supp...
12049
import tvm import sys import time import numpy as np from tvm.tensor_graph.testing.models import resnet from tvm.tensor_graph.core import ForwardGraph, BackwardGraph, compute, \ GraphTensor, GraphOp, PyTIRGraph from tvm.tensor_graph.nn import CELoss, SGD from tvm.tensor_graph.core.schedul...
12058
import sys from typing import Generator from typing import List from typing import Optional import pytest from _pytest.pytester import Pytester def test_one_dir_pythonpath(pytester: Pytester, file_structure) -> None: pytester.makefile(".ini", pytest="[pytest]\npythonpath=sub\n") result = pytester.runpytest("...
12080
from cytoolz.functoolz import ( curry, ) from eth_utils import ( to_dict, to_tuple, ) @curry @to_dict def normalize_dict(value, normalizers): for key, item in value.items(): normalizer = normalizers[key] yield key, normalizer(item) @curry @to_tuple def normalize_array(value, normali...
12090
import os import shutil import unittest from base64 import b64encode from sonLib.bioio import TestStatus from sonLib.bioio import getTempFile from sonLib.bioio import getTempDirectory from sonLib.bioio import system from toil.job import Job from toil.common import Toil from cactus.shared.common import cactus_call, Chi...
12096
import json class TrainingSpecification: template = """ { "TrainingSpecification": { "TrainingImage": "IMAGE_REPLACE_ME", "SupportedHyperParameters": [ { "Description": "Grow a tree with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impu...
12108
from django.conf import settings from django.contrib.auth.decorators import user_passes_test from django.core.paginator import Paginator from django.core.urlresolvers import reverse from django.http import Http404, HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response from django.template i...
12124
from typing import TypedDict from .utils.Classes.String import String from .utils.assert_string import assert_string from .utils.merge import merge class _IsStrongPasswordOptions(TypedDict): min_length: int min_uppercase: int min_lowercase: int min_numbers: int min_symbols: int return_score: ...
12130
import pytest @pytest.fixture(scope="session") def test_data(): from pathlib import Path module_dir = Path(__file__).resolve().parent test_dir = module_dir / "test_data" return test_dir.resolve() @pytest.fixture(scope="session") def database(): return "jobflow_test" @pytest.fixture(scope="ses...
12147
from __future__ import unicode_literals from __future__ import print_function import moya from moya.compat import text_type from requests_oauthlib import OAuth1Session def get_credentials(provider, credentials): client_id = credentials.client_id or provider.get('client_id', None) client_secret = credentials...
12170
import asyncio import logging import traceback import uuid from typing import Optional, Tuple, Any, Callable from pesto.ws.core.payload_parser import PayloadParser, PestoConfig from pesto.ws.core.pesto_feature import PestoFeatures from pesto.ws.core.utils import load_class, async_exec from pesto.ws.features.algorithm_...
12172
import configparser import os import typing from sitri.providers.base import ConfigProvider class IniConfigProvider(ConfigProvider): """Config provider for Initialization file (Ini).""" provider_code = "ini" def __init__( self, ini_path: str = "./config.ini", ): """ ...
12175
from kinetics.reaction_classes.reaction_base_class import Reaction class Generic(Reaction): """ This Reaction class allows you to specify your own rate equation. Enter the parameter names in params, and the substrate names used in the reaction in species. Type the rate equation as a string in rate_equa...
12180
import json import requests from .exceptions import ( RequestsError, RequestsTimeoutError, RPCError ) _default_endpoint = 'http://localhost:9500' _default_timeout = 30 def base_request(method, params=None, endpoint=_default_endpoint, timeout=_default_timeout) -> str: """ Basic RPC request ...
12184
from __future__ import print_function import argparse, sys from .utils import is_textfile def contains_crlf(filename): with open(filename, mode='rb') as file_checked: for line in file_checked.readlines(): if line.endswith(b'\r\n'): return True return False def main(argv=Non...
12200
from KratosMultiphysics import ParallelEnvironment, IsDistributedRun if IsDistributedRun(): from KratosMultiphysics.mpi import DataCommunicatorFactory import KratosMultiphysics.KratosUnittest as UnitTest import math class TestDataCommunicatorFactory(UnitTest.TestCase): def setUp(self): self.registere...
12201
from __future__ import print_function try: import vkaudiotoken except ImportError: import path_hack from vkaudiotoken import supported_clients import sys import requests import json token = sys.argv[1] user_agent = supported_clients.KATE.user_agent sess = requests.session() sess.headers.update({'User-Agent'...
12205
import pytest from Thycotic import Client, \ secret_password_get_command, secret_username_get_command, \ secret_get_command, secret_password_update_command, secret_checkout_command, secret_checkin_command, \ secret_delete_command, folder_create_command, folder_delete_command, folder_update_command from tes...
12215
import numpy as np from radix import radixConvert c = radixConvert() a = np.load("../../data/5/layer4.npy") print(a.shape) a = a*128 a = np.around(a).astype(np.int16) print(a) a = np.load('../../data/6.npy') a = a*128 a = np.around(a).astype(np.int8) print(a.shape) for i in range(84): print(i) print(a[i]) ''...
12216
class Wrapper(object): wrapper_classes = {} @classmethod def wrap(cls, obj): return cls(obj) def __init__(self, wrapped): self.__dict__['wrapped'] = wrapped def __getattr__(self, name): return getattr(self.wrapped, name) def __setattr__(self, name, value): set...
12221
if not __name__ == "__main__": print("Started <Pycraft_StartupAnimation>") class GenerateStartupScreen: def __init__(self): pass def Start(self): try: self.Display.fill(self.BackgroundCol) self.mod_Pygame__...
12277
from django.db.models.signals import post_init from factory import DjangoModelFactory, Sequence, SubFactory from factory.django import mute_signals from affiliates.banners import models class CategoryFactory(DjangoModelFactory): FACTORY_FOR = models.Category name = Sequence(lambda n: 'test{0}'.format(n)) ...
12297
from flask import Flask, jsonify, request, render_template, redirect from flask_pymongo import PyMongo from werkzeug import secure_filename import base64 app = Flask(__name__) app.config['MONGO_DBNAME'] = 'restdb' app.config['MONGO_URI'] = 'mongodb://localhost:27017/restdb' mongo = PyMongo(app) @app.route('/') def ...
12315
from test.test_base import TestBase class TestMath(TestBase): def test_isclose(self): _test = self._assert_execute _test('ㄹ (ㄱㅇㄱ ㄱㅇㄱ ㄴㄱ ㅅㅎㄷ ㄱㅎㄷ ㄴ (ㅂ ㅅ ㄱ ㅂㅎㄹ)ㅎㄷㅎ)ㅎㄴ', 'True') _test('ㅂ ㅅ ㅂ ㅂㅎㄹ (ㄱㅇㄱ ㄱㅇㄱ ㄴㄱ ㅅㅎㄷ ㄱㅎㄷ ㄴ (ㅂ ㅅ ㄱ ㅂㅎㄹ)ㅎㄷㅎ)ㅎㄴ', 'True') _test('ㅂ ㅅ ㅈ ㅂㅎㄹ (ㄱㅇㄱ ㄱㅇㄱ ㄴㄱ ㅅㅎㄷ ㄱㅎㄷ ㄴ (ㅂ...
12335
from enum import Enum as _Enum class UsageType(_Enum): CONTROL_LINEAR = () CONTROL_ON_OFF = () CONTROL_MOMENTARY = () CONTROL_ONE_SHOT = () CONTROL_RE_TRIGGER = () DATA_SELECTOR = () DATA_STATIC_VALUE = () DATA_STATIC_FLAG = () DATA_DYNAMIC_VALUE = () DATA_DYNAMIC_FLAG = () ...
12344
import time, copy import asyncio class TempRefManager: def __init__(self): self.refs = [] self.running = False def add_ref(self, ref, lifetime, on_shutdown): expiry_time = time.time() + lifetime self.refs.append((ref, expiry_time, on_shutdown)) def purge_all(self): ...
12354
import torch import json import os from torch.utils.data import DataLoader,Dataset import torchvision.transforms as transforms from PIL import Image import numpy as np data_folder = "./dataset/images" press_times = json.load(open("./dataset/dataset.json")) image_roots = [os.path.join(data_folder,image_file) \ ...
12355
import json from grafana_backup.dashboardApi import create_snapshot def main(args, settings, file_path): grafana_url = settings.get('GRAFANA_URL') http_post_headers = settings.get('HTTP_POST_HEADERS') verify_ssl = settings.get('VERIFY_SSL') client_cert = settings.get('CLIENT_CERT') debug = setting...
12361
from numpy import array, rad2deg, pi, mgrid, argmin from matplotlib.pylab import contour import matplotlib.pyplot as plt import mplstereonet from obspy.imaging.beachball import aux_plane from focal_mech.lib.classify_mechanism import classify, translate_to_sphharm from focal_mech.io.read_hash import read_demo, read_h...
12443
import math from mathutils import Euler import bpy from .portal2_entity_classes import * from .portal_entity_handlers import PortalEntityHandler local_entity_lookup_table = PortalEntityHandler.entity_lookup_table.copy() local_entity_lookup_table.update(entity_class_handle) class Portal2EntityHandler(PortalEntityHan...
12454
import sys import webbrowser import os from comicstreamerlib.folders import AppFolders from PyQt4 import QtGui,QtCore class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, app): QtGui.QSystemTrayIcon.__init__(self, icon, None) self.app = app self.menu = QtGui.QMenu(None) ...
12532
from urllib.parse import urlparse from quart import current_app as app, request, jsonify def filter_referrers(): filters = app.config.get('REFERRERS_FILTER') if not filters: return None referrer = request.referrer if referrer: parsed = urlparse(referrer) for filter in filters:...
12535
from django.contrib import admin from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import models if settings.HAS_ADDITIONAL_USER_DATA: try: class UserProfileInline(admin.TabularInline): model = models.UserProfile extra = 0 except (...
12558
import data_algebra import data_algebra.test_util from data_algebra.data_ops import * # https://github.com/WinVector/data_algebra import data_algebra.util import data_algebra.SQLite def test_compount_where_and(): d = data_algebra.default_data_model.pd.DataFrame( { "a": ["a", "b", None, None]...
12592
from pheasant.renderers.jupyter.jupyter import Jupyter jupyter = Jupyter() jupyter.findall("{{3}}3{{5}}") jupyter.page
12598
import tensorflow as tf from ..fastspeech.model import ( TFFastSpeechEncoder, TFTacotronPostnet, TFFastSpeechLayer, ) from ..speechsplit.model import InterpLnr import numpy as np import copy class Encoder_6(tf.keras.layers.Layer): def __init__(self, config, hparams, **kwargs): super(Encoder_6,...
12605
from ..utilities import ( has_same_structure, is_equivalent_molecule, is_equivalent_building_block, are_equivalent_functional_groups, ) def test_with_functional_groups(building_block, get_functional_groups): """ Test :meth:`.BuildingBlock.with_functional_groups`. Parameters ----------...
12651
from pathlib import Path import logging from .logger import Logger from .log_formatter import LogFormatter class FileLogger(Logger): fmt = LogFormatter(use_colour=False, output_ts=False) logger = None def __init__(self, folder, format=None): if format is None: format = ("%(asctime)s|...
12654
from flask import request, session, url_for from requests_oauthlib import OAuth2Session class OAuth2Login(object): def __init__(self, app=None): if app: self.init_app(app) self.app = app def get_config(self, app, name, default_value=None): return app.config.get(self.config_prefix + name, def...
12671
from typing import List from pydantic import BaseModel from icolos.core.containers.compound import Conformer, unroll_conformers from icolos.utils.enums.step_enums import StepRMSDEnum, StepDataManipulationEnum from icolos.core.workflow_steps.step import _LE from icolos.core.workflow_steps.calculation.base import StepCa...
12678
from enum import Enum import pytest import gino from gino.dialects.aiomysql import AsyncEnum pytestmark = pytest.mark.asyncio db = gino.Gino() class MyEnum(Enum): ONE = "one" TWO = "two" class Blog(db.Model): __tablename__ = "s_blog" id = db.Column(db.BigInteger(), primary_key=True) title = ...
12685
from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import (HVAC_MODE_AUTO, PRESET_AWAY, PRESET_COMFORT, PRESET_ECO, ...
12699
from transformer import Encoder from torch import nn,optim from torch.nn.functional import cross_entropy,softmax, relu from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate import torch import utils import os import pickle class GPT(nn.Module): def __init__(self, model_d...