id
stringlengths
3
8
content
stringlengths
100
981k
11524648
import mxnet as mx from mxnet import gluon from mxnet import nd from mxnet.gluon.loss import Loss, _reshape_like import horovod.mxnet as hvd def _as_list(arr): """Make sure input is a list of mxnet NDArray""" if not isinstance(arr, (list, tuple)): return [arr] return arr class SSDMultiBoxLoss(Lo...
11524649
import numpy as np a = np.arange(3) print(a) # [0 1 2] b = np.arange(3) print(b) # [0 1 2] c = np.arange(1, 4) print(c) # [1 2 3] print(np.all(a == b)) # True print(np.all(a == c)) # False print(np.array_equal(a, b)) # True print(np.array_equal(a, c)) # False print(np.array_equiv(a, b)) # True print(np.array_e...
11524658
import pylearn2 import pylearn2.datasets as ds import pickle import numpy as np train_sets = [] valid_sets = [] test_sets = [] for i in range(5): with open("../../data/pylearn2/train_car_{:02d}.pkl".format(i),'r') as f: train_sets.append(pickle.load(f)) with open("../../data/pylearn2/valid_ca...
11524706
import sys import os import argparse import winreg import pathlib from IPython import embed from traitlets.config import get_config import winsandbox def read_args(): parser = argparse.ArgumentParser() parser.add_argument("-i", "--interactive", default=False, action="store_true", hel...
11524721
from django.apps import AppConfig class HealthCenterConfig(AppConfig): name = 'applications.health_center'
11524731
from setuptools import setup import os setup( name='FlaskSearch', version='0.1', url='https://github.com/dhamaniasad/Flask-Search', license='BSD', author='<NAME>', author_email='<EMAIL>', description='Powerful search functionality for Flask apps via ElasticSearch', py_modules=['flask_se...
11524748
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from numpy import sqrt, exp, array from inference.mcmc import HamiltonianChain """ # Hamiltonian sampling example Hamiltonian Monte-Carlo (HMC) is a MCMC algorithm which is able to efficiently sample from complex PDFs which present difficulty for...
11524749
from math import sqrt, floor from collections import Counter def center_of_geometry(Coordinates): ''' Give me x, y, z coordinates, get back the cooresponding center of geometry ''' return [sum(Coordinate)/len(Coordinate) for Coordinate in zip(*Coordinates)] def distance(Coordinates): ''' Eu...
11524768
import traceback import math import numpy as np import litenn as nn import litenn.core as nc from litenn.core import CLKernelHelper as ph def conv2DTranspose (input_t, kernel_t, stride=2, dilation=1, padding='same'): """ conv2DTranspose operator. input_t Tensor shape must be ...
11524780
import tensorflow as tf import edward as ed from edward.models import Categorical, Normal, Bernoulli from keras.utils import to_categorical import numpy as np ############################################ ### THIS INTERNAL DEFINITION FOR THE NN #### ############################################ #########################...
11524787
import ast from collections import defaultdict from typing import Any, Dict, List, Optional, Union from flake8_plugin_utils import Visitor from .errors import ( ImplicitReturn, ImplicitReturnValue, UnnecessaryAssign, UnnecessaryReturnNone, ) from .utils import is_false, is_none NameToLines = Dict[str...
11524789
from falcon_unzip.dedup_h_tigs import main import sys if __name__ == "__main__": main(sys.argv)
11524792
import asyncio from threading import Thread class Pool: def __init__(self): self.loop = asyncio.get_event_loop() self.loop_runner = Thread(target=self.loop.run_forever) self.loop_runner.daemon = True self.loop_runner.start() def run(self, coro): return asyncio.run_coro...
11524826
import sys assert sys.version_info >= (3, 5) import os import pathlib import json import open3d as o3d if __name__ == '__main__': base_folder = "/cluster/project/infk/courses/3d_vision_21/group_14/1_data" model_base_folder = os.path.join(base_folder, "ShapeNetCore.v2") pcd_base_folder = os.path.joi...
11524857
import torch def to_batch(state, action, reward, next_state, done, device): state = torch.FloatTensor(state).unsqueeze(0).to(device) action = torch.FloatTensor([action]).view(1, -1).to(device) reward = torch.FloatTensor([reward]).unsqueeze(0).to(device) next_state = torch.FloatTensor(next_state).unsqu...
11524917
import sys import subprocess from xml.dom import minidom import json class TestResultParser: def parse_file(self, filename): return self.parse(open(filename).read()) def parse(self, xmltext): doc = minidom.parseString(xmltext) root = doc.documentElement test_suites = [self.proc...
11524927
import argparse import sys import csv import os parser = argparse.ArgumentParser() parser.add_argument('--primer-snp-bed', type=str, required=True) parser.add_argument('--amplicon-depth-tsv', type=str, required=True) parser.add_argument('--sample-name', type=str, default="none") args, files = parser.parse_known_args()...
11524940
from osr2mp4.ImageProcess import imageproc from osr2mp4.ImageProcess.PrepareFrames.YImage import YImage scoreboard = "menu-button-background" def prepare_scoreboard(scale, settings): """ :param scale: float :return: [PIL.Image] """ img = YImage(scoreboard, settings, scale).img img = img.crop((int(img.size[0] ...
11524983
import os SERVICE_VERSIONS = ( ("service-less-equal", "2.2", "3.0"), ("service-greater-equal", "1.5", "2.2"), ("service-equal", "2.2", '2.2'), ('service-less', '2.3', '2.4'), ("service-greater", '1', '2'), ) CLUSTER_VERSIONS = ( ("cluster-less-equal", "1.6", "2.0"), ("cluster-greater-equal...
11524992
from __future__ import absolute_import import os import deepthought.spearmint.wrapper as spearmint_wrapper # Write a function like this called 'main' def main(job_id, params): print 'Anything printed here will end up in the output directory for job #:', str(job_id); print params; print os.environ['PYTHONPATH']...
11525026
import os import sqlalchemy import datetime from sqlalchemy import Column, VARCHAR, Integer, String, DateTime, ForeignKey, Boolean from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy.sql import exists from dot...
11525034
import pytest @pytest.mark.parametrize('query, expected_terms', [ # query expected ('the one', ['the one', 'the', 'one', '1']), ('to be or not to be', ['to be', 'be or', 'or not', 'not to', 'to', 'be', 'or']), ('html', ['html', 'Hypertext Markup Language']) ...
11525036
import tensorflow as tf from data_utils import Vocabulary, batch_generator from model import LSTMModel import os import codecs FLAGS = tf.flags.FLAGS tf.flags.DEFINE_string('checkpoint_path', 'checkpoint/base', 'model path') tf.flags.DEFINE_integer('batch_size', 100, 'number of seqs in one batch') tf.flags.DEFINE_int...
11525100
import numpy as np from scipy.stats import norm from scipy.special import gammaln def two_tailed_ztest(success1, success2, total1, total2): """ Two-tailed z score for proportions Parameters ------- success1 : int the number of success in `total1` trials/observations success2 : int ...
11525102
import numpy as np import cv2 import scipy.misc def normalization(img): # rescale input img within [-1,1] return img / 127.5 - 1 def inverse_normalization(img): # rescale output img within [0,1], then saving by 'scipy.misc.imsave' return (img + 1.) / 2. def read_one_img(img_dir): img = cv2.imr...
11525130
from django.db import models from .product import Product class TestCase(models.Model): PRIORITY_CHOICES = ((0, 'Urgent'), (1, 'High'), (2, 'Medium'), (3, 'Low')) name = models.CharField(max_length=200) full_name = models.CharField(max_length=400, default='') keyword = models.CharField(max_length=10...
11525140
import base64 import secrets import string import struct from itertools import islice, cycle from encoders.Encoder import Encoder from engine.component.CallComponent import CallComponent from engine.component.CodeComponent import CodeComponent from engine.modules.EncoderModule import EncoderModule from enums.Language ...
11525250
from udpwkpf import WuClass, Device import sys import mraa from twisted.protocols import basic from twisted.internet import reactor, protocol PORT = 2222 if __name__ == "__main__": class Number(WuClass): #"Number" WuClass has been defined in ~/wukong-darjeeling/wukong/ComponentDefinitions/WuKongStandardLibrary.x...
11525259
from unittest import TestCase from DivideTwoIntegers import DivideTwoIntegers class TestDivideTwoIntegers(TestCase): def test_divide(self): d = DivideTwoIntegers() self.assertTrue(d.divide(1, 1) == 1) self.assertTrue(d.divide(0, 1) == 0) self.assertTrue(d.divide(-1, -1) == 1) ...
11525264
DEBUG = True SECRET_KEY = "unguessable" INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "rest_framework.authtoken", "redis_pubsub", "testapp" ] DATABASES = { "default": { ...
11525269
import Cell class GridWorld: def __init__(self, width, height, obstacles): self.width = width self.height = height self.cells = [[Cell.Cell(i, j) for j in range(width)] for i in range(height)] self.obstacles = obstacles for obstacle in self.obstacles: self.cells[obstacle[0]][obstacle[1]].obsta...
11525282
from models import (cluster) generator_dict = {'standard': cluster.G} discriminator_dict = {'standard': cluster.D}
11525289
from .model import Model import numpy as np import time def softmax(x): r"""Compute softmax values for each sets of scores in $x$. Args: x (numpy.ndarray): Input vector to compute softmax Returns: numpy.ndarray: softmax(x) """ e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(...
11525290
try: import ldap except ImportError: pass import logging from django.conf import settings from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import Group, User from django.core.exceptions import PermissionDenied from django_auth_adfs.backend import AdfsAuthCodeBackend from ...
11525295
import numpy as np from scipy.special import hyp2f1, gammaln def get_r2(iv, dv, stack_intercept=True): """ Regress dv onto iv and return r-squared. Parameters ---------- iv : numpy array Array of shape N (samples) x K (features) dv : numpy array Array of shape N (samples) x 1 ...
11525310
import warnings from typing import Any from prefect.executors import LocalExecutor as _LocalExecutor class LocalExecutor(_LocalExecutor): def __new__(cls, *args: Any, **kwargs: Any) -> "LocalExecutor": warnings.warn( "prefect.engine.executors.LocalExecutor has been moved to " "`pr...
11525312
import os import sys import time import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) node = cluster.add_instance('node', stay_alive=T...
11525326
import dexy.reporters.nodegraph.d3 import dexy.reporters.nodegraph.text import dexy.reporters.nodegraph.graphviz
11525338
from django.db import models from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User class SimpleText(models.Model): """A Testing app""" firstname = models.CharField(blank=True, max_length=255) lastname = models....
11525361
from flask_restplus import Resource, reqparse from flask_jwt import jwt_required from models.item import ItemModel class Item(Resource): # Adding parser as part of the class parser = reqparse.RequestParser() parser.add_argument('price', type = float, required = True, help = "Price is required!" )...
11525368
import keras.layers as KL import keras.backend as K import tensorflow as tf from lib.nets.resnet_backbone import identity_block as bottleneck from keras.utils import conv_utils from keras.engine import InputSpec import numpy as np class UpsampleBilinear(KL.Layer): def call(self, inputs, **kwargs): source, ...
11525385
import FWCore.ParameterSet.Config as cms pythiaUESettingsBlock = cms.PSet( pythiaUESettings = cms.vstring( 'MSTU(21)=1 ! Check on possible errors during program execution', 'MSTJ(22)=2 ! Decay those unstable particles', 'PARJ(71)=10 . ! for which ctau 10 mm', 'MSTP(33)=0 ! no K factors in har...
11525409
try: import tensorflow as tf except ImportError: tf = None class NegBinOutput(tf.keras.layers.Layer): """Negative binomial output layer""" def __init__( self, original_dim=None, name='neg_bin_output', **kwargs ): super().__init__(name=name,...
11525429
from django.db import models from data_refinery_common.models.computational_result import ComputationalResult from data_refinery_common.models.sample import Sample class SampleResultAssociation(models.Model): sample = models.ForeignKey(Sample, blank=False, null=False, on_delete=models.CASCADE) result = mode...
11525447
from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand class Command(BaseCommand): help = """Print the list of users.""" def handle(self, *args, **options): # Print out users. User = get_user_model() for x in User.objects.all(): p...
11525458
from __future__ import annotations from textwrap import dedent from typing import Callable import pytest from pytest_mock import MockerFixture from tomlkit.toml_document import TOMLDocument from pyproject_fmt.formatter import format_pyproject from pyproject_fmt.formatter.config import Config from tests import Fmt ...
11525474
import numpy as np full_data_dir = '../cifar100/cifar-100-python/train' vali_dir = '../cifar100/cifar-100-python/test' DATA_URL = 'http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz' IMG_WIDTH = 32 IMG_HEIGHT = 32 IMG_DEPTH = 3 NUM_CLASS = 100 NUM_TRAIN_BATCH = 1 EPOCH_SIZE = 50000 * NUM_TRAIN_BATCH def _read...
11525480
import json class BaseModel(object): def to_dict(self): return self.schema.dump(self).data @classmethod def from_dict(cls, dct): return cls.schema.load(dct).data
11525494
import datetime import logging from django.core.management.base import BaseCommand from main.models import Localization logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Deletes any localizations marked for deletion with null project, type, version, or media.' def add_arguments(self, ...
11525520
from runboat.github import CommitInfo from runboat.k8s import DeploymentMode, _render_kubefiles, make_deployment_vars from runboat.settings import BuildSettings EXPECTED = """\ resources: - pvc.yaml - deployment.yaml - service.yaml - ingress.yaml namespace: runboat-builds namePrefix: "build-name-" commonLab...
11525532
import os import sys import logging from pyomo.environ import * from pyomo.opt import TerminationCondition import numpy as np import pandas as pd class CALVIN(): def __init__(self, linksfile, ic=None, log_name="calvin"): """ Initialize CALVIN model object. :param linksfile: (string) CSV file containin...
11525542
from flask import render_template from flask import request from flask import Blueprint from flask import flash from flask import redirect from flask import url_for from flask import jsonify from flaskapp.config import ExampleData from flaskapp.utils import gmaps_tool as tls main = Blueprint("main", __name__) @ma...
11525545
import os import sys sys.path.insert(1, os.path.join(sys.path[0], '../pytorch')) import numpy as np import argparse import h5py import math import time import logging import yaml import pickle import matplotlib.pyplot as plt from sklearn import metrics import torch import torch.nn as nn import torch.nn.functional as F...
11525553
import pytest from dbt.tests.util import run_dbt from tests.functional.graph_selection.fixtures import SelectionFixtures def run_schema_and_assert(project, include, exclude, expected_tests): # deps must run before seed run_dbt(["deps"]) run_dbt(["seed"]) results = run_dbt(["run", "--exclude", "never...
11525592
from amaranth_boards.upduino_v2 import * from amaranth_boards.upduino_v2 import __all__ import warnings warnings.warn("instead of nmigen_boards.upduino_v2, use amaranth_boards.upduino_v2", DeprecationWarning, stacklevel=2)
11525596
import string import random from time import sleep from decimal import Decimal from mock import patch, MagicMock from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from django.test import TransactionTestCase from cc.models import Wallet, Address, Currency, Operation, Transaction, WithdrawTransaction f...
11525598
import numpy as np import scipy.stats import subprocess import os import warnings from genome_integration import simulate_mr from genome_integration import utils from genome_integration.association import GeneticAssociation def read_assocs_from_plink_qassoc(assoc_file): assocs = {} with open(assoc_file, "r") ...
11525607
import tensorflow as tf from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D from tensorflow.keras.models import Model from tensorflow.keras import backend as K input_img = Input(shape=(28, 28, 1)) # adapt this if using `channels_first` image data format x = Conv2D(16, (3, 3), activat...
11525629
from bayesnet.sampler.hmc import hmc from bayesnet.sampler.metropolis import metropolis __all__ = [ "hmc", "metropolis" ]
11525649
from google.appengine.ext import ndb from werkzeug.test import Client from backend.api.handlers.helpers.model_properties import simple_team_properties from backend.common.consts.auth_type import AuthType from backend.common.models.api_auth_access import ApiAuthAccess from backend.common.models.event_team import EventT...
11525667
import visdom import pickle import os import numpy as np from sklearn.manifold import TSNE import matplotlib.pyplot as plt class FeatureVisualizer(object): def __init__(self, data_root, feature_root, env): self.data_root = data_root self.feature_root = feature_root self.feature_data = pi...
11525668
from glob import glob from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QVBoxLayout, QDialog, QLabel, QWidget, QHBoxLayout, QSizePolicy, QApplication from bauh import __version__, __app_name__, ROOT_DIR from bauh.context import generate_i18n from bauh.view.util import resource PROJECT_URL = 'https://github.c...
11525709
from __future__ import annotations from typing import List, Iterator, Type, Tuple, Union, TYPE_CHECKING import ast from ..action import default_actions, actions if TYPE_CHECKING: from ..models import ( SchemaActionModel, MorphActionModel, CategoryActionModel, ColumnModel, C...
11525717
from unittest import TestCase import numpy as np import nibabel as nib from unet3d.utils.resample import resample from unet3d.utils.augment import scale_affine, generate_permutation_keys, permute_data class TestAugmentation(TestCase): def setUp(self): self.shape = (4, 4, 4) self.affine = np.dia...
11525729
import numpy as np from skimage.measure import compare_ssim as ssim import imageio import os def calculate_ssim_l1_given_paths(paths): file_list = os.listdir(paths[0]) ssim_value = 0 l1_value = 0 for f in file_list: # assert(i[0] == i[1]) fake = load_img(paths[0] + f) real = lo...
11525767
import re import numpy as np import pandas as pd def read_file(path): with open(path, 'r') as f: content = f.read() return content def tosec(t): return round(float(re.findall(r'.*(?=s)', t)[0]), 3) def minsec2sec(t): m = re.findall(r'\d+(?=min)', t)[0] _s = re.findall(r'\d+(?=s)', t) ...
11525773
import ntpath from datetime import datetime as dt import os import pandas as pd import numpy as np import math import sqlite3 # clean the original raw data by storing only the columns that we need, and removing the rest. def clean(from_path, to_path, columns): def convert_date(date): if date == '': ...
11525796
import logging logging.warning('ramiro_analysis is deprecated, use composite analysis instead') from pycqed.analysis.composite_analysis import *
11525801
import os import unittest import chapter test_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test_files') class ChapterTests(unittest.TestCase): def setUp(self): self.factory = chapter.ChapterFactory() ## def test_create_chapter_from_url(self): ## c = self.fac...
11525804
from .helpers import * import numpy as np import json import copy import scipy.interpolate as interp import matplotlib.pyplot as plt class Airfoil: """A class defining an airfoil. Parameters ---------- name : str Name of the airfoil. input_dict : dict Dictionary describing the ai...
11525811
from typing import Callable, List from pip._internal.req.req_install import InstallRequirement from pip._internal.req.req_set import RequirementSet InstallRequirementProvider = Callable[[str, InstallRequirement], InstallRequirement] class BaseResolver: def resolve( self, root_reqs: List[Instal...
11525823
from typing import Any, Dict, Optional from aiogram import Bot from aiogram.dispatcher.filters.state import State from aiogram.types import Chat, User from .protocols import DialogRegistryProto, BaseDialogManager from ..context.events import ( Data, Action, DialogStartEvent, DialogSwitchEvent, DialogUpdateEvent, ...
11525834
from typing import Optional, List import torch import torch.nn.functional as F import torch.distributed as dist from torch import Tensor from torch.nn.parameter import Parameter from . import _reduction as _Reduction from ..__init__ import _PARALLEL_DIM from ..__init__ import set_attribute from ..distributed import...
11525837
import tkinter as tk import requests from bs4 import BeautifulSoup url = 'https://weather.com/en-IN/weather/today/l/32355ced66b7ce3ab7ccafb0a4f45f12e7c915bcf8454f712efa57474ba8d6c8' frameWindow = tk.Tk() frameWindow.title("Weather") frameWindow.config(bg = 'white') def getWeather(): page = requests.get(url) ...
11525842
from __future__ import absolute_import, print_function, unicode_literals import sys from collections.abc import Callable is_ironpython = "IronPython" in sys.version def is_callable(x): return isinstance(x, Callable) def execfile(fname, glob, loc=None): loc = loc if (loc is not None) else glob exec( ...
11525855
from __future__ import annotations from typing import Any, Dict, Optional from boa3.constants import GAS_SCRIPT from boa3.model.method import Method from boa3.model.property import Property from boa3.model.type.classes.classarraytype import ClassArrayType from boa3.model.variable import Variable class GasClass(Clas...
11525876
import hoverxref import setuptools with open('README.rst', 'r') as fh: long_description = fh.read() setuptools.setup( name='sphinx-hoverxref', version=hoverxref.version, author='<NAME>', author_email='<EMAIL>', description='Sphinx extension to embed content in a tooltip on xref hover', ur...
11525881
import functools import re import parsimonious from parsimonious import ( expressions, ) from eth_abi.exceptions import ( ABITypeError, ParseError, ) grammar = parsimonious.Grammar(r""" type = tuple_type / basic_type tuple_type = components arrlist? components = non_zero_tuple / zero_tuple non_zero_tup...
11525902
from ramda import * from ramda.private.asserts import * def remove_test(): assert_equal(remove(2, 3, [1, 2, 3, 4, 5, 6, 7, 8]), [1, 2, 6, 7, 8])
11525942
from typing import NamedTuple, List, Dict from ..asserts.asserts import FieldValidator class Production(NamedTuple): id: str children: List[str] @classmethod def from_json(cls, d: dict) -> 'Production': v = FieldValidator(cls, d) return Production( id=v.get('id', int), ...
11525959
from random import randint class Product(object): def __init__(self, name, price = 10, weight = 20, flammability = 0.5): self.name = name self.price = price self.weight = weight self.flammability = flammability self.identifier = randint(10e5, 10e6-1) def stealability(se...
11525991
del_items(0x8013CAB4) SetType(0x8013CAB4, "struct Creds CreditsTitle[6]") del_items(0x8013CC5C) SetType(0x8013CC5C, "struct Creds CreditsSubTitle[28]") del_items(0x8013D0F8) SetType(0x8013D0F8, "struct Creds CreditsText[35]") del_items(0x8013D210) SetType(0x8013D210, "int CreditsTable[224]") del_items(0x8013E420) SetTy...
11525993
import numpy as np import cv2 from lanetracker.window import Window from lanetracker.line import Line from lanetracker.gradients import get_edges from lanetracker.perspective import flatten_perspective class LaneTracker(object): """ Tracks the lane in a series of consecutive frames. """ def __init__(...
11526013
import gym from gym.wrappers import TimeLimit from rlkit.envs.wrappers import CustomInfoEnv, NormalizedBoxEnv def make_env(name): env = gym.make(name) # Remove TimeLimit Wrapper if isinstance(env, TimeLimit): env = env.unwrapped env = CustomInfoEnv(env) env = NormalizedBoxEnv(...
11526062
from functools import partial from textwrap import dedent from unittest import skip, expectedFailure # noqa: F401 import sublime from SublimeLinter.lint import ( backend, Linter, linter as linter_module, util, ) from unittesting import DeferrableTestCase from SublimeLinter.tests.parameterized import ...
11526118
from .dataloader import * from .dataset import * from .openml_download import * from .mxutils import *
11526127
from unification import var from kanren import run, membero from kanren.arith import lt, gt, lte, gte, add, sub, mul, mod, div x = var('x') y = var('y') def results(g): return list(g({})) def test_lt(): assert results(lt(1, 2)) assert not results(lt(2, 1)) assert not results(lt(2, 2)) def test_g...
11526136
import wx import re import platform import datetime import Utils reNonTimeChars = re.compile('[^0-9:.]') def secsToValue( secs, allow_none, display_seconds, display_milliseconds ): if secs is None and allow_none: return secs v = Utils.formatTime( secs, highPrecision=True, extraPrecision=True, forceHours...
11526142
from machine import Pin from time import sleep_ms, sleep_us ser = Pin(5, Pin.OUT) ser.value(0) rclock = Pin(6, Pin.OUT) rclock.value(0) srclock = Pin(7, Pin.OUT) srclock.value(0) def srclock_pulse(): srclock.value(1) sleep_us(10) srclock.value(0) sleep_us(10) def rclock_pulse(): rclock.value(1)...
11526181
from casadi import * x = SX.sym('x') u = SX.sym('u') xu = vertcat(x, u) rhs = x - u discrete_model = Function('discrete_model', [x, u], [rhs, jacobian(rhs, xu)]) discrete_model.generate('discrete_model.c', {'with_header': True}) discrete_model_cost = Function('discrete_model_cost', [x, u], [xu, jacobian(xu, xu)]) d...
11526218
import random from torch.utils.data.sampler import Sampler def _batchify(l, batch_size): for i in range(0, len(l), batch_size): yield l[i:i + batch_size] def _flatten(l): return [item for sublist in l for item in sublist] class SubsetSequentialSampler(Sampler): """ Samples elements sequen...
11526232
from flask import Flask, render_template, send_file, make_response, url_for, Response,request,redirect from flask_restful import reqparse, abort, Api, Resource import pickle import numpy as np import werkzeug from Predictor import * app = Flask(__name__) api = Api(app) predictor = Predictor() parser = reqparse.Request...
11526238
import json from ..exceptions import SparkPostAPIException as RequestsSparkPostAPIException class SparkPostAPIException(RequestsSparkPostAPIException): def __init__(self, response, *args, **kwargs): errors = None # noinspection PyBroadException try: data = json.loads(response....
11526241
import unittest from smsframework import Gateway from smsframework.providers import NullProvider from smsframework import OutgoingMessage, IncomingMessage, MessageStatus class GatewayTest(unittest.TestCase): """ Test Gateway """ def setUp(self): self.gw = Gateway() # Providers self....
11526245
import itertools import json import random import time from ast import literal_eval as make_tuple from multiprocessing import Process, Queue import numpy as np import psutil from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.gaussian_process i...
11526250
import unittest import torch from torch.autograd import Variable from torchsample.metrics import CategoricalAccuracy class TestMetrics(unittest.TestCase): def test_categorical_accuracy(self): metric = CategoricalAccuracy() predicted = Variable(torch.eye(10)) expected = Variable(torch.Long...
11526258
import torch from torch.autograd import Variable from unittest import TestCase from wavenet_modules import dilate class Test_Dilation(TestCase): def test_dilate(self): input = Variable(torch.linspace(0, 12, steps=13).view(1, 1, 13)) dilated = dilate(input, 1) assert dilated.size() == (1, ...
11526259
import requests plugin_name = 'malshare' config = None def check(query): API_KEY = config['api'] url ='https://malshare.com/api.php?api_key={}&action=details&hash={}'.format(API_KEY, query) print(url) req = requests.get(url) res = {} res['found'] = True if b'Sample not found by hash' not in re...
11526261
import numpy as np import matplotlib.pyplot as plt from moviepy.editor import * from moviepy.video.io.bindings import mplfig_to_npimage if __name__ == '__main__': #Boolean to set whether to include audio or not in final product include_audio = False # Read in data generated from previous video a...
11526268
from openstatesapi.jurisdiction import make_jurisdiction J = make_jurisdiction('ks') J.url = 'http://kansas.gov'