id
stringlengths
3
8
content
stringlengths
100
981k
11590597
from fractions import Fraction class Solution: def isRationalEqual(self, S: str, T: str) -> bool: def convert(s): if '.' not in s: return Fraction(int(s), 1) i = s.index('.') result = Fraction(int(s[:i]), 1) s = s[i + 1:] if '(' not...
11590602
import maya.cmds as mc import glTools.utils.attribute import types class Remap(object): ''' Object wrapper for remapValue node in Maya. ''' # CONSTANTS _REMAPSUFFIX = 'remap' def __init__( self, remapName, inputValue = None, inputMin = None, inputMax = None, outputMin = None, ...
11590604
from easydict import EasyDict cartpole_dqfd_config = dict( exp_name='cartpole_dqfd', env=dict( manager=dict(shared_memory=True, force_reproducibility=True), collector_env_num=8, evaluator_env_num=5, n_evaluator_episode=5, stop_value=195, ), policy=dict( c...
11590622
import unittest from mock import patch from rfid import RFIDClient, comma_format_to_ten_digit, ten_digit_to_comma_format TEST_CONTROLLER_IP = "192.168.1.20" TEST_CONTROLLER_SERIAL = 123106461 TEST_BADGE = 3126402 open_door_resp = ( b" A\xb9\x8c\x05\x00\x00\x00\x9dtV\x07\x00\x00\x00\x00\x01\x05\x02\x00\x01" ...
11590644
import numpy as np import re import matplotlib.pyplot as plt import matplotlib as mpl plt.rcParams["font.family"] = "Times New Roman" mpl.rcParams['xtick.direction'] = 'in' mpl.rcParams['ytick.direction'] = 'in' fontsize = 9 mpl.rcParams['axes.labelsize'] = fontsize mpl.rcParams['xtick.labelsize'] = fontsize...
11590659
import numpy as np from mmseg.core.evaluation import (eval_metrics, mean_dice, mean_fscore, mean_iou) from mmseg.core.evaluation.metrics import f_score def get_confusion_matrix(pred_label, label, num_classes, ignore_index): """Intersection over Union Args: pre...
11590691
import numpy from ReID_net.Log import log def shift_im(im, offset): return shift(im, offset, "reflect", None) def shift_lab(lab, offset, void_label): return shift(lab, offset, "constant", void_label) def generate_video(im, lab, n_frames, max_speed, void_label): speed = (numpy.random.rand() * 2 - 1.0) * max_...
11590736
from torch.autograd import Variable import torch import torch.optim import copy import numpy as np from scipy.linalg import hadamard from .helpers import * dtype = torch.cuda.FloatTensor #dtype = torch.FloatTensor from data import transforms as transform def exp_lr_scheduler(optimizer, epoch, init_lr=0.001, lr_deca...
11590758
import math import torch import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self, args): super().__init__() for k, v in args.__dict__.items(): self.__setattr__(k, v) self.emb = nn.Embedding(self.dict_size, self.emb_dim) self.fi...
11590763
from math import log def next_text(modeler, dataset, subset_size=50): # Limit our search to the least seen examples # TODO it's a little hacky to use the dataframe underlying the dataset... min_seen = dataset.df["seen"].min() least_seen_examples = dataset.df[dataset.df["seen"]==min_seen] if ((len(...
11590765
import logging import time import pytest import salt.defaults.exitcodes from saltfactories.utils import random_string from tests.support.helpers import PRE_PYTEST_SKIP_REASON pytestmark = [ pytest.mark.slow_test, pytest.mark.windows_whitelisted, ] log = logging.getLogger(__name__) @pytest.fixture def maste...
11590842
import click from testplan.cli.commands import single_reader_commands from testplan.cli.commands import writer_commands from testplan.cli.utils.actions import ProcessResultAction, ParseSingleAction @click.group(name="convert", chain=True) def convert(): """ Convert a single input file to testplan format. ...
11590855
import pytest import numpy as np from scipy import sparse from sklearn.datasets import load_iris keras = pytest.importorskip("keras") from keras.models import Sequential # noqa: E402 from keras.layers import Dense # noqa: E402 from keras.utils import to_categorical # noqa: E402 from imblearn.datasets import make...
11590875
import torch.nn as nn import torch class LR(nn.Module): def __init__(self, config): super().__init__() self.model = nn.Linear(in_features=config.hidden_size, out_features=1) def forward(self, *inputs, **kwargs): feature = kwargs.pop("features") if feature.dim() == 3: feature = torch.mean(fe...
11590882
import datetime import itertools import logging import logging.config import urllib.parse from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from django.conf import settings from django.db.models import Q import pytz from opencivicdata.legislative.models import...
11590893
from conans import ConanFile, CMake, tools import os required_conan_version = ">=1.33.0" class SrtConan(ConanFile): name = "srt" homepage = "https://github.com/Haivision/srt" description = "Secure Reliable Transport (SRT) is an open source transport technology that optimizes streaming performance across ...
11590919
from directory_constants.choices import COUNTRY_CHOICES from domestic.forms import SectorPotentialForm, UKEFContactForm def test_sector_potential_form(): sector_list = [ {'name': 'Sector One'}, {'name': 'Sector Two'}, {'name': 'Sector Three'}, {'name': 'Sector Four'}, ] f...
11590963
from collections import OrderedDict from SeleniumLibrary.base import LibraryComponent, keyword class PluginWithAllArgs(LibraryComponent): def __init__(self, ctx, arg, *varargs, **kwargs): LibraryComponent.__init__(self, ctx) self.arg = arg self.varargs = varargs self.kwargs = kwar...
11590985
import sys import time from i2cdriver import I2CDriver, EDS if __name__ == '__main__': i2 = I2CDriver(sys.argv[1]) d = EDS.LED(i2) TEAL = 0x008080 ORANGE = 0xffa500 while 1: time.sleep(1) d.hex(TEAL, 3) time.sleep(1) d.hex(ORANGE, 3)
11591006
import torch from deepsvg.difflib.tensor import SVGTensor from torch.distributions.categorical import Categorical import torch.nn.functional as F def _get_key_padding_mask(commands, seq_dim=0): """ Args: commands: Shape [S, ...] """ with torch.no_grad(): key_padding_mask = (commands ==...
11591061
class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: anchor, length = 0, 0 for i in range(len(nums)): if i and nums[i - 1] >= nums[i]: anchor = i length = max(length, i - anchor + 1) return length
11591091
from typing import Union, Dict from cif.atoms import atoms def formula_str_to_dict(sumform: Union[str, bytes]) -> Dict[str, str]: """ converts an atom name like C12 to the element symbol C Use this code to find the atoms while going through the character astream of a sumformula e.g. C12H6O3Mn7 Fi...
11591162
DEFAULT_CONFIG_PATH = "~/.sotabench/sotabenchapi.ini" SOTABENCH_API_URL = "https://sotabench.com/api/v0"
11591164
import csv import pprint import bw2io import wurst from bw2data.database import DatabaseChooser from wurst import searching as ws from . import DATA_DIR FILEPATH_FIX_NAMES = DATA_DIR / "fix_names.csv" FILEPATH_BIOSPHERE_FLOWS = DATA_DIR / "dict_biosphere.txt" class DatabaseCleaner: """ Class that cleans th...
11591192
from django.db import models from django.utils import timezone import subprocess from apps.news.models import News class Hunt(models.Model): id = models.AutoField(primary_key=True) datetime = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=255) keyword = models.CharField(...
11591202
from . import enc from base64 import urlsafe_b64encode as b64enc from urllib.parse import quote def _header(video_id, channel_id) -> str: S1_3 = enc.rs(1, video_id) S1_5 = enc.rs(1, channel_id) + enc.rs(2, video_id) S1 = enc.rs(3, S1_3) + enc.rs(5, S1_5) S3 = enc.rs(48687757, enc.rs(1, video_id)) ...
11591213
import unittest from unittest.mock import Mock from kaggle_gcp import KaggleKernelCredentials, init_ucaip from test.support import EnvironmentVarGuard def _make_credentials(): import google.auth.credentials return Mock(spec=google.auth.credentials.Credentials) class TestUcaip(unittest.TestCase): def te...
11591229
import logging import sys from typing import List from scholarly import scholarly from ..utils import dump_papers logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logger = logging.getLogger(__name__) scholar_field_mapper = { "venue": "journal", "author": "authors", "cites": "citations", } pr...
11591250
from django.db import models # Create your models here. class Destination(models.Model): name = models.CharField( unique=True, max_length=50, null=False, blank=False, ) description = models.TextField( max_length=2000, null=False, blank=False ) ...
11591271
from e2e import DockerTest class TestHelp(DockerTest): def test_guet_command_by_itself_displays_help_message(self): self.add_command('guet') self.execute() self.assert_text_in_logs(0, 'usage: guet <command>') def test_guet_command_shows_help_message_when_dash_h_is_given(self): ...
11591273
import pathlib import numpy as np import pytest import meshio from . import helpers @pytest.mark.parametrize( "mesh", [ helpers.empty_mesh, helpers.tri_mesh, helpers.triangle6_mesh, helpers.quad_mesh, helpers.quad8_mesh, helpers.tri_quad_mesh, helpers...
11591275
import random import os import os.path NAMES = ['stefan','melanie','nick','darrel','kent','simon'] AGES = list(range(1,10)) + [None] def get_schema_path(fname): dname = os.path.dirname(os.path.realpath(__file__)) return os.path.join(dname, fname) def load_schema_file(fname): fname = get_schema_path(fname...
11591276
import numpy as np from scipy import misc import matplotlib.pyplot as plt import cv2 def psnr(im1, im2): """ im1 and im2 value must be between 0 and 255""" im1 = np.float64(im1) im2 = np.float64(im2) rmse = np.sqrt(np.mean(np.square(im1[:] - im2[:]))) psnr = 20 * np.log10(255 / rmse) return psn...
11591313
import ctypes import windows.generated_def as gdef from ..apiproxy import ApiProxy, NeededParameter from ..error import fail_on_zero, succeed_on_zero class Shell32Proxy(ApiProxy): APIDLL = "shell32" default_error_check = staticmethod(fail_on_zero) @Shell32Proxy() def ShellExecuteA(hwnd, lpOperation, lpFile, ...
11591371
import imp import subprocess import os from string import Template PLUGINS = [ 'interpolate', ] BASE_FOLDER = 'torch2trt_dynamic/converters' NINJA_TEMPLATE = Template(( "rule link\n" " command = g++ -shared -o $$out $$in -L$torch_dir/lib -L$cuda_dir/lib64 -L$trt_lib_dir -lc10 -lc10_cuda -ltorch -lcudart...
11591387
import os import time import datetime import ref import torch import torch.utils.data from opts import opts from model.Pose3D import Pose3D from datahelpers.dataloaders.fusedDataLoader import FusionDataset from datahelpers.dataloaders.h36mLoader import h36m from datahelpers.dataloaders.mpiiLoader import mpii from dat...
11591413
import argparse import cv2 import numpy as np def build_arg_parser(): parser = argparse.ArgumentParser(description='Reconstruct the 3D map from \ the two input stereo images. Output will be saved in \'output.ply\'') parser.add_argument("--image-left", dest="image_left", required=True, ...
11591420
from typing import NamedTuple from typing_extensions import Protocol from sciencebeam_parser.config.config import AppConfig from sciencebeam_parser.external.wapiti.wrapper import LazyWapitiBinaryWrapper # using protocol to avoid delft import where we just need the typing hint class DownloadManagerProtocol(Protocol)...
11591440
from test_helper import unittest, paypal, client_id, client_secret, assert_regex_matches from paypalrestsdk.openid_connect import Tokeninfo, Userinfo, authorize_url, logout_url, endpoint class TestTokeninfo(unittest.TestCase): def test_create(self): self.assertRaises( paypal.ResourceNotFound,...
11591445
import collections import datetime import itertools import json import math from operator import itemgetter import random import re import sys from typing import List, Optional, Union import pytz from pytz import UnknownTimeZoneError from .sql.casts import get_time_formatter from .sql.internal_utils.joins import ( ...
11591469
getObject = { "certificate": "-----BEGIN CERTIFICATE----- \nMIIEJTCCAw2gAwIBAgIDCbQ0MA0GCSqGSIb3DQEBCwUAMEcxCzAJBgNVBAYTAlVT" " -----END CERTIFICATE-----", "certificateSigningRequest": "-----BEGIN CERTIFICATE REQUEST-----\n" "MIIC1jCCAb4CAQAwgZAxCzAJBgNVBAYTAl...
11591494
from ansiblemdgen.Config import SingleConfig from ansiblemdgen.Utils import SingleLog import os from os import walk import yaml class WriterBase: config = None def __init__(self): self.config = SingleConfig() self.log = SingleLog() self.log.info("Base directory: "+self.config.get_bas...
11591538
import os, re from time import sleep from WhatsAppManifest.adb.base import WhatsAppManifest from WhatsAppManifest.consts import _PACKAGE_NAME_ from WhatsAppManifest.adb.device import Device from WhatsAppManifest.manifest.android import AndroidKeyEvents from WhatsAppManifest.automator.whatsapp.database import WhatsAppDa...
11591546
from .base_request import BaseRequest from .console import embed, shell_entry from .misc import decode_text_from_webwx, enhance_connection, enhance_webwx_request, ensure_list, get_receiver, \ get_text_without_at_bot, get_user_name, handle_response, match_attributes, match_name, match_text, repr_message, \ smart...
11591564
from __future__ import absolute_import from celery import Celery, platforms from library.config.database import redis_config platforms.C_FORCE_ROOT = True celery_redis_conf = redis_config['session'] BROKER_URL = 'redis://:' + celery_redis_conf['pwd'] + '@' + celery_redis_conf['host'] + ':' + str(celery_redis_conf['p...
11591595
BASE_INDEX = 1 """Index of "base" points (96% of the training set picked at random)""" VALID_INDEX = 2 """Index of "valid" points (2% of the training set picked at random)""" HIDDEN_INDEX = 3 """Index of "hidden" points (2% of the training set picked at random)""" PROBE_INDEX = 4 """Index of "probe" points (1/3 of t...
11591599
import mmap import fcntl import io class MmapIo: def __init__(self, filepath): self.mmap_filepath = filepath self.mm = None def open(self): self.f = open(self.mmap_filepath, "r+b") self.mm = mmap.mmap(fileno=self.f.fileno(), length=0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ ...
11591651
import django from schema_graph.schema import get_schema DJANGO_LT_19 = django.VERSION < (1, 9, 0) def test_abstract_models(): expected = { "django.contrib.auth": ("AbstractBaseUser", "AbstractUser", "PermissionsMixin"), "django.contrib.sessions": ("AbstractBaseSession",), "tests.inheri...
11591656
from typing import Any, Dict, List from casymda.blocks import Sink, Source from main.geo.geo_info import GeoInfo from main.model.blocks.drive_tour import DriveTour from main.model.blocks.truck import Truck from main.model.geo_info_setup import get_geo_info geo_info: GeoInfo = get_geo_info() class Model: def __i...
11591691
import os from warnings import warn from xml.dom import minidom import parmed as pmd import mbuild as mb from mbuild.compound import Compound from mbuild.utils.io import has_foyer def specific_ff_to_residue( structure, forcefield_selection=None, residues=None, reorder_res_in_pdb_psf=False, boxes...
11591692
def _go_command(ctx): output = ctx.attr.output if ctx.attr.os == "windows": output = output + ".exe" output_file = ctx.actions.declare_file(ctx.attr.os + "/" + ctx.attr.arch + "/" + output) pkg = ctx.attr.pkg ld_flags = "-s -w" if ctx.attr.ld: ld_flags = ld_flags + " " + ctx.attr.ld options = [...
11591721
import unittest from flask import Flask, Blueprint, request try: from mock import Mock except: # python3 from unittest.mock import Mock import flask import flask_restful import flask_restful.fields #noinspection PyUnresolvedReferences from nose.tools import assert_true, assert_false # you need it for tests...
11591742
from pycap import PropertyTree, Observer, Observable, Experiment import unittest class ObserverObservableTestCase(unittest.TestCase): def test_builders(self): for AbstractClass in [Observer, Observable]: # AbstractClass takes a PropertyTree as argument. self.assertRaises(TypeError...
11591765
import os import time from eval_engines.bag.bagEvalEngine import BagEvalEngine from bag.io import read_yaml from bag_deep_ckt.util import * import IPython class TIACTLEEvaluationEngine(BagEvalEngine): def __init__(self, design_specs_fname): BagEvalEngine.__init__(self, design_specs_fname) def impose...
11591800
import superimport import numpy as np import matplotlib.pyplot as plt from scipy.stats import multivariate_normal from jax import vmap class BinaryFA: def __init__(self, input_dim, latent, max_iter, conv_tol=1e-4, compute_ll=True): self.W = 0.1 * np.random.randn(latent, input_dim) # 2x16 self.b = 0.01 * n...
11591866
import os.path as op from os import getenv from uuid import uuid4 from unittest import SkipTest from flask_admin.contrib.fileadmin import azure from .test_fileadmin import Base class AzureFileAdminTests(Base.FileAdminTests): _test_storage = getenv('AZURE_STORAGE_CONNECTION_STRING') def setUp(self): ...
11591896
import numpy as np import mxnet as mx from mxnet.gluon import nn, HybridBlock from mxnet.util import use_np from autogluon_contrib_nlp.layers import get_activation, get_norm_layer from autogluon_contrib_nlp.models.transformer import TransformerEncoder from .. import constants as _C from ..config import CfgNode @use_n...
11591901
from abc import ABC, abstractmethod from utils import * from transformations import * class Augmentor(ABC): def __init__(self, params): self.output_type_list = params.get('output_type_list', ['single', 'multi-object']) self.overlap_ratio = params.get('overlap_ratio', 0) self.persp_trans...
11591905
from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, Http404 from django.utils.crypto import get_random_string from django.contrib.auth.decorators import login_required from django.dispatch import Signal from django.dispatch import receiver from core.signals import sig...
11591912
import redis POOL = redis.ConnectionPool(host='127.0.0.1',decode_responses=True,max_connections=20)
11591936
from __future__ import print_function, unicode_literals import io import re from twisted.internet import reactor from twisted.internet.defer import gatherResults, inlineCallbacks, returnValue from twisted.internet.error import ConnectionRefusedError from twisted.trial import unittest import mock from .. import _ren...
11591966
def sum(array, initial, to): total = 0 for i in range(initial, to + 1): total += array[i] return total def partition(array, N, K): if K == 1: return sum(array, 0, N - 1) if N == 1: return array[0] best = 100000000 for i in range(1, N + 1): best...
11591994
import argparse import sys from sourced.ml.cmd.args import add_repo2_args from sourced.ml.cmd import ArgumentDefaultsHelpFormatterNoNone from cmd.code2vec_extract_features import code2vec_extract_features def get_parser() -> argparse.ArgumentParser: """ Creates the cmdline argument parser. """ parser...
11592000
import numpy as np import pandas as pd from ..exceptions import ArgumentsError from ..utils import num_of_samples class Split: """Class for splitting the dataset into train and test sets""" def __init__(self): self.df = None self.train_df = None self.target_label = None self....
11592010
from bs4 import BeautifulSoup import requests import csv URL = "https://www.indiatoday.in/" def writeToCSV(topTenNews, category): with open("topTen" + category + "News.csv", "w") as file: writer = csv.writer(file) writer.writerow(["Date", "Link", "Headline"]) for news in topTenNews: ...
11592040
import unittest import math import pandas as pd from hummingbot.core.clock import ( Clock, ClockMode ) from hummingbot.core.py_time_iterator import PyTimeIterator NaN = float("nan") class MockPyTimeIterator(PyTimeIterator): def __init__(self): super().__init__() self._mock_variable = No...
11592079
from __future__ import print_function import argparse import logging import odil def add_subparser(subparsers): parser = subparsers.add_parser( "print", help="Print the contents of data sets", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("inputs", nargs="+", meta...
11592112
from abc import ABC from abc import abstractmethod from typing import Any from typing import Optional class Step(ABC): def __init__(self): pass # Concrete implementations should raise a StepException upon encountering a fatal error to signal that the # pipeline should exit early. @abstractmet...
11592123
import os import numpy as np from deephyper.benchmark.benchmark_functions_wrappers import linear_ np.random.seed(2018) def load_data(dim=10): """ Generate data for linear function -sum(x_i). Return: Tuple of Numpy arrays: ``(train_X, train_y), (valid_X, valid_y)``. """ # size = 100000 ...
11592149
import mock from chroma_core.models import ManagedHost from chroma_core.models import Volume from chroma_core.models import VolumeNode from chroma_core.models import ForceRemoveHostJob from chroma_core.models import StopLNetJob from chroma_core.models import HostOfflineAlert from chroma_core.models import Command from...
11592154
from flask import ( Blueprint, Response, abort, jsonify, render_template, request, send_from_directory, ) import whiskyton.helpers.sitemap as whiskyton_sitemap from whiskyton import app, models from whiskyton.helpers.charts import Chart files = Blueprint("files", __name__) @files.route("...
11592164
import tensorflow as tf import numpy as np from typing import Tuple from modules.utils import PostNet, CBHGLayer, PreNet, PositionalEncoding from modules.attention import BahdanauAttention, CrossAttentionBLK class BasePosterior(tf.keras.layers.Layer): """Encode the target sequence into latent distribu...
11592215
import unittest import logging import os import re skip_unless = os.getenv("SKIP_TEST_UNLESS", "") skip_unless_expression = re.compile("%s" % skip_unless) def skip_if_required(): def decorator(cls): if skip_unless: m = skip_unless_expression.match(cls.__name__) if not m: ...
11592234
import sys from IPython.Debugger import Pdb from IPython.Shell import IPShell from IPython import ipapi shell = IPShell(argv=['']) def set_trace(): ip = ipapi.get() def_colors = ip.options.colors Pdb(def_colors).set_trace(sys._getframe().f_back)
11592268
import numpy as np def resample_stats(stats, *data, n=1000): """ Resample data set `data` `n` times and evaluate statistic `stats`. """ N = data[0].shape[0] for i in range(1, len(data)): if data[i].shape[0] != N: raise ValueError( 'Expected batch_size ({}) to m...
11592272
from ..util import BaseCase import pygsti from pygsti.protocols import vb as _vb from pygsti.processors import CliffordCompilationRules as CCR from pygsti.processors import QubitProcessorSpec as QPS class TestPeriodicMirrorCircuitsDesign(BaseCase): def test_design_construction(self): n = 4 qs = ...
11592291
import pytest from plenum.common.constants import LEDGER_STATUS from plenum.common.messages.node_messages import Checkpoint, LedgerStatus from plenum.common.startable import Mode from plenum.server.node import Node from plenum.server.replica import Replica from plenum.server.replica_validator_enums import STASH_CATCH_...
11592295
from django.test import TestCase, override_settings from tests.models import TestModel class TestSlugification(TestCase): def test_unicode_slugs(self): """ Confirm the preservation of unicode in slugification by default """ sample_obj = TestModel.objects.create() # a unico...
11592317
import warnings import numpy as np from numba import jit """ This code is from scipy project with following license: SciPy license Copyright © 2001, 2002 Enthought, Inc. All rights reserved. Copyright © 2003-2019 SciPy Developers. All rights reserved. Redistribution and use in source and binary forms, with or wi...
11592343
from __future__ import division import csv import tensorflow as tf #import params import numpy as np def weight_variable(name, shape): return tf.get_variable(name, shape=shape, initializer=tf.contrib.layers.xavier_initializer()) # initial = tf.truncated_normal(shape, stddev=0.1) # return tf.Variab...
11592365
from django.db import models from django.urls import reverse from target import target from django.utils import timezone DEFAULT_RULES = """Make words of at least four letters using the grid letters at most once. The centre letter must be in every word. There's one nine-letter word. There are no plurals or proper noun...
11592386
import sys import json from flask import ( Flask, Response, request, send_from_directory, ) from azure.messaging.webpubsubservice import ( WebPubSubServiceClient ) hub_name = 'chat' app = Flask(__name__) service = WebPubSubServiceClient.from_connection_string(sys.argv[1], hub=hub_name) @app...
11592430
import logging import os import uuid import pandas as pd import pytest # from output import build_tag from pybatfish.client.session import Session from pybfe.client.session import GRPCSession as Session NETWORK_FIXTURES = ['arista'] BF_INIT_SNAPSHOT = "yes" BF_NETWORK = 'arista' BF_SNAPSHOT = 'snapshot0' BF_SNAPSHO...
11592434
import numpy as np import SimpleITK as sitk from scipy.interpolate import griddata from platipy.imaging.label.utils import vectorised_transform_index_to_physical_point def evaluate_distance_on_surface( reference_volume, test_volume, abs_distance=True, reference_as_distance_map=False ): """ Evaluates a d...
11592444
import dectate import morepath from morepath.converter import Converter from morepath.error import ( DirectiveReportError, ConfigError, LinkError, TrajectError, ) from webtest import TestApp as Client import pytest def test_simple_path_one_step(): class app(morepath.App): pass class ...
11592446
import logging import requests from bs4 import BeautifulSoup from http_request_randomizer.requests.parsers.UrlParser import UrlParser from http_request_randomizer.requests.proxy.ProxyObject import ProxyObject, AnonymityLevel logger = logging.getLogger(__name__) __author__ = 'pgaref' class RebroWeeblyParser(UrlPars...
11592458
online_store = { "keychain": 0.75, "tshirt": 8.50, "bottle": 10.00 } keychain = online_store['keychain'] tshirt = online_store['tshirt'] bottle = online_store['bottle'] choicekey = input("How many keychains will you be purchasing? If not purchasing keychains, enter 0. ") choicetshirt = input("How many ...
11592468
import numpy as np from scipy.spatial.distance import cdist def create_bins_and_dist_matrices(ns, constraints=True): """Get bins and distance matrix for pairwise distributions comparison using Earth Mover's Distance (EMD). ns requires: bw_bonds bw_angles bw_constraints bw_...
11592482
import numpy as np from bico.geometry.squared_euclidean import squared_euclidean_distance from bico.nearest_neighbor.base import NearestNeighbor, NearestNeighborResult from typing import List class SimpleProjection(NearestNeighbor): """ Nearest neighbor implementation by projecting points into buckets using rando...
11592517
from __future__ import unicode_literals from .compat import implements_to_string from . import diagnose from .interface import AttributeExposer __all__ = ["MoyaException", "FatalMoyaException", "throw"] @implements_to_string class MoyaException(Exception, AttributeExposer): fatal = False __moya_exposed_att...
11592522
VERSION = (0, 10, 1, 'final', 0) __all__ = [ 'WebSocketApplication', 'Resource', 'WebSocketServer', 'WebSocketError', 'get_version' ] def get_version(*args, **kwargs): from .utils import get_version return get_version(*args, **kwargs) try: from .resource import WebSocketApplication, ...
11592524
from __future__ import annotations from decimal import Decimal from typing import Type import pytest from typic.constraints import ( IntContraints, FloatContraints, DecimalContraints, ConstraintValueError, ConstraintSyntaxError, ) from typic.constraints.common import BaseConstraints @pytest.mark...
11592569
t = int(input()) while t: n = int(input()) if n < 1500: HRA = n*0.10 DA = n*0.9 else: HRA = 500 DA = n*0.98 print(n + HRA + DA) t = t-1
11592580
from django.db import models from django.contrib.auth.models import User # Create your models here. PROGRESSION_STATUS = ( (0, 'Completed'), (1, 'Almost there'), (2, 'Under progression'), (3, 'Initialized'), ) class Activity(models.Model): user = models.ForeignKey(User) activity_category = models.CharField(max...
11592583
import numpy as np import matplotlib.pyplot as plt from aeropy.geometry.airfoil import CST from aeropy.morphing.camber_2D import * # testing = 'structurally_consistent' testing = 'structurally_consistent' inverted = False morphing_direction = 'forwards' if testing == 'tracing': N1 = 1. N2 = 1. tip_displacem...
11592602
from umongo.fields import ListField, EmbeddedField from umongo.document import DocumentImplementation from umongo.embedded_document import EmbeddedDocumentImplementation def map_entry(entry, fields): """ Retrieve the entry from the given fields and replace it if it should have a different name within the ...
11592619
import torch.nn as nn import torch.utils.model_zoo as model_zoo import math import torch def conv3x1(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=(3, 1), stride=(stride, 1), padding=(1, 0), bias=False) def co...
11592724
import torch.nn as nn class EMAHelper(object): def __init__(self, mu=0.999): self.mu = mu self.shadow = {} def register(self, module): if isinstance(module, nn.DataParallel): module = module.module for name, param in module.named_parameters(): if param....
11592734
import numpy as np import tensorflow as tf from keras import backend as K from keras import initializers from keras import layers from keras.utils.generic_utils import get_custom_objects # Obtained from https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/efficientnet_model.py class EfficientNet...
11592794
from ipykernel.kernelbase import Kernel from tableauhyperapi import HyperProcess, Connection, Telemetry, HyperException from tabulate import tabulate import time import json from datetime import datetime import shlex class HyperKernel(Kernel): implementation = 'Hyper' implementation_version = '0.0' langua...