id
stringlengths
3
8
content
stringlengths
100
981k
1628841
import bench class Foo: num = 20000000 def test(num): i = 0 while i < Foo.num: i += 1 bench.run(test)
1628843
import os import sys from datetime import datetime import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # local def add_path(path): if path not in sys.path: sys.path.insert(0, path) add_path(os.path.abspath('..')) from pycls.al.ActiveLe...
1628857
def extractHokageTrans(item): """ # Hokage Translations """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if any([('Aim the Deepest Part of the Different World Labyrinth'.lower() in tag.lower()) for tag in item['...
1628918
from .class_weighted_bce_loss import WeightedBCEWithLogitsLoss from .cnn_rnn import EfficientNet, EfficientNet3D, ResNet, ResNet3D
1628919
import os import torch from collections import OrderedDict import re import math import argparse def network_blending(low, high, res, ratio=1, name=None): net_A = torch.load(low) net_B = torch.load(high) net_interp = OrderedDict() A_names = list(net_A['g_ema'].keys()) B_names = list...
1628925
from entity import User from .dao import BaseDao class UserDao(BaseDao): T = User def add_user(self, username: str, password: str): """ Add a user to the db :param username: :param password: """ session = self.Session() user = User(name=username.lower()...
1628933
import math from scipy import interpolate class NoneInterpolator: def __call__(self, level): return None class ProfileLevels: def __init__(self, rotorGeometry, windSpeedLevels, windDirectionLevels=None, upflowLevels=None): self.windSpeedLevels = windSpeedLevels self.windDirectionLev...
1628984
import gdsfactory as gf @gf.cell def straight_with_padding(padding: float = 3.0) -> gf.Component: """ Adding padding to a cached component should raise MutabilityError Args: default: default padding on all sides """ c = gf.c.straight() c.add_padding(default=padding) # add padding to ...
1628993
import sys import torch import numpy as np from math import pi from torch.distributions import Normal, Categorical from .geoml.curve import CubicSpline import math class DistSqKL(torch.autograd.Function): @staticmethod def forward(ctx, net, p0, p1): device = "cuda" if torch.cuda.is_available() else "c...
1629055
import numpy as np import pandas as pd df = pd.DataFrame(data=[[1, 2, 3], [4, 5, 6]], columns=['a', 'b', 'c']) print(df) # a b c # 0 1 2 3 # 1 4 5 6 a_df = df.values print(a_df) # [[1 2 3] # [4 5 6]] print(type(a_df)) # <class 'numpy.ndarray'> print(a_df.dtype) # int64 s = df['a'] print(s) # 0 1 # 1...
1629078
from pytensor import * class RNNClassifier(Graph): def __init__(self, vocab_size, input_size, hidden_size): """ RNN classification :param vocab_size: :param input_size: :param hidden_size: """ super().__init__('RNNClassifier') # embedding size ...
1629121
from __future__ import unicode_literals from django.db import migrations, connection from bluebottle.utils.utils import update_group_permissions from bluebottle.clients import properties from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant def add_group_permissions(apps, sc...
1629128
import os import subprocess can_dir = os.path.dirname(os.path.abspath(__file__)) libdbc_fn = os.path.join(can_dir, "libdbc.so") subprocess.check_call(["make"], cwd=can_dir) from selfdrive.can.parser_pyx import CANParser # pylint: disable=no-name-in-module, import-error assert CANParser
1629133
import numpy as np import pymc3 as pm import pandas as pd import theano import arviz as az from arviz_json import get_dag, arviz_to_json #Hierarchical Linear Regression Model #Reference1: https://docs.pymc.io/notebooks/multilevel_modeling.html #Reference2: https://docs.pymc.io/notebooks/GLM-hierarchical.html#The-data-...
1629171
import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.datasets import mnist import tensorflow_datasets as tfds physical_devices = tf.config.list_physical_devices("GPU") tf.config.experimental.set_memory_growth...
1629200
from kdbinsert import KdbInsert from optparse import OptionParser import sys from aselite import read_any from remote_db import RemoteDB from server_config import * class RemoteInsert(KdbInsert): #email and password are set prior to running insert if email/pw combo is present def __init__(self): self.e...
1629218
import unittest from programy.utils.language.default import DefaultLangauge ############################################################################# # class DefaultTests(unittest.TestCase): def test_split_into_sentences(self): sentences = DefaultLangauge.split_into_sentences("") self.asser...
1629232
from pydantic import BaseModel, conlist from enum import Enum from typing import Dict, Union, List, Tuple, Any import yaml # Enums for objectives and constraints class ObjectiveEnum(str, Enum): MINIMIZE = 'MINIMIZE' MAXIMIZE = 'MAXIMIZE' # Allow any case @classmethod def _missing_(cls, name):...
1629250
from . import pandas, xarray # noqa (API import) try: import dask as _dask # noqa (Test dask installed) from . import dask # noqa (API import) except ImportError: pass try: import cudf as _cudf # noqa (Test cudf installed) import cupy as _cupy # noqa (Test cupy installed) from . import ...
1629290
from EasyLogin import EasyLogin a=EasyLogin() # make a GET request, and use cache to speed up a.get("http://www.shanghairanking.com/ARWU2016.html",cache=True) # this is the table we need table=a.b.find("table",{"id":"UniversityRanking"}) count=0 # delete first <tr>, which is unneccesary a.d("tr",{}) print("Ran...
1629293
from __future__ import absolute_import from celery import Celery from django.conf import settings app = Celery('webalyzer') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
1629299
import json import os import shutil from pathlib import Path from typing import Callable from .deck_exporter import DeckExporter from ..anki.adapters.anki_deck import AnkiDeck from ..representation import deck_initializer from ..representation.deck import Deck from ..utils.constants import DECK_FILE_NAME, DECK_FILE_...
1629384
from .mlp import MLP # Hide lines below until Lab 2 from .cnn import CNN # Hide lines above until Lab 2 # Hide lines below until Lab 3 from .line_cnn_simple import LineCNNSimple from .line_cnn import LineCNN from .line_cnn_lstm import LineCNNLSTM # Hide lines above until Lab 3
1629402
import torch import numpy as np from xgboost import XGBClassifier,XGBRegressor from collections import OrderedDict from XBNet.Seq import Seq class XBNETClassifier(torch.nn.Module): ''' XBNetClassifier is a model for classification tasks that tries to combine tree-based models with neural networks to create...
1629473
from .cmap import CMapParser from .document import PDFParser, RegistryPDFParser from .objstm import ObjStmParser from .inlineimage import InlineImageParser
1629476
import unittest """ 1 / \ 2 3 / \ 4 5 """ #DFS PostOrder 4 5 2 3 1 (Left-Right-Root) def is_balancedRecurive(tree_root): def postorder(node): if node is None: return postorder(node.left) postorder(node.right) print(node.value, end=' ') postorder...
1629503
import pickle import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches CB_color_cycle = ['#377eb8', '#ff7f00', '#4daf4a', '#f781bf', '#a65628', '#984ea3', '#999999', '#e41a1c', '#dede00'] def __min_birth_max_death(persistence, band=0.0): # Look...
1629506
from collections import deque import numpy as np # A circular buffer implemented as a deque to keep track of the last few # frames in the environment that together form a state capturing temporal # and directional information. Provides an accessor to get the current # state at any given time, which is represented as ...
1629511
import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import layers import numpy as np import csv import sys import os # Import utility functions from 'utils.py' file from utils import checkFolders, show_variables, add_suffix, backup_configs # Import convolution layer definitions from 'convolution l...
1629515
import os import sys from os.path import dirname, abspath sys.path.append(dirname(dirname(abspath(__file__)))) import gym import time from agents.actor_critic_agents.A2C import A2C from agents.DQN_agents.Dueling_DDQN import Dueling_DDQN from agents.actor_critic_agents.SAC_Discrete import SAC_Discrete from agents.acto...
1629516
import numpy as np from yt.testing import assert_allclose_units, fake_random_ds, requires_file from yt.units import cm, s # type: ignore from yt.utilities.answer_testing.framework import data_dir_load from yt.visualization.volume_rendering.off_axis_projection import off_axis_projection def random_unit_vector(prng):...
1629536
import random import networkx as nx from utils.link_prediction import link_prediction class Graph: def __init__(self): self.g = nx.Graph() def set_graph(self, g): self.g = g def get_graph(self): return self.g def load_graph(self, edge_list, directed=False): self.g = ...
1629553
from typing import Type from starlette import status from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.responses import JSONResponse, Response from starlette.testclient import TestClient from starlette_context import plugins from starlette_context.header_keys impo...
1629593
from django.conf.urls.defaults import * urlpatterns = patterns('pypy.translator.js.examples.djangoping.views', (r"^ping.js$", "ping_js"), (r"^ping/$", "ping"), (r"^$", "index"), )
1629605
import os import os.path import signal import subprocess import time import psutil import pytest PYTEST_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(PYTEST_DIR) RSDS_BIN = os.path.join(ROOT, "target", "debug", "rsds-scheduler") RSDS_WORKER_BIN = os.path.join(ROOT, "target", "debug", "rsds-w...
1629613
from django.core.urlresolvers import reverse from django.test import TestCase import json from myshop.models import Product from myshop.models.manufacturer import Manufacturer class ProductSelectViewTest(TestCase): def setUp(self): manufacturer = Manufacturer.objects.create(name="testmanufacturer") ...
1629640
from stanpyro.distributions import * from stanpyro.dppllib import sample, param, observe, factor, array, zeros, ones, empty, matmul, true_divide, floor_divide, transpose, dtype_long, dtype_float, vmap def convert_inputs(inputs): return { } def model(): # Parameters cluster = sample('cluster', improp...
1629656
from alibi_detect.base import BaseDetector, outlier_prediction_dict import numpy as np from unittest import TestCase from adserver.od_model import AlibiDetectOutlierModel from adserver.constants import HEADER_RETURN_INSTANCE_SCORE from typing import Dict from adserver.base import ModelResponse class DummyODModel(Base...
1629659
from leapp.actors import Actor from leapp.libraries.common.rpms import get_installed_rpms from leapp.models import LeftoverPackages, TransactionCompleted, InstalledUnsignedRPM, RPM from leapp.tags import RPMUpgradePhaseTag, IPUWorkflowTag class CheckLeftoverPackages(Actor): """ Check if there are any RHEL 7 p...
1629674
from python_pachyderm.service import Service, enterprise_proto class EnterpriseMixin: """A mixin for enterprise-related functionality.""" def activate_enterprise(self, license_server: str, id: str, secret: str) -> None: """Activates enterprise by registering with a license server. Parameters...
1629684
import boto3 import json import random import time from datetime import datetime, timedelta from apps import App, Humana, Evidation import events import csv """ Synthentic generator code for a days worth of data """ apps = [(Humana(), range(0,60)), (Evidation(), range(55,85))] benes = [] with open('benes.csv') as be...
1629709
import pyforms from pyforms import BaseWidget from pyforms.controls import ControlPlayer class VideoWindow(BaseWidget): def __init__(self): BaseWidget.__init__(self, 'Video window') self._player = ControlPlayer('Player') self.formset = ['_player'] if __name__ == "__main__": pyforms...
1629726
from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from PooledEffect import PooledEffect from EffectController import EffectController import random class ExplosionTip(PooledEffect, EffectController): NUM_PARTS = 10 def __init__(self): PooledEffect.__init__(self) Ef...
1629748
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ i, j = 0, len(nums)-1 k = 0 while k<=j: if nums[k] == 0: nums[i], nums[k] = nums[k],nums[i] i+=1 ...
1629753
import numpy as np import pandas as pd import os import os.path fold = 4#1#4#3 resep = 143#21#17#39 gbtdepth = 2#3#2#3 neptime = 0.3 testdetp = -2 traindetp = -2 start_epoch = 0 # start from epoch 0 or last checkpoint epoch resmodelpath = './detcls-'+str(fold)+'-old/ckptgbt.t7' def iou(box0, box1): r0 = box0[3] / ...
1629755
from math import ceil from math import floor def closest_even_integer(x): """ Computes closest even integer to an input float or integer. If x is an integer, the output is x+1 if x is odd else x """ if not isinstance(x, (int, float)): raise ValueError(f"Expected {x} to be an integer or a f...
1629761
import os import unittest from __main__ import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * # # BreachWarningSelfTest # class BreachWarningSelfTest(ScriptedLoadableModule): def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) self.parent.title = "BreachWarningSelfTes...
1629781
class InPlace: def __init__(self, val): self.val = val def __ipow__(self, other): self.val **= other return self def __imul__(self, other): self.val *= other return self def __imatmul__(self, other): # I guess you could think of an int as a 1x1 matrix ...
1629793
import torch import numpy as np import cv2 import tqdm import os import json from pycocotools.mask import * from src.unet_plus import SE_Res50UNet,SE_Res101UNet import time local_time = time.strftime('%Y-%m-%d-%H-%M',time.localtime(time.time())) TEST_IMG_PATH = '/mnt/jinnan2_round2_test_b_20190424' NORMAL_LIST_P...
1629805
import time import torch import sys import os import subprocess argslist = list(sys.argv)[1:] num_gpus = torch.cuda.device_count() argslist.append('--n_gpus={}'.format(num_gpus)) workers = [] job_id = time.strftime("%Y_%m_%d-%H%M%S") argslist.append("--group_name=group_{}".format(job_id)) os.makedirs('logs', exist_ok=...
1629839
import os import networkx as nx def fix_layout(G): for n in G.nodes: node = G.nodes(data=True)[n] if node["kind"] in {"model"}: node["shape"] = '"square"' node["width"] = "1" elif node["kind"] in {"data", "prob"}: node["shape"] = '"circle"' elif ...
1629862
import unittest from boost_collections.zskiplist.zskiplist import Zskiplist class TestZskiplist(unittest.TestCase): def setUp(self): self.zsl = Zskiplist() self.zsl.zsl_insert(10, 'a') self.zsl.zsl_insert(10, 'b') def test_zsl_insert(self): zsl = self.zsl self.zsl.zs...
1629906
from collections import namedtuple import os from utils import cleanup class Test(object): Case = namedtuple('Case', ['path', 'versions', 'command', 'options', 'cleanup']) cases = dict() # unit test cases cases['vectorAdd.f128'] = Case( path='samples/vectorAdd.f128', ve...
1629911
from django.apps import AppConfig class OAuthConfig(AppConfig): """ Configuration for the OAuth app Set the OAUTH_METHOD variable in the project's settings.py to 'token' to send Django Rest Framework tokens upon login. Otherwise, successfull logins will redirect to the url set by LOGIN_REDIR...
1629971
from django.contrib import admin from src.apps.trainings.admin.network_admin import NetworkAdmin from src.apps.trainings.models import Network admin.site.register(Network, NetworkAdmin)
1629990
import cPickle as pickle import uuid import logging import time import heapq import socket NAMESPACE = uuid.UUID('7e0d7720-fa98-4270-94ff-650a2c25f3f0') def addr_to_tuple(addr): parts = addr.split('-') return parts[0], int(parts[1]) def tuple_to_addr(addr): if addr[0] == '0.0.0.0': addr = socket...
1630036
from traceback_with_variables import printing_exc, ColorSchemes def mean(vs): return sum(vs) / sum(1 for v in vs) def get_avg_ratio(size1, size2): return mean([get_ratio(h, w) for h, w in [size1, size2]]) def get_ratio(h, w): return h / w def main(): sizes_str = '300 200 300 0' with printing...
1630076
import argparse import sys import os import shutil import time import numpy as np from random import sample from sklearn import metrics import torch from torch.optim.lr_scheduler import MultiStepLR from torch.utils.tensorboard import SummaryWriter from deepKNet.data import get_train_valid_test_loader from deepKNet.mode...
1630112
import unittest from mockito import * from meme import Meme class MemeApiTest(unittest.TestCase): def test_should_get_meme_by_name(self): meme_repository_mock = Mock() when(meme_repository_mock).get('some_name').thenReturn('ok') Meme.meme_repository = meme_repository_mock ...
1630123
from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=5) knn.fit(XA,yA) yP = knn.predict(XB)
1630124
ALL_USERS_URI = "http://acs.amazonaws.com/groups/global/AllUsers" def is_s3_object_is_public(s3_obj): # Loop over all the grants. for grant in s3_obj.Acl().grants: # Find the all users grantee. if "URI" not in grant["Grantee"]: continue elif grant["Grantee"]["URI"] == ALL_U...
1630129
import pytest def test_api_methods(api_info): assert api_info.endpoints.report_test_start.version >= 1 @pytest.fixture def api_info(client): return client.api.info()
1630152
from __future__ import unicode_literals import unittest import utn11 CANONICAL_PAIRS = [ ('\u1010\u102D\u103A', '\u1010\u103A\u102D'), ('\u1010\u103A\u102D', '\u1010\u103A\u102D'), ('\u101B\u1031\u1037\u103E', '\u101B\u103E\u1031\u1037'), ('\u101B\u1031\u103E\u1037', '\u101B\u103E\u1031\u1037'), ('\u101B\...
1630153
import time import terminalio import displayio import adafruit_imageload from adafruit_display_text import label from adafruit_bitmap_font import bitmap_font from adafruit_magtag.magtag import MagTag # --| USER CONFIG |-------------------------- STATION_ID = ( "9447130" # tide location, find yours here: https://t...
1630162
import base64 from functools import wraps from django.http import HttpResponse from corehq.apps.api.cors import ACCESS_CONTROL_ALLOW, add_cors_headers_to_response from corehq.apps.api.models import ApiUser def api_user_basic_auth(permission, realm=''): def real_decorator(view): def wrapper(request, *arg...
1630200
from flask import request, jsonify, url_for from app import app from config import ROOT_URL from app.tasks import debug_celery_task from app.tasks import update_local_ftp_configurations, update_local_tftp_configurations @app.route(ROOT_URL + "debug/calculate_task", methods=['POST']) def debug_calculate_task(): "...
1630255
import uuid import pytest from supriya.patterns.events import CompositeEvent, NodeFreeEvent, NullEvent, Priority id_ = uuid.uuid4() @pytest.mark.parametrize( "event, offset, expected", [ ( CompositeEvent([NullEvent(delta=0.25), NodeFreeEvent(id_, delta=0.0)]), 0.0, ...
1630264
from bokeh.io import output_file, show from bokeh.models.widgets import Div output_file("div.html") div = Div(text="""Your <a href="https://en.wikipedia.org/wiki/HTML">HTML</a>-supported text is initialized with the <b>text</b> argument. The remaining div arguments are <b>width</b> and <b>height</b>. For this exampl...
1630279
from django.test import TestCase from django.core.cache import cache from django_redis import get_redis_connection class CacheAwareTestCase(TestCase): """ Cache-aware TestCase that clears the Redis storage and cache on startup """ def clearCache(self): """ Clears the cache ...
1630303
import flask as f from ..entities._entity import EntitySerializer from ..entities.commit import CommitSerializer from ..entities.run import Run class _Serializer(EntitySerializer): def _dump(self, commits): def _run(contender): baseline = contender.get_baseline_run() baseline_url,...
1630343
from __future__ import absolute_import from __future__ import division from __future__ import print_function from caffe2.python import core, workspace from caffe2.proto import caffe2_pb2 import time def build_net(net_name, cross_socket): net = core.Net(net_name) net.Proto().type = "async_scheduling" numa...
1630351
from monzo.monzo import Monzo from monzo.errors import BadRequestError import pytest class TestApiErrors: @pytest.fixture def unauthorized_client(self): return Monzo("gibberish") def test_whoami(self, unauthorized_client): with pytest.raises(BadRequestError): unauthorized_clie...
1630354
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import torch import torch.nn.functional as F from ops.TCP.TCP_module import TCP from torch.nn.init import orthogonal_ __all__ = ['Res2Net', 'res2net50'] class MEModule(nn.Module): """ Motion exciation module :param reduction=1...
1630358
import welleng.clearance import welleng.io import welleng.error import welleng.survey import welleng.utils import welleng.mesh import welleng.visual import welleng.version import welleng.errors.tool_errors import welleng.exchange.wbp import welleng.exchange.csv import welleng.target import welleng.connector import well...
1630376
from pybricks.hubs import PrimeHub from pybricks.parameters import Button # Initialize the hub. hub = PrimeHub() # Configure the stop button combination. Now, your program stops # if you press the center and Bluetooth buttons simultaneously. hub.system.set_stop_button((Button.CENTER, Button.BLUETOOTH)) # Now we can ...
1630384
from __future__ import absolute_import from __future__ import division from __future__ import print_function from lib.model.utils.config import cfg from lib.model.faster_rcnn.faster_rcnn import _fasterRCNN_BiDet import lib.model.faster_rcnn.binary_utils as b_utils import torch import torch.nn as nn import m...
1630389
from ethereum.block import BlockHeader from ethereum.utils import decode_hex, int256, big_endian_to_int def is_dao_challenge(config, number, amount, skip): return number == config['DAO_FORK_BLKNUM'] and amount == 1 and skip == 0 def build_dao_header(config): return BlockHeader( prevhash=decode_hex('...
1630392
from __future__ import print_function, absolute_import, division class ConditionalResetAction(object): def __init__(self, adict): self.field = adict['field'] self.update_fields = adict.get('update_fields', None) def process_version(self, version): new_version = version.copy() ...
1630429
import boto3 import sys import time # This Lambda function was designed to pull some code from a zip file location in a place of your choice. For my test, # I used the S3 script below: # import boto3 # def get_s3buckets(): # s3Buckets = boto3.client('s3') # resource = s3Buckets.list_buckets() # ...
1630492
import tarfile import sys version = sys.argv[1] tar = tarfile.open(f"dist/bioscrape-{version}.tar.gz") for member in tar.getmembers(): print(member) tar.close()
1630550
from distutils.core import setup try: from setuptools import find_packages except ImportError: print ("Please install Distutils and setuptools" " before installing this package") raise setup( name='relay.runner', version='0.1.10.dev0', description=( 'A smart thermostat. Give...
1630552
import unittest from oeqa.oetest import oeRuntimeTest, skipModule from oeqa.utils.decorators import * def setUpModule(): #check if DEFAULTTUNE is set and it's value is: x86-64-x32 defaulttune = oeRuntimeTest.tc.d.getVar("DEFAULTTUNE", True) if "x86-64-x32" not in defaulttune: skipMo...
1630561
from sqlalchemy import create_engine from sqlalchemy import Table, Column from sqlalchemy import Integer, String, Text from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # engine = create_engine('mysq...
1630620
import tensorflow as tf import numpy as np from typing import Text, List, Dict, Any, Union, Optional, Tuple, Callable from rasa.shared.nlu.constants import TEXT from rasa.utils.tensorflow.model_data import FeatureSignature from rasa.utils.tensorflow.constants import ( REGULARIZATION_CONSTANT, CONNECTION_DENSIT...
1630635
import pandas as pd from server.telemetry.pandas_import import TelemetryFrame, TelemetrySeries def _describe(s: pd.Series): ps = [0.25, 0.5, 0.75, 0.9, 0.95] d = s.describe(percentiles=ps) print(d) def print_series_summary(series: TelemetrySeries, by_pid: bool = False): if by_pid: for pid i...
1630675
import torch import torch.nn as nn import torch.nn.functional as F from gma import Aggregate from setrans import ExpandedFeatTrans import copy class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim,...
1630683
from django.contrib.auth.decorators import login_required, user_passes_test from django.http.response import HttpResponse, HttpResponseRedirect from django.views.decorators.http import require_http_methods from django.shortcuts import render from django.urls import reverse from . models import LdapAcademiaUser from ....
1630702
import itertools import numba as nb import numpy as np import pandas as pd import pytest from sid.contacts import _consolidate_reason_of_infection from sid.contacts import _numpy_replace from sid.contacts import calculate_infections_by_contacts from sid.contacts import create_group_indexer @pytest.mark.unit @pytest....
1630730
from pyxnat import Interface import os.path as op from . import skip_if_no_network _modulepath = op.dirname(op.abspath(__file__)) fp = op.join(op.dirname(op.abspath(__file__)), 'central.cfg') print(fp) central = Interface(config=fp) proj_1 = central.select.project('surfmask_smpl2') subj_1 = proj_1.subject('CENTRAL05...
1630777
import numpy as np import skimage from skimage import transform from PIL import Image from constants import scale_fact def float_im(img): return np.divide(img, 255.) # Adapted from: https://stackoverflow.com/a/39382475/9768291 def crop_center(img, crop_x, crop_y): """ To crop the center of an image ...
1630817
class FenwickTree: def __init__(self, n): self.size = n self.tree = [0] * (n + 1) def __lowbit(self, index): return index & (- index) def update(self, index, delta): while index < self.size + 1: self.tree[index] += delta index += self.__lowbit(index)...
1630858
import struct import binascii from libband.commands.facilities import Facility def lookup_packet(packet): """ Analyzes command sent to MSFT Band (from Bluetooth HCI log for example) and spits out all the parameters, for example - which command it is, how much data it expects in return, what arguments ...
1630910
import pytest import six from mock import MagicMock from requests import HTTPError from threatresponse.request.response import Response def test_that_getattr_and_setattr_are_delegated(): inner_response = MagicMock() response = Response(inner_response) response.foo = 'bar' response.spam('eggs') ...
1630919
import os from core.BaseImporter import BaseImporter from scipy.io import loadmat import yaml class Importer(BaseImporter): def __init__(self): with open('./modules/config/Matconv/equivalences.yaml', 'r') as infile: self.equivalences = yaml.load(infile) self.bottom = None def find_...
1630932
import isobar as iso from isobar.io.midi import MidiInputDevice, MidiOutputDevice import pytest import time from . import dummy_timeline VIRTUAL_DEVICE_NAME = "Virtual Device" no_midi = False try: midi_out = iso.MidiOutputDevice() except iso.DeviceNotFoundException: no_midi = True @pytest.mark.skipif(no_midi...
1630959
import numpy as np import os import pytest import tempfile import zipfile import shutil from b3get.utils import unzip_to @pytest.fixture def azipfile(): basedir = tempfile.mkdtemp() input_files = [tempfile.mktemp(dir=basedir) for _ in range(16)] for idx, fn in enumerate(input_files): with open(fn...
1631034
from arg_parser import UserArgs from collections import Counter from dataset_handler.dataset import CUB_Xian, SUN_Xian, AWA1_Xian from dataset_handler.transfer_task_split import ZSLsplit, GZSLsplit, ImbalancedDataSplit, DragonSplit, GFSLSplit from attribute_expert.model import AttributeExpert from keras.utils import to...
1631065
from __future__ import print_function import deepstate_base import logrun class CrashTest(deepstate_base.DeepStateTestCase): def run_deepstate(self, deepstate): (r, output) = logrun.logrun([deepstate, "build/examples/Crash"], "deepstate.out", 1800) self.assertEqual(r, 0) self.assertTr...
1631084
from torch import nn from torch.nn import Linear class AE_encoder(nn.Module): def __init__(self, ae_n_enc_1, ae_n_enc_2, ae_n_enc_3, n_input, n_z): super(AE_encoder, self).__init__() self.enc_1 = Linear(n_input, ae_n_enc_1) self.enc_2 = Linear(ae_n_enc_1, ae_n_enc_2) self.enc_3 = ...
1631108
def limit_vals(input_value, low_limit, high_limit): """ Apply limits to an input value. Parameters ---------- input_value : float Input value. low_limit : float Low limit. If value falls below this limit it will be set to this value. high_limit : float High limit. If...