id
stringlengths
3
8
content
stringlengths
100
981k
9958792
from metalibm_core.core.simple_scalar_function import ScalarBinaryFunction from metalibm_core.core.ml_formats import ML_Binary32, ML_Int32 from metalibm_core.core.precisions import ML_Faithful from metalibm_core.core.ml_operations import ( Statement, Return, ExponentExtraction, ExponentInsertion, MantissaExtrac...
9958906
import vtk def initialize(self, VTKWebApp, args): if not VTKWebApp.view: # VTK specific code renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowIn...
9958911
from google.cloud.gapic.trace.v1 import enums from google.cloud.gapic.trace.v1 import trace_service_api from google.devtools.cloudtrace.v1 import trace_pb2 from google.protobuf import timestamp_pb2 import calendar import time import uuid # point this at your project ID PROJECT_ID = 'gapic-test' api = trace_service...
9958967
from deepy3d import Deepy3d from _version import __version__ __all__ = ['CNN_Model', 'ConfigReader', 'PatientIO', 'Scans', 'util']
9958978
import random from openpyxl import Workbook from openpyxl.styles import PatternFill from openpyxl.formatting.rule import CellIsRule wb = Workbook() ws = wb.active values = random.sample(range(100), k=10) for i, value in enumerate(values, 1): column_a = ws.cell(i, 1) column_a.value = value row_le...
9958981
algorithm='dqn' env_class='UnityMLVector' model_class='TwoLayer2x' environment = { 'name': 'compiled_unity_environments/Banana.app' } model = { 'state_size': 37, 'action_size': 4, 'fc_units': (32, 32) } agent = { 'action_size': 4, 'use_double_dqn': False, } train = { 'n_episodes': 1000, ...
9959072
from keras import backend as K import os import sys def set_keras_backend(backend): if K.backend() != backend: os.environ['KERAS_BACKEND'] = backend reload(K) assert K.backend() == backend
9959073
import argparse import numpy import sys import csv import os from collections import defaultdict parser = argparse.ArgumentParser() parser.add_argument('--input-tsv', type=str, required=True) args, files = parser.parse_known_args() def main(): print("\t".join(["contig", "position", "ref", "alt", "primer_name", "...
9959106
from datetime import datetime import typing from fastapi.responses import JSONResponse as BaseResponse class JSONResponse(BaseResponse): def render(self, content: typing.Any) -> bytes: if isinstance(content, datetime): return content.replace(microsecond=0).isoformat() return super()....
9959132
import json import pytest import brahe.data_models as bdm from .paths import TEST_DATA @pytest.fixture def request_sf_point(): filepath = TEST_DATA / 'request_sf_point.json' request_json = json.load(open(filepath, 'r')) yield bdm.Request(**request_json) @pytest.fixture def request_sf_polygon(): filep...
9959146
import fortran_dissipation as fortran def add_viscosity(grid, state, dstate, viscosity): for comp in "ijk": for direc in "ijk": coef = viscosity*grid.ids2[direc] cova = state.u[comp].view(direc) dudt = dstate.u[comp].view(direc) if direc == comp: ...
9959149
import sys import numpy from matplotlib import pyplot from scipy import stats import pytest from paramnormal import activity from paramnormal import dist from paramnormal.utils import seed BASELINE_DIR = 'baseline_images/test_activity' TOLERANCE = 15 def assert_dists_are_equivalent(dist1, dist2): numpy.rando...
9959190
import matplotlib.pyplot as plt import numpy as np import pandas as pd def plot(title, filename, xlabel=None, ylabel=None, n_obj=None, algo=None, noise=None, new_fig=False ): with open(filename, 'r') as f: y = f.readlines() y = [...
9959201
from ._model import CellAssign from ._module import CellAssignModule __all__ = ["CellAssign", "CellAssignModule"]
9959209
class Affine(object): DIE = 128 KEY = (7, 3, 55) def __init__(self): pass def encryptChar(self, char): K1, K2, kI = self.KEY return chr((K1 * ord(char) + K2) % self.DIE) def encrypt(self, string): return "".join(map(self.encryptChar, string)) def decryptChar(self, char):...
9959211
from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize hello_parallel = Extension('hello_parallel', ['hello_parallel.pyx'], extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp...
9959234
import tensorflow as tf class LSTMNBase(object): '''Base class implementing the constructor and the generic soft attention reweighting. Args: num_units (int): Number of units in the hidden LSTMN layer scope (Optional[tf VariableScope]): Scope that all operations will be prefixed with. Att...
9959236
import click from a2ml.api.a2ml_experiment import A2MLExperiment from a2ml.api.utils.context import pass_context @click.group('experiment', short_help='Experiment management') @pass_context def cmdl(ctx): """Experiment management""" ctx.setup_logger(format='') @click.command(short_help='List Experiments for...
9959241
import subprocess import threading import re def getClipboardData(): p = subprocess.Popen(['pbpaste'], stdout=subprocess.PIPE) retcode = p.wait() data = p.stdout.read() return data.decode('utf-8') clip = getClipboardData() def check_for_clipboard_change(): global clip threading.Timer(0.5,...
9959245
import asyncio import logging import threading import multiprocessing from construct import Container from xbox.nano.render.client import Client from xbox.nano.render.sink import Sink from xbox.nano.render.video.sdl import SDLVideoRenderer from xbox.nano.render.audio.sdl import SDLAudioRenderer class BlockingClient(...
9959284
from typing import Dict, Any, Union from bxcommon.feed.eth.eth_transaction_feed_entry import EthTransactionFeedEntry from bxcommon.utils.object_hash import Sha256Hash class EthTransactionNoSignatureFeedEntry(EthTransactionFeedEntry): def __init__(self, tx_hash: Sha256Hash, tx_contents: Union[memoryview, Dict[str...
9959296
import torch from torch.autograd import Variable import torchvision from torchvision import transforms from PIL import Image import numpy as np from const import PAD class Data_loader(object): def __init__(self, path, imgs, labels, max_len, batch_size, is_cuda, img_size=299, evaluation=False): self._pa...
9959298
import logging import uuid from config import SQLALCHEMY_DATABASE_URI from sqlalchemy import Boolean, Column, DateTime, Float, Integer, String, create_engine from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker ...
9959312
from .kb_helper import * from .state_tracker import * from .dialog_manager import * from .dict_reader import * from .utils import *
9959357
from SimpleHTTPServer import SimpleHTTPRequestHandler from json import loads from random import randint from re import search as re_search from urllib import unquote class TinyHandler(SimpleHTTPRequestHandler, object): the_number = randint(1, 99999) def __init__(s...
9959371
from __future__ import absolute_import from __future__ import print_function # -*- coding: utf-8 -*- import numpy as np import os from keras.models import load_model import cv2 os.environ["CUDA_VISIBLE_DEVICES"]="2" learning_rate=0.001 continue_from_best=False model=load_model('bestweights3') os....
9959374
import unittest from isceobj.Util.mathModule import MathModule as MM class MathModuleTest(unittest.TestCase): def setUp(self): self.V = [1,2,3] self.M = [[1,2,3], [4,5,6], [7,8,9]] self.N = [[1,2,3], [1,2,3], [1,2,3]] ...
9959449
import haiku as hk from ..utils import is_stochastic, jit from .._core.base_stochastic_func_type1 import BaseStochasticFuncType1 from .._core.base_stochastic_func_type2 import BaseStochasticFuncType2 class Regularizer: r""" Abstract base class for policy regularizers. Check out :class:`coax.regularizers...
9959481
from speedtest import Speedtest #pip install speedtest-cli speedTest = Speedtest() print("donwload : ",speedTest.download()) print("upload :",speedTest.upload()) speedTest.get_servers([]) print("ping : ",speedTest.results.ping + " ms")
9959485
from __future__ import print_function from datetime import datetime import json import boto3 config = boto3.client('config') s3 = boto3.client('s3') def evaluate_compliance(rule_parameters): s3_bucket_name = rule_parameters['S3BucketName'] bucket_list = rule_parameters['LogBuckets'] non_compliant_list =...
9959496
from copy import deepcopy from easydict import EasyDict as edict import multiprocessing from lib import arguments, cfg_utils, fdutil, io_control_file, utils from lib.config import cfg as cfg_default from lib.validate_arguments import all_keys_known, is_boolean, is_string, is_positive_integer, valid_act_fn,\ valid_...
9959499
import glfw import compushady.config import compushady.formats import compushady from compushady.shaders import hlsl import struct import platform import math compushady.config.set_debug(True) print('Using device', compushady.get_current_device().name) target = compushady.Texture2D(1024, 1024, compushady.formats.B8G...
9959510
class BitcartError(Exception): """Generic error class for all errors raised""" class TemplateDoesNotExistError(BitcartError): """Template does not exist and has no default""" class TemplateLoadError(BitcartError): """Failed to load template file from disk"""
9959546
from pytezos.sandbox.node import SandboxedNodeAutoBakeTestCase from pytezos import ContractInterface from pytezos.operation.result import OperationResult code = """ parameter (or (int %decrement) (int %increment)); storage int; code { UNPAIR ; IF_LEFT { SWAP ; SUB } { ADD } ; NIL operation ; PAIR } """ class Concurr...
9959551
import os import re import datetime import dateutil.parser import configparser import numpy as np import astropy.io.fits as fits from astropy.table import Table from ...utils.misc import extract_date from ..common import load_obslog, load_config from .common import print_wrapper, get_ccd_geometry from .reduce import ...
9959582
import datetime import json import subprocess from urllib.parse import urljoin import requests import jsonpath_rw_ext as jp from openpyxl import Workbook from openpyxl.utils import get_column_letter from web.apps.web_copo.lookup import lookup as lk from web.apps.web_copo.schemas.utils.data_utils import json_to_pytype...
9959593
from fastapi import FastAPI from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html, ) from starlette.exceptions import HTTPException from starlette.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles from starlette.status i...
9959595
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import pandas as pd import pytest from treecat.format import export_rows from treecat.format import guess_schema from treecat.format import import_data from treecat.format import ...
9959596
import sys import numpy as np import tensorflow as tf sys.path.append("..") from libs import octree_samples tf.enable_eager_execution() # dump the octree samples for i in range(1, 7): name = 'octree_%d' % i octree = octree_samples(name) with open(name + '.octree', 'wb') as fid: fid.write(octree.numpy())
9959606
import numpy as np from helper import f from helper import f_prime_x0 from helper import f_prime_x1 from helper import plot_rosenbrock np.random.seed(0) def main() -> None: x0 = np.random.uniform(-2.0, 2.0) x1 = np.random.uniform(-2.0, 2.0) x_start = (x0, x1) y_start = f(x0, x1) print(f"Globa...
9959612
import sys from typing import Union from internalblue import Address def bytes_to_hex(data): # type: (Union[bytes, bytearray]) -> str return "".join(format(x, "02x") for x in bytearray(data)) def flat(data: [Address, bytes], filler: int) -> bytes: res = bytes() last_section_end = 0 for address ...
9959630
import pytest from mongoengine_migrate import actions @pytest.fixture def actions_rank(): """Actions are sorted by priority ascending""" return [ actions.RenameEmbedded, actions.CreateEmbedded, actions.AlterEmbedded, actions.RenameDocument, actions.CreateDocument, ...
9959641
import sys test_cases = open(sys.argv[1], 'r') for test in test_cases: test = test.strip() if len(test) == 0: continue lower = 0 upper = 0 for character in test: if character.islower(): lower += 1 else: upper += 1 lower = float(lower) / len(test) ...
9959679
import unittest from dbTools import * class TestDbRestaurantTable(unittest.TestCase): test_cases_insert = [ { 'signIn': [False, '', ''], 'tableNumber': 2, 'result': False }, { 'signIn': [True, 'rName1', '123456'], 'tabl...
9959722
from . import cli # __ __ ____ _ __ ___ # ____ ____ _ / /_ / /_ ___ / __ \ / | / // | # / __ \ / __ `// __// __// _ \ / /_/ // |/ // /| | # / /_/ // /_/ // /_ / /_ / __// _, _// /| // ___ | # / .___/ \__,_/ \__/ \__/ \___//_/ |_|/_/ |_//_/ |_| # /_/ # # (c) 2018-202...
9959733
import logging import os.path from typing import Any, Callable, Generator, Union, cast from more_itertools import ilen from thenewboston_node.business_logic.blockchain.file_blockchain.base import ( # noqa: I101 EXPECTED_LOCK_EXCEPTION, LOCKED_EXCEPTION, FileBlockchainBaseMixin ) from thenewboston_node.business_l...
9959742
from collections import namedtuple import re inequalities = { '.lt': lambda x, y: x < y, '.leq': lambda x, y: x <= y, '.eq': lambda x, y: x == y, '.geq': lambda x, y: x >= y, '.gt': lambda x, y: x > y, } class Phrase(object): fields = ['text', 'words', 'char_offsets', 'pos_tags', 'ner_tags', ...
9959764
import os import random import shell import string from hypothesis.database import ExampleDatabase from hypothesis import given, settings from hypothesis.strategies import lists, composite, integers, randoms, floats, text, sampled_from from test_util import run, clone_source, compile_buffer_sizes if os.environ.get('TE...
9959769
import logging import time from typing import Optional, List, Any, Dict import hydra import numpy as np import torch import torch.nn.functional as F from omegaconf import DictConfig from torch import Tensor, nn from pytorch_lightning import LightningModule from climart.data_loading.constants import TEST_YEARS, get_da...
9959781
import json import logging import os import sys from distutils.util import strtobool from typing import Any, Callable, Iterator, List, Optional, TypeVar, Union import requests from flask import Flask, Response, abort, jsonify, request, stream_with_context from plz.controller import configuration from plz.controller.a...
9959820
from typing import Union from boa3.builtin.interop.blockchain.block import Block from boa3.builtin.interop.blockchain.transaction import Transaction from boa3.builtin.interop.contract import Contract from boa3.builtin.type import UInt160, UInt256 current_height: int = 0 def get_contract(hash: UInt160) -> Contract: ...
9959838
import gtk from pyscrabble.constants import * class InfoWindow(gtk.Window): ''' Information window ''' def __init__(self, title, header, main): ''' Constructor @param title: Window title @param header: Header text ''' ...
9959916
import torchvision import typing import torch import logging log = logging.getLogger(__name__) __all__ = ['CIFAR10', 'CIFAR100'] #NOTE: normalization values taken from: https://github.com/kuangliu/pytorch-cifar/issues/19 __NORM_MEAN_STD__ = { 'CIFAR10': { 'mean': torch.Tensor([ [[0.49139968]...
9959952
import re import os from itertools import zip_longest class ReviewPair: def __init__(self, reference_file, target_file): self.reference_file = reference_file self.target_file = target_file def partition_files(reference_language, target_language, file_map): result = [] for path in file_ma...
9959973
import imagej import imagej.stack as ijs import xarray as xr # start imagej print("Starting ImageJ...") ij = imagej.init(headless=False) print(f"ImageJ Version: {ij.getVersion()}") # get xarray from dataset img = ij.io().open('/home/eevans/Downloads/test_stack.tif') img_xr = ij.pyfrom_java(img) # extract first chann...
9959974
from __future__ import division, absolute_import, print_function from .cifar10 import CIFAR10 from .mnist import MNIST
9960001
from .models import (TestModel, GenericModel, ReleaseResourcesParamsModel, ResourceDescriptorModel, UpdateFieldsParamsModel, LockResourcesParamsModel, StatisticsRequestModel)
9960002
from unittest import TestCase from back_propagation import * class TestBackPropagation(TestCase): def test_unit(self): unit1 = Unit() unit2 = Unit() unit3 = Unit(unit1, unit2) self.assertSequenceEqual(unit1.get_parents(), []) self.assertSequenceEqual(unit1.get_children(), [...
9960008
import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix from sklearn.metrics import roc_auc_score from sklearn.metrics import mean_squared_error import matplotlib matplotlib.use("TkAgg") # initiating random number np.random.seed(11) #### Creating the dataset # mean and standard deviation...
9960021
import pytest pytestmark = [pytest.mark.django_db] @pytest.fixture def api(api): api.user.is_superuser = True api.user.save() return api def test(api, diploma): api.delete(f'/api/v2/diplomas/{diploma.slug}/', expected_status_code=405)
9960103
import argparse import json import os import urllib import urllib.request import requests import sys from requests.auth import HTTPBasicAuth def get_course_page(api_url, token): return json.loads(requests.get(api_url, headers={'Authorization': 'Bearer ' + token}).text) def get_all_weeks(stepik_resp): return...
9960111
from abc import abstractmethod from openpype.modules import OpenPypeInterface class ISettingsChangeListener(OpenPypeInterface): """Module has plugin paths to return. Expected result is dictionary with keys "publish", "create", "load" or "actions" and values as list or string. { "publish": ["p...
9960124
import a import b import c import d import f A = 1 A = 1 A = 1 A = 1 A = 1 A = 1 def a(): pass def a(): pass def a(): pass def a(): pass A = 1 def a(): pass A = 1 def a(): pass A = 1 def a(): pass A = 1 A = 1 class a: pass class a: pass class a: pass ...
9960162
import configparser from typing import List, Dict, Optional, Union from math import ceil from pathlib import Path from jira import JIRA, JIRAError from django.conf import settings from apps.extractor.main.cleaner import clean_text from apps.extractor.main.preprocessor import calculate_ttr from apps.extractor.main.ma...
9960265
import warnings import numpy as np import matplotlib.pyplot as plt def plot(shapley_values, feature_names=None, sort_features=True, max_features=np.inf, orientation='horizontal', error_bars=True, color='tab:green', title='Feature Importance', tit...
9960297
from __future__ import print_function import argparse import sys import time import torch import torch.nn as nn import torch.optim as optim import torch.backends.cudnn as cudnn from torch.autograd import Variable import torch.utils.data as data import torchvision import torchvision.transforms as transforms from data_lo...
9960310
import FWCore.ParameterSet.Config as cms beamspotanalyzer = cms.EDAnalyzer('AnotherBeamSpotAnalyzer', bsCollection = cms.InputTag("offlineBeamSpot"), bsHistogramMakerPSet = cms.PSet( histoPa...
9960315
import unittest import hcl2 from checkov.terraform.checks.resource.gcp.GoogleProjectDefaultNetwork import check from checkov.common.models.enums import CheckResult class TestGoogleProjectDefaultNetwork(unittest.TestCase): def test_failure(self): hcl_res = hcl2.loads(""" resource "google...
9960330
def _create_ref(ref_type, pkg_name, name): """Creates a reference for the specified type. Args: ref_type: A `string` value. Must be one of the values in `reference_types`. pkg_name: The package name as a `string`. name: The name of the item as a `string`. Returns:...
9960367
import json import os import numpy as np import scipy as sp import pandas as pd from pandas.tools.plotting import scatter_matrix import seaborn as sns import matplotlib.pyplot as plt from mpl_toolkits.axes_grid.inset_locator import inset_axes import ast import cPickle as pickle for i in range(1,21): temp = [] ...
9960368
from yozuch.generators.template import TemplateEntry, TemplateGenerator from yozuch.paginator import Paginator class BlogIndexGenerator(TemplateGenerator): def __init__(self, url_template, name, template, posts_per_page=0, pagination_url=None): super().__init__(url_template, name, template) self....
9960440
class Solution: def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: result = [] for i in range(len(nums)): result = result[0:index[i]] + [nums[i]] + result[index[i]:] return result
9960462
def test_singleton(): from trame.app.singleton import Singleton @Singleton def new_object(): return object() # Normally, a new object would be returned each time # However, since this is a singleton, the same object should be returned assert new_object() is new_object()
9960471
from automlk.dataset import get_dataset_list, create_dataset_sets """ module specifically designed to update Xyset after new version """ for dt in get_dataset_list(): if dt.status != 'created': print(dt.name) # update X y set create_dataset_sets(dt)
9960486
import torch.nn as nn import FrEIA.framework as Ff import FrEIA.modules as Fm from .. import InvertibleArchitecture from .. import CouplingType from ..coupling_blocks.slow import AIO_SlowCouplingBlock from ..coupling_blocks.glow import AIO_GlowCouplingBlock from ...utils.dct_transform import DCTPooling2d class Inv...
9960581
import tensorflow as tf import numpy as np def sample_gumbel(shape, eps=1e-20): """Sample from Gumbel(0, 1)""" U = tf.random_uniform(shape,minval=0,maxval=1) return -tf.log(-tf.log(U + eps) + eps) def gumbel_softmax(logits, temperature): """ Draw a sample from the Gumbel-Softmax distribution""" y = logits + sa...
9960674
import math from . import meter import torch import numpy as np class ValueSummaryMeter(meter.Meter): def __init__(self): super(ValueSummaryMeter, self).__init__() self.reset() self.val = 0 def add(self, value, n=1): self.val = value self.sum += value self.var ...
9960738
import torch from models.distributions import BaseDistribution from models.distributions.diagonalgaussian import DiagonalGaussian from models.transformations.coupling import Coupling from models.transformations.squeeze import Squeeze from models.transformations.conv1x1 import Conv1x1 from models.transformations.normal...
9960741
from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Table, Column, Float, Integer, String, DateTime, MetaData, ForeignKey, func import os import random import string db=SQLAlchemy() class Users(db.Model): address = db.Column(db.String(80), primary_key=True, unique=True) submit_token = db.Column(db.Stri...
9960764
import unittest import torch from torch.utils.data import DataLoader from pytorchtrainer import create_default_trainer from pytorchtrainer.stop_condition import EarlyStopping from pytorchtrainer.callback import MetricCallback from pytorchtrainer.metric import Accuracy from test.common import XorModule, XorDataset c...
9960787
import lightgbm as lgb import pandas as pd import numpy as np from datetime import datetime from pathlib import Path from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import RepeatedStratifiedKFold from sklearn.model_selection import train_test_split path=Path("data/") train=pd.read_c...
9960791
class NoElementsError(Exception): pass class NullArgumentError(Exception): pass class NoMatchingElement(Exception): pass class MoreThanOneMatchingElement(Exception): pass
9960864
from typing import Type from uuid import UUID from sqlalchemy import select from api.db.errors import DoesNotExist from api.db.models.tenant import TenantCreate, TenantUpdate, TenantRead, Tenant from api.db.repositories.base import BaseRepository class TenantsRepository(BaseRepository[TenantCreate, TenantUpdate, Ten...
9960879
import pytest import open_cp.scripted.preds as preds import datetime def test_TimeRange(): tr = preds.TimeRange(datetime.datetime(2016,1,1), datetime.datetime(2016,1,5), datetime.timedelta(days=1)) assert tr.first == datetime.datetime(2016,1,1) assert tr.stop_before == datetime.datetime(2016,1,5...
9960888
import unittest from pyNTM import PerformanceModel class TestRSVPLSPConfigSetupBW(unittest.TestCase): def test_config_setup_bw_model_load(self): model = PerformanceModel.load_model_file( "test/lsp_configured_setup_bw_model.csv" ) model.update_simulation() self.assertEq...
9960914
import argparse import os.path as path import torch import torch.nn.functional as F from torch_geometric.datasets import Planetoid import torch_geometric.transforms as T from torch_geometric.nn import GCNConv, GAE, VGAE from torch_geometric.utils import train_test_split_edges from tinydfa import DFALayer, DFA from mod...
9960989
import pandas as pd import pytest from torch.utils.data import DataLoader from transformers import BertTokenizer from octopod import MultiDatasetLoader from octopod.ensemble import OctopodEnsembleDataset, OctopodEnsembleDatasetMultiLabel from octopod.text.dataset import OctopodTextDataset, OctopodTextDatasetMultiLabel...
9960992
import os import numpy as np import pickle from umap import UMAP target_output_dim = 2 batch_size = 10 input_dim = 28 model_path = 'pre-trained.model' train_data = np.random.rand(batch_size, input_dim) model = UMAP(n_components=target_output_dim, random_state=42) model.fit(train_data) pickle.dump(model, open(model_...
9961006
import unittest import Adafruit_NeoPixel_FTDI as neo class MockMPSSE(object): def __init__(self): self.output = None def Start(self): pass def Stop(self): pass def Write(self, data): self.output = data class Test_NeoPixel(unittest.TestCase): def test_build_byte_lookup(self): self.assertEqual(ne...
9961018
import configparser import logging logger = logging.getLogger(__name__) import cv2 from pose.hand_dataset.selector import select_dataset from pose.hand_dataset import common_dataset cv2.setNumThreads(0) def visualize_dataset(config, debug=True, visualize=True, iterate_all=False): dataset = select_dataset(conf...
9961054
from .runner import Runner import raylink import time class Manager(raylink.OutlineNode): TYPE = 'manager' def setup(self): """Setup manager node, create storage, ps captain, logger and runner, and put the config into the storage. """ st_time = time.time() self._stora...
9961132
import neptune neptune.init('shared/onboarding', api_token='<KEY>') with neptune.create_experiment(name='hello-neptune'): neptune.append_tag('introduction-minimal-example') n = 117 for i in range(1, n): neptune.log_metric('iteration', i) neptune.log_metric('loss', 1/i**0.5) neptune.log_text('magi...
9961167
import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler ############################################################################### # Helper Functions ############################################################################### class LayerNorm(nn.Modu...
9961178
import json import logging from http import HTTPStatus from random import randint from celery import chain from django.conf import settings from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from drf_yasg.utils import swagger_auto_schema from requests import HTTPE...
9961193
import argparse from typing import Dict, Any import numpy as np import torch from main_loop import generate_dataset, create_fold_generator from utils import AnalysisType, DatasetType, ConnType, Normalisation, EncodingStrategy def save_svm_format(dataset_slice, fold_num: int, fold_name: str, dataset_type: str, analy...
9961196
from django.urls import path from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView from ingest.schema import schema app_name = "ingest" urlpatterns = [ path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True, schema=schema))), ]
9961294
import itertools import os import pickle import numpy as np from hypergrad.util import dictslice from hypergrad.mnist import random_partition def datapath(fname): project_dir = os.environ['EXPERI_PROJECT_PATH'] datadir = project_dir+"/library/hypergrad/data/mnist" # datadir = os.path.expanduser('/Users/...
9961318
import argparse import math import multiprocessing import os import random import sys import chainer import chainer.functions as cf import chainermn import cupy as cp import matplotlib.pyplot as plt import numpy as np from chainer.backends import cuda import gqn from gqn.data import Dataset, Iterator from gqn.preproc...
9961402
import sys import os import ntpath import json import requests _AZFUNC_API_KEY="AZURE_FUNCTION_KEY: ex. aRVQ7Lj0vzDhY0JBYF8gpxYyEBxLwhO51JSC7X5dZFbTvROs7xNg==" _AZFUNC_API_URL="AZURE_FUNCTION_ENDPOINT: ex. https://<app_account>.azurewebsites.net/api/<func_name>" if __name__ == '__main__': file_path = "/tmp/...
9961415
import numpy as np from audiomate.utils import stats from . import container class FeatureContainer(container.Container): """ The FeatureContainer is a container for storing features extracted from audio data. Features are array-like data, where every feature represents the properties of a given segm...