id
stringlengths
3
8
content
stringlengths
100
981k
1671967
import logging import datetime import os import pytest from wuphf.endpoints import SmtpMessenger from wuphf.endpoints.smtp_messenger import sample_msg exp0 = "To: <EMAIL>\nFrom: <EMAIL>\nSubject: Sample WUPHF generated at {}".format(datetime.datetime.now().date()) exp1 = "The WUPHF message is: \"Hello world\"" exp2 = ...
1671986
from __future__ import absolute_import, unicode_literals from kombu import Queue from celery.utils.nodenames import worker_direct class test_worker_direct: def test_returns_if_queue(self): q = Queue('foo') assert worker_direct(q) is q
1672003
from models.model_plain import ModelPlain import numpy as np class ModelPlain4(ModelPlain): """Train with four inputs (L, k, sf, sigma) and with pixel loss for USRNet""" # ---------------------------------------- # feed L/H data # ---------------------------------------- def feed_data(self, data,...
1672055
from indy_common.constants import GET_RICH_SCHEMA_OBJECT_BY_ID, RS_ID from indy_common.config_util import getConfig from indy_node.server.request_handlers.read_req_handlers.rich_schema.abstract_rich_schema_read_req_handler import \ AbstractRichSchemaReadRequestHandler from plenum.common.constants import DOMAIN_LEDG...
1672074
import abc from copy import copy from dataclasses import dataclass, field import functools import multiprocessing from multiprocessing import synchronize import threading import time import typing as tp import stopit from pypeln import utils as pypeln_utils from . import utils from .queue import IterableQueue, Outpu...
1672079
from ....Classes.Arc1 import Arc1 from ....Classes.SurfLine import SurfLine def get_surface_active(self, alpha=0, delta=0): """Return the full winding surface Parameters ---------- self : SlotW22 A SlotW22 object alpha : float float number for rotation (Default value = 0) [rad] ...
1672083
import logging from time import sleep from vspk import v6 as vsdk from vspk.utils import set_log_level set_log_level(logging.ERROR) def did_receive_push(data): """ Receive delegate """ import pprint pp = pprint.PrettyPrinter(indent=4) pp.pprint(data) if __name__ == '__main__': import sys ...
1672120
import math import mmcv import torchvision.utils from basicsr.data import create_dataloader, create_dataset def main(mode='folder'): """Test vimeo90k dataset. Args: mode: There are two modes: 'lmdb', 'folder'. """ opt = {} opt['dist'] = False opt['phase'] = 'train' opt['name'] =...
1672160
import os from lib import action class Plan(action.TerraformBaseAction): def run(self, plan_path, state_file_path, target_resources, terraform_exec, variable_dict, variable_files): """ Plan the changes required to reach the desired state of the configuration Args: - pl...
1672167
import functools import inspect import logging import os from typing import Callable, Optional from ..shared import constants from ..shared.functions import resolve_truthy_env_var_choice from ..tracing import Tracer from .exceptions import MiddlewareInvalidArgumentError logger = logging.getLogger(__name__) def lamb...
1672193
from datetime import date, timedelta, datetime import numpy import os import requests import sys config = ["develop", "master"] def getLastWeekTimeWindow(): dt = date.today() start = dt - timedelta(days=dt.weekday()+7) end = start + timedelta(days=7) return (start.isoformat(), end.isoformat()) def ge...
1672236
import argparse import os class TermColors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' FUNCTION_NAME_PREFIX = "pybind_output_fun_" def write_module(out_file, module_name...
1672239
import os import pytest import manuel.ignore import manuel.codeblock import manuel.doctest import manuel.testing def make_manuel_suite(ns): """ Prepare Manuel test suite. Test functions are injected in the given namespace. """ # Wrap function so pytest does not expect an spurious "self" fixture...
1672294
from functools import partial from typing import Callable, Type, Union import hypothesis.extra.numpy as hnp import hypothesis.strategies as st import numpy as np import pytest from hypothesis import assume, given from numpy.testing import assert_array_equal import mygrad as mg from mygrad import Tensor from mygrad.ma...
1672322
import itertools import string import numpy as np from numpy import random import pytest import pandas.util._test_decorators as td from pandas import DataFrame, MultiIndex, Series, date_range, timedelta_range import pandas._testing as tm from pandas.tests.plotting.common import TestPlotBase, _check_plot_works impor...
1672369
from .lrs_layer import LowRankSig_FirstOrder, LowRankSig_HigherOrder import numpy as np import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) import keras from keras import backend as K from keras.layers import Dense, BatchNormalization, Reshape, Activation def init_lrs2_model(input_shape, num_levels, n...
1672383
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from login.email import send_password_reset_email from v1.models import Contact, PortalCategory, PortalTopic admin.site.register(Contact) admin.site.unregister(User) @admin.register(User) c...
1672387
import glob import xml.etree.ElementTree as ET import json from tqdm import tqdm import random MAX_DEPTH = 3 MAX_DEPTH += 1 random.seed(42) class Hier(object): def __init__(self, label): super(Hier, self).__init__() self.label = label self.children = {} def __repr__(self): return self.label + '\t' + '\t'...
1672395
import pymclevel from pymclevel.minecraft_server import MCServerChunkGenerator from pymclevel import BoundingBox import logging logging.basicConfig(level=logging.INFO) gen = MCServerChunkGenerator() half_width = 4096 gen.createLevel("HugeWorld", BoundingBox((-half_width, 0, -half_width), (half_width, 0, half_width))...
1672448
from __future__ import absolute_import import matplotlib matplotlib.rc('xtick', labelsize=6) matplotlib.rc('ytick', labelsize=6) from numpy import arange class small_multiples_plot(object): def __init__(self, fig=None, *args, **kwargs): if fig is None: raise AssertionError("A valid fig...
1672460
class Document(object,IDisposable): """ An object that represents an open Autodesk Revit project. """ def AutoJoinElements(self): """ AutoJoinElements(self: Document) Forces the elements in the Revit document to automatically join to their neighbors where appropriate. """ pass def CanEna...
1672465
import sqlite3 import unittest from tests import load_resource from tibiawikisql import Article, models, schema class TestModels(unittest.TestCase): def setUp(self): self.conn = sqlite3.connect(":memory:") self.conn.row_factory = sqlite3.Row schema.create_tables(self.conn) def test_a...
1672476
import torch class AnchorGenerator(object): def __init__(self, base_size, scales, ratios, scale_major=True, ctr=None): self.base_size = base_size self.scales = torch.Tensor(scales) self.ratios = torch.Tensor(ratios) self.scale_major = scale_major self.ctr = ctr sel...
1672491
import base64 import contextlib import os from .analysis import get_names from .emitter import Emitter, FileWriter from .consts import ( INDENT, MAX_HIGHLIGHT_RANGE, POSITION_ENCODING, PROTOCOL_VERSION, ) class DefinitionMeta: """ A bag of properties around a single source definition. This contai...
1672518
from alertaclient.utils import DateTime class ApiKey: def __init__(self, user, scopes, text='', expire_time=None, customer=None, **kwargs): self.id = kwargs.get('id', None) self.key = kwargs.get('key', None) self.user = user self.scopes = scopes self.text = text se...
1672549
f = open('input.txt') lines = [l.strip() for l in f.readlines()] inputs = [[int(j) for j in i] for i in lines] hlen = len(lines[0]) # 100 vlen = len(lines) # 100 def adj1(l,i): if i == 0: return [1] elif i == l-1: return [l-2] else: return [i-1,i+1] def adj(i,j): return [(ii,j) for ii in...
1672556
import covertool #!/usr/bin/env python # # Copyright (c) 2008, <NAME> <bbb [at] cs.unc.edu> # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the...
1672625
from unittest import TestCase from app import create_app class TestWelcome(TestCase): def setUp(self): self.app = create_app().test_client() def test_welcome(self): """ Tests the route screen message """ rv = self.app.get('/api/') # If we recalculate the hash ...
1672676
import torch import torch.nn as nn import torch.nn.functional as F import math import numpy as np from scipy import signal from scipy import linalg as la from functools import partial from model.rnncell import RNNCell from model.orthogonalcell import OrthogonalLinear from model.components import Gate, Linear_, Modrelu...
1672692
from setuptools import setup name = 'zipdump' version = '0.3' setup(name=name, version=version, url='https://github.com/nlitsme/zipdump', author='<NAME>', author_email='<EMAIL>', description='Analyze zipfile, either local, or from url', classifiers=[ "Programming Language :: Python",...
1672707
from enum import Enum import logging import binascii from blatann.nrf.nrf_dll_load import driver import blatann.nrf.nrf_driver_types as util from blatann.nrf.nrf_types.enums import * from blatann.nrf.nrf_types.gap import BLEGapAddr logger = logging.getLogger(__name__) class BLEGapSecMode(object): d...
1672717
def wavelet(Y,dt,pad=0.,dj=0.25,s0=-1,J1=-1,mother="MORLET",param=-1): """ This function is the translation of wavelet.m by Torrence and Compo import wave_bases from wave_bases.py The following is the original comment in wavelet.m #WAVELET 1D Wavelet transform with optional singificance testing % % ...
1672784
import torch import os def train_simple_conv(model, cfg, train_loader, optimizer, epoch): model.train() total_loss = 0 print (len(optimizer.param_groups)) for batch_idx, sampled_batch in enumerate(train_loader): optimizer.zero_grad() nn_outputs = model(sampled_batch['data'].to(cfg.dev...
1672828
import numpy as np from copy import deepcopy from rlcard.games.mahjong import Dealer from rlcard.games.mahjong import Player from rlcard.games.mahjong import Round from rlcard.games.mahjong import Judger class MahjongGame: def __init__(self, allow_step_back=False): '''Initialize the class MajongGame ...
1672848
import unittest import sys import re import os from androguard.misc import AnalyzeAPK from androguard.decompiler.decompiler import DecompilerJADX def which(program): """ Thankfully copied from https://stackoverflow.com/a/377028/446140 """ def is_exe(fpath): return os.path.isfile(fpath) and os...
1672861
from __future__ import print_function import argparse import os import random import chainer import numpy as np from chainer import training, Variable from chainer.training import extensions from dataset import H5pyDataset from model import DCGAN_G, DCGAN_D, init_bn, init_conv from sampler import sampler from update...
1672915
from glob import glob def get_activations(model, model_inputs, print_shape_only=False, layer_name=None): import keras.backend as K print('----- activations -----') activations = [] inp = model.input model_multi_inputs_cond = True if not isinstance(inp, list): # only one input! let's w...
1672958
from __future__ import absolute_import, division import textwrap from pprint import PrettyPrinter from _plotly_utils.utils import * # Pretty printing def _list_repr_elided(v, threshold=200, edgeitems=3, indent=0, width=80): """ Return a string representation for of a list where list is elided if it has ...
1672978
import logging from abc import abstractmethod, ABC class PostProcess(ABC): def __init__(self): self.logger = logging.getLogger("barry") @abstractmethod def __call__(self, **inputs): pass class PkPostProcess(PostProcess): """ An abstract implementation of PostProcess for power spectr...
1673014
from vibora import Vibora, Request from vibora.tests import TestSuite from vibora.responses import JsonResponse from vibora.multipart import FileUpload class FormsTestCase(TestSuite): async def test_simple_post__expects_correctly_interpreted(self): app = Vibora() @app.route('/', methods=['POST']...
1673025
import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np from scipy.ndimage.filters import gaussian_filter1d plt.rc('font', family='serif') plt.rc('font', serif='Times New Roman') plt.rcParams["mathtext.fontset"] = "stix" def smooth(y): return gaussian_filter1d(y, sigma...
1673029
from django.db import models from django.utils.translation import gettext_lazy as _ from core.models import BaseAbstractModel from core.utils import iban_validator, phonenumber_validator from orders import enums from products.models import Product class BillingAddress(BaseAbstractModel): """ Billing Address ...
1673037
from __future__ import absolute_import import numpy as np import pandas as pd import matplotlib.pyplot as plt def percentile(n): def percentile_(x): return np.percentile(x, n) percentile_.__name__ = 'percentile_%s' % n return percentile_ #determine unconditional mean, sum R in each bin. But then ...
1673043
from idm.objects import dp, MySignalEvent from idm.utils import find_mention_by_event from microvk import VkApiResponseException @dp.longpoll_event_register('+др', '+друг', '-др', '-друг') @dp.my_signal_event_register('+др', '+друг', '-др', '-друг') def change_friend_status(event: MySignalEvent) -> str: user_id =...
1673049
import pytest from pycec.network import PhysicalAddress def test_creation(): pa = PhysicalAddress("8F:65") assert 0x8F65 == pa.asint pa = PhysicalAddress("0F:60") assert 0x0F60 == pa.asint pa = PhysicalAddress("2.F.6.5") assert 0x2F65 == pa.asint assert "2.f.6.5" == pa.asstr pa = Physi...
1673101
from typing import Dict, List, Sequence, TypeVar, Union from turf.bbox import bbox from turf.explode import explode from turf.nearest_point import nearest_point from turf.helpers import ( all_geometry_types, FeatureCollection, MultiPolygon, Point, Polygon, ) from turf.helpers import feature, featu...
1673141
class Networks(object): def __init__(self, session): super(Networks, self).__init__() self._session = session def getNetwork(self, networkId: str): """ **Return a network** https://developer.cisco.com/meraki/api-v1/#!get-network - networkId (string): (required) ...
1673172
import torch from torchvision import datasets, transforms from torch.utils.data import DataLoader import os def getSVHN(batch_size, test_batch_size, img_size, **kwargs): num_workers = kwargs.setdefault('num_workers', 1) kwargs.pop('input_size', None) print("Building SVHN data loader with {} workers".form...
1673188
import typing import vel.api as api from vel.callbacks.time_tracker import TimeTracker class SimpleTrainCommand: """ Very simple training command - just run the supplied generators """ def __init__(self, epochs: int, model_config: api.ModelConfig, model_factory: api.ModelFactory, optimizer...
1673227
import unittest import hcl2 from checkov.terraform.checks.resource.azure.AppServiceIdentityProviderEnabled import check from checkov.common.models.enums import CheckResult class TestAppServiceIdentityProviderEnabled(unittest.TestCase): def test_failure(self): hcl_res = hcl2.loads(""" resour...
1673291
import tensorflow as tf from abcnn import args class Graph: def __init__(self, abcnn1=False, abcnn2=False): self.p = tf.placeholder(dtype=tf.int32, shape=(None, args.seq_length), name='p') self.h = tf.placeholder(dtype=tf.int32, shape=(None, args.seq_length), name='h') self.y = tf.placeho...
1673302
import pykd import re LOG_FILE = open(r'C:\local\tmp\ttt-common-bp-go.txt', 'w') def pykdLog2File(logObj, fileObj): for line in str(logObj).split('\n'): fileObj.write(line+'\n') def pykdLog(log): print(log) pykdLog2File(log, LOG_FILE) pykd.dbgCommand(r'bc *') pykd.dbgCommand(r'bp 08bca3d8') pykd...
1673317
import torch from torch import Tensor from typing import List, Union def _cat(tensors: List[Tensor], dim: int = 0) -> Tensor: """ Efficient version of torch.cat that avoids a copy if there is only a single element in a list """ # TODO add back the assert # assert isinstance(tensors, (list, tuple))...
1673355
from _kratos.formal import remove_async_reset as _remove_async_reset from .passes import verilog import tempfile import os import shutil import subprocess def output_btor(generator, filename, remove_async_reset=True, yosys_path="", quite=False, **kargs): # check yosys if yosys_path == "" or no...
1673366
import pickle from werkzeug.contrib.cache import (BaseCache, NullCache, SimpleCache, MemcachedCache, GAEMemcachedCache, FileSystemCache) from ._compat import range_type class SASLMemcachedCache(MemcachedCache): def __init__(self, servers=None, default_timeout=300, key_prefix=N...
1673484
import pytest import json from collections import OrderedDict import time import tox from redis import Redis # from RLTest import Env from pymongo import MongoClient from tests import find_package @pytest.mark.mongo class TestMongoJSON: def teardown_method(self): self.dbconn.drop_database(self.DBNAME) ...
1673577
from __future__ import print_function from airflow.operators import SparkSubmitOperator from airflow.models import DAG from datetime import datetime, timedelta import os DAG_ID = os.path.basename(__file__).replace(".pyc", "").replace(".py", "") APPLICATION_FILE_PATH = "~/spark-test/spark_test.R" default_args = { ...
1673608
import numpy as np import h5py import time import logging from utilities import calculate_scalar, scale import config class DataGenerator(object): def __init__(self, hdf5_path, batch_size, holdout_fold, seed=1234): """ Inputs: hdf5_path: str batch_size: int holdout_...
1673642
from __future__ import absolute_import import logging class Result: ''' 'lik0' : null likelihood 'nLL' : negative log-likelihood 'sigma2' : the model variance sigma^2 'beta' : [D*1] array of fixed effects weig...
1673646
import numpy as np from mayavi import mlab def sectional2nodal(x): return np.r_[x[0], np.convolve(x, [0.5, 0.5], "valid"), x[-1]] def nodal2sectional(x): return 0.5 * (x[:-1] + x[1:]) def set_axes_equal(ax): """Make axes of 3D plot have equal scale so that spheres appear as spheres, cubes as cubes...
1673746
import sys from requests import get from core.colors import bad def reverseLookup(inp): lookup = 'https://api.hackertarget.com/reverseiplookup/?q=%s' % inp try: result = get(lookup).text sys.stdout.write(result) except: sys.stdout.write('%s Invalid IP address' % bad)
1673773
from contextlib import contextmanager from StringIO import StringIO import logging from posix import rmdir import unittest import os from time import time from eventlet import GreenPool from hashlib import md5 from tempfile import mkstemp, mkdtemp from shutil import rmtree from copy import copy import math import tarfi...
1673790
from icolos.core.containers.generic import GenericData import unittest from icolos.core.workflow_steps.schrodinger.desmond_preprocessor import StepDesmondSetup from icolos.utils.general.files_paths import attach_root_path import os from tests.tests_paths import PATHS_EXAMPLEDATA from icolos.utils.enums.step_enums imp...
1673810
import pandas as pd import valentine.metrics as valentine_metrics import valentine.algorithms import valentine.data_sources class NotAValentineMatcher(Exception): pass def valentine_match(df1: pd.DataFrame, df2: pd.DataFrame, matcher: valentine.algorithms.BaseMatcher, ...
1673873
import datetime from typing import List from sqlalchemy import cast, String, or_ from sqlalchemy.dialects import postgresql from backend.database.objects import Game, PlayerGame, GameVisibilitySetting, GameTag from backend.utils.checks import is_admin from backend.utils.safe_flask_globals import get_current_user_id ...
1673899
import logging import gluoncv as gcv gcv.utils.check_version('0.8.0') from gluoncv.auto.estimators import CenterNetEstimator from gluoncv.auto.tasks.utils import config_to_nested from d8.object_detection import Dataset if __name__ == '__main__': # specify hyperparameters config = { 'dataset': 'sheep...
1673917
from functools import partial from .config import BOROUGHS from .error import GeosupportError from .function_info import ( FUNCTIONS, AUXILIARY_SEGMENT_LENGTH, WORK_AREA_LAYOUTS ) def list_of(length, callback, v): output = [] i = 0 # While the next entry isn't blank while v[i:i+length].strip() != ...
1673928
import json import hashlib class ConfigBase: __slots__ = [] def to_dict(self): return { x : getattr(self, x) for x in self.__slots__ } def to_json(self, **kwargs): return json.dumps(self, default = lambda x : x.to_dict(), **kwargs) def __getitem__(self, key): return getattr(...
1673985
import sys print("@function from_script:hello") print("say hello") print("This is not part of the function.", file=sys.stderr)
1673994
import h5py import numpy as np from PIL import Image from matplotlib import pyplot as plt from copy import deepcopy #group a set of img patches def group_images(data,per_row): assert data.shape[0]%per_row==0 assert (data.shape[1]==1 or data.shape[1]==3) data = np.transpose(data,(0,2,3,1)) a...
1674005
import csv import os import torch from torch.optim import * import torchvision from torchvision.transforms import * from scipy import stats from sklearn import metrics import numpy as np class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset(...
1674022
from vesper.tests.test_case import TestCase from vesper.util.byte_buffer import ByteBuffer class ByteBufferTests(TestCase): def test_initializer(self): b = ByteBuffer(10) self.assertEqual(len(b.bytes), 10) self.assertEqual(b.offset, 0) b = ByteBuffer(bytearray(1...
1674048
from typing import Callable, Optional import torch from torch import nn import constants from rl_multi_agent import MultiAgent from rl_multi_agent.experiments.experiment import ExperimentConfig from rl_multi_agent.furnmove_episode_samplers import FurnMoveEpisodeSampler from rl_multi_agent.furnmove_episodes import Fur...
1674059
from paste.response import * def test_replace_header(): h = [('content-type', 'text/plain'), ('x-blah', 'foobar')] replace_header(h, 'content-length', '10') assert h[-1] == ('content-length', '10') replace_header(h, 'Content-Type', 'text/html') assert ('content-type', 'text/html') in h ...
1674066
import numpy as np a = np.ones([2, 3], np.float32) a = [[0.1, 0.1, 0.1], [0.1, 0.2, 0.3]] gamma = np.ones([1, 3], np.float32) gamma = [[0.01, 0.02, 0.03]] mean = np.ones([1, 3], np.float32) mean = [[0.09, 0.08, 0.07]] var = np.ones([1, 3], np.float32) var = [[0.0001, 0.0003, 0.0004]] z = np.subtract(a, mean) ...
1674089
from __future__ import unicode_literals from django.apps import AppConfig class VideokitConfig(AppConfig): name = 'videokit' DEFAULT_VIDEO_CACHE_BACKEND = 'videokit.cache.VideoCacheBackend' VIDEOKIT_CACHEFILE_DIR = 'CACHE/videos' VIDEOKIT_TEMP_DIR = 'videokit-temp' VIDEOKIT_SUPPORTED_FORMATS = ['...
1674119
from pwnypack.shellcode.arm.thumb import ARMThumb __all__ = ['ARMThumbMixed'] class ARMThumbMixed(ARMThumb): """ Environment that targets a generic, unrestricted ARM architecture that switches to the Thumb instruction set. """ PREAMBLE = [ '.global _start', '.arm', '_sta...
1674122
import torch import torch.nn as nn import torch.nn.functional as F from qanet.position_encoding import PositionEncoding from qanet.layer_norm import LayerNorm1d from qanet.depthwise_separable_conv import DepthwiseSeparableConv1d from qanet.self_attention import SelfAttention class EncoderBlock(nn.Module): def __...
1674148
import sys import random from dqn import Agent import numpy as np class MockEnv: def __init__(self, env_name): self.action_space = MockActionSpace(10) self.observation_space = MockObservationSpace((1, 1, 1)) def reset(self): return self.random_observation() def step...
1674154
from mongokat import Document, Collection class ShortNamesDocument(Document): """ This Document subclass supports limited alias names, as suggested in https://github.com/pricingassistant/mongokat/issues/13 Note that they don't work in queries, field name lists, or dict(doc). Further subclassing would be necessar...
1674184
import torch class EstimateAffineParams(torch.nn.Module): """ Layer to estimate the parameters of an affine transformation matrix, which would transform the ``mean_shape`` into a given shape """ def __init__(self, mean_shape): """ Parameters ---------- mean_shap...
1674215
from odoo import models, fields, api from odoo import exceptions import logging _logger = logging.getLogger(__name__) class TodoWizard(models.TransientModel): _name = 'todo.wizard' _description = 'To-do Mass Assignment' task_ids = fields.Many2many('todo.task', string='Tasks') new_deadline = fields.Da...
1674226
from datetime import datetime, timedelta, timezone import logging import pickle from unittest.mock import Mock import pytest import trio from . import AsyncMock, asyncio_loop, fail_after from starbelly.frontier import FrontierExhaustionError from starbelly.job import ( PipelineTerminator, RunState, StatsT...
1674256
from pygsti.processors import QubitProcessorSpec from ..testutils import BaseTestCase class ProcessorSpecCase(BaseTestCase): def test_processorspec(self): # Tests init a pspec using standard gatenames, and all standards. n = 3 gate_names = ['Gh','Gp','Gxpi','Gypi','Gzpi','Gpdag','Gcphas...
1674257
import pytest pytest.importorskip("requests") pytest.importorskip("requests.exceptions") def test_load_module(): __import__("modules.contrib.getcrypto")
1674312
from telium.constant import * from telium.payment import TeliumAsk, TeliumResponse, LrcChecksumException, SequenceDoesNotMatchLengthException from telium.manager import * from telium.version import __version__, VERSION
1674326
from typing import Generator from typing import Iterator from typing import Tuple import numpy from ..Spectrum import Spectrum def parse_msp_file(filename: str) -> Generator[dict, None, None]: """Read msp file and parse info in list of spectrum dictionaries.""" # Lists/dicts that will contain all params, mas...
1674379
from django.test import TestCase from ringapp.models import Logic, PropertySide, Ring, RingProperty from ringapp.LogicUtils import LogicEngine, LogicError from model_mommy import mommy log_eng = LogicEngine() # [(0, ''), # (1, 'left and right'), # (2, 'left'), # (3, 'right'), # (4, 'left or right'), ] class Lo...
1674440
from datetime import date today = date.today() def bthdycal(b_year,b_month,b_date,name): age = today.year - int(b_year) if (today.month == int(b_month) and today.day == int(b_date)): print(f"Happy Birthday {name}") print(f"its your {age} birthday") else: print(f"the coming birthday ...
1674447
import logging import graypy from balebot.config import Config class Logger: logger = None @staticmethod def init_logger(): use_graylog = Config.use_graylog source = Config.source graylog_host = Config.graylog_host graylog_port = Config.graylog_port log_level = C...
1674452
from typing import Optional, Tuple from overrides import overrides import torch from torch.nn import Conv1d, Linear from allennlp.modules.seq2vec_encoders.seq2vec_encoder import Seq2VecEncoder from allennlp.nn import Activation @Seq2VecEncoder.register("cnn") class CnnEncoder(Seq2VecEncoder): """ A ``CnnEnc...
1674478
from .octopus_ml import plot_imp from .octopus_ml import adjusted_classes from .octopus_ml import cv from .octopus_ml import cv_adv from .octopus_ml import cv_plot from .octopus_ml import roc_curve_plot from .octopus_ml import confusion_matrix_plot from .octopus_ml import hist_target from .octopus_ml import target_pie ...
1674484
import numpy as np from tqdm import trange, tqdm import tensorflow as tf from .fedbase import BaseFedarated from flearn.utils.tf_utils import process_grad, cosine_sim, softmax, norm_grad from flearn.utils.model_utils import batch_data, gen_batch, gen_epoch, project class Server(BaseFedarated): def __init__(self,...
1674537
import dash import dash_html_components as html external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.renderer = 'var renderer = new DashRenderer();' app.layout = html.Div('Simple Dash App') if __name__ == '__main__': app....
1674540
import pandas as pd import math import parser # Worksheets with indemnification funds and temporary remuneration # For active members there are spreadsheets as of July 2019 # Adjust existing spreadsheet variations def format_value(element): if element == None: return 0.0 if type(element) == str and "...
1674556
import torch import numpy as np from functools import partial class Optimizer(): def __init__(self, parameters, optimizer, lr, eps, lr_scheduler, tf_start=1, tf_end=1, tf_step=1, **kwargs): # Setup teacher forcing scheduler self.tf_type = tf_end != 1 self.tf_rate = lambda step: max( ...
1674582
import rospy import smach import smach_ros from helpers import movement as m from helpers import transforms as t from helpers import gripper class ToolChange(smach.State): def __init__(self, tool=None, duration=1.0): smach.State.__init__(self, outcomes=['succeeded','failed']) self.tool = tool ...
1674583
from django.conf.urls import url from .views import levels urlpatterns = [ url(r'(?P<level>\d+)', levels, name="level"), ]
1674592
from datetime import datetime, timedelta import logging import onedrivesdk import onedrivesdk.error from onedrive_client.od_tasks import base from onedrive_client import od_api_helper class UpdateSubscriptionTask(base.TaskBase): def __init__(self, repo, task_pool, webhook_worker, subscription_id=None): ...
1674596
from __future__ import with_statement import random from collections import defaultdict from datetime import datetime import pytest from whoosh import analysis, fields, index, qparser, query from whoosh.compat import b, u, xrange, text_type, PY3, permutations from whoosh.filedb.filestore import RamStorage from whoosh...