content
stringlengths
5
1.05M
################################################# # SN74HC595 with software SPI ESP12-E # # Sums up 1 bit by 1 bit till 255 is reached # # Author: Miguel Sama # # Date: 19/06/2018 # ################################################# from machine import...
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with...
import clr if clr.use35: clr.AddReference("Microsoft.Scripting") clr.AddReference("Microsoft.Dynamic") clr.AddReference("Microsoft.Scripting.Core") import Microsoft.Scripting.Ast as Exprs from Microsoft.Scripting.ComInterop import ComBinder from Microsoft.Scripting.Utils import (Action, Func)...
import os import json, boto3 def lambda_handler(event, context): print("Trigger Event: ") print(event) region = os.environ['REGION'] elbv2_client = boto3.client('elbv2', region_name=region) available_target_groups = os.environ['AVAILABLE_TARGET_GROUPS'] arr_available_target_groups = available_...
import RPi.GPIO as GPIO import time pinServo=40 GPIO.cleanup() GPIO.setmode(GPIO.BOARD) GPIO.setup(pinServo, GPIO.OUT) servo=GPIO.PWM(pinServo, 50) servo.start(0) while True: ang = int(input()) # if (ang>170 and ang < 0): # print('angulo no posible') # break # else: servo.ChangeDutyCycle((ang*12/180)) time.sleep(...
from cdmanager import cd import os import shutil from pathlib import Path working_folder = '../data/tfs_rep_2/' destination_folder = '../gemFiles/rep2/' with cd(working_folder): for root, dirs, files in os.walk('./'): #print(dirs) if 'GEMout' in dirs: namedir = str(root.replace('./', '...
from __future__ import annotations import decimal import re import pytest from django.core.validators import MaxValueValidator, MinValueValidator, URLValidator from rest_framework import serializers from rest_framework.fields import ( BooleanField, CharField, DateField, DateTimeField, DecimalField...
from typing import Optional from pydantic import BaseModel, Field class ScopeCreate(BaseModel): scope_name: str = Field(max_length=32) description: str = Field(max_length=128) default: Optional[bool] = Field(default=False) class ScopeUpdate(BaseModel): description: str = Field(max_length=128) clas...
def day2_1(): total = 0 for line in open('day2input.txt'): l, w, h = line.split('x') l, w, h = int(l), int(w), int(h) area = 2*l*w + 2*w*h + 2*h*l slack = min(l*w, w*h, h*l) total += area + slack print total def day2_2(): total = 0 for line in open('day2inpu...
# PROJECT DECEMBRE 2019 # PROJECT STAR MAP / DATABASE # By Enguerran VIDAL # This file contains the database handling functions. ############################################################### # IMPORTS # #############################################################...
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import pydart import controller import numpy as np import pickle import action as ac from numpy.linalg import inv import mmMath state = {} state['DrawAxis'] = True state['DrawGrid'] = True state['DrawDataAbs'] = True state['DrawDataRelGlobal'] ...
#!/usr/bin/python # -*- coding: UTF-8 -*- from django.conf.urls import include, url from django.contrib import admin from gps.view.index import * urlpatterns = [ url('^getPeople/$', getPeople), url('^getGPS/$', getGPS), url('^sendGPS/$', sendGPS), ]
import csv import glob import math import os import sys from random import random, seed from timeit import default_timer as timer import time from statistics import mean from pathlib import Path import networkx as nx import numpy as np from scapy.layers.inet import IP, UDP from scapy.utils import PcapWriter, PcapReader...
import os import sys import glob import pickle import shutil import argparse import tensorflow as tf def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def read_pickle_fr...
#!/usr/bin/pyton import numpy as np from matplotlib import pyplot as plt from matplotlib import animation import pdb import os directory=os.path.basename(__file__)[:-3] if not os.path.exists('texFiles/'+str(directory)): os.system('mkdir texFiles/'+str(directory)) path='texFiles/'+str(directory) """ Comparison ...
import logging from contextlib import closing from typing import Any, Dict, Optional from flask_appbuilder.security.sqla.models import User from flask_babel import gettext as _ from sqlalchemy.engine.url import make_url from sqlalchemy.exc import DBAPIError, NoSuchModuleError from rabbitai.commands.base import BaseCo...
""" Created on Mon Jan 18 12:34:06 2021 Note this is working with ETABs v19, comtypes v1.1.7. It is not working on my local machiene only on the remote desktop @author: aguter """ import numpy as np import os import sys import comtypes.client import matplotlib.pyplot as plt ProgramPath = r"C:\Program Files...
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
from unittest import mock from src.video_player import VideoPlayer def test_flag_video_with_reason(capfd): player = VideoPlayer() player.flag_video("amazing_cats_video_id", "dont_like_cats") out, err = capfd.readouterr() lines = out.splitlines() assert len(lines) == 1 assert "Successfully fla...
from app import db from app import models from flask import Blueprint bp = Blueprint("setup", __name__) @bp.route("/", methods=["POST"], strict_slashes=False) def setup(): models.Base.metadata.create_all(db.get_engine()) return "<h1> Created DB successfully! </h1>"
try: from setuptools import setup except ImportError: print("No setuptools package, using distutils.core") from distutils.core import setup import unittest def my_test_suite(): test_loader = unittest.TestLoader() test_suite = test_loader.discover('tests', pattern='test_*.py') return test_suite setup...
from .compare_gw import *
from django import forms from django.forms import widgets from django.utils.translation import ugettext as _ from .models import Organization from .utils import get_data_source_model class OrganizationForm(forms.ModelForm): class Meta: model = Organization fields = ( 'data_source', '...
import inspect import sys import threading from typing import Callable, Union, TypeVar, Any, Generic, Optional, List, Iterable class PromiseResolver: __slots__ = ("_promise", ) def __init__(self, promise): self._promise = promise def resolve(self, val): if self._promise is None: return self._promise._re...
from __future__ import annotations import multiprocessing import queue import threading import time from dataclasses import dataclass, field from multiprocessing import Queue, Process from queue import Empty from threading import Thread from typing import List, Dict import psutil import requests from MHDDoS.attack i...
from .convscore_solver import SolverConvScore import torch from utils import to_var from tqdm import tqdm from math import isnan import numpy as np class SolverConvScoreSSREM(SolverConvScore): def __init__(self, config, train_data_loader, eval_data_loader, is_train=True, model=None): super(SolverConvScore...
import numpy as np import cv2 as cv def cv_imshow(title='Res',img=None): print(img.shape) cv.imshow(title,img) cv.waitKey(0) cv.destroyAllWindows() def image_normalization(img, img_min=0, img_max=255): """This is a typical image normalization function where the minimum and maximum of the imag...
# Lint as: python3 # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
#!/usr/bin/env python from __future__ import print_function import math import rospy from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry from b2_logic.nodes.pilot import PilotNode, PVelocityController from b2.msg import Proximity DEFAULT_NODE_NAME = "pilot_node" # Subscribes DEFAULT_PROXIMITY_TOP...
from aws_cdk import ( aws_s3 as s3, core ) class CdkExampleS3Stack(core.Stack): def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) bucket = s3.Bucket( self, "mytestbucket", bucket_name="m...
""" opencadd.io.core Defines the base class for the io module. """ from pathlib import Path class _Base: """ Base class for io classes. """ def __init__(self): """ This class contains no __init__ initialization. """ raise RuntimeError("This class only support initia...
from django.test import TestCase from django.template import Template, Context class TemplateTagTest(TestCase): def setUp(self): pass def test_tag(self): content = ( "{% load logical_rules_tags %}" "This is a {% testrule test_is_pizza 'pizza' %}test{% e...
#!/usr/bin/env python # -*- coding: utf-8 -* import urllib2 import urllib import cookielib import re from config import WEIBO_ACCOUNT, WEIBO_PWD class Fetcher(object): def __init__(self, username=None, pwd=None, cookie_filename=None): self.cj = cookielib.LWPCookieJar() if cookie_filename is not ...
""" Pop does not care what it is removing in case of set Since set is an unordered collection """ from prescription_data import patients trial_patients = {'Denise', 'Eddie', 'Frank', 'Georgia', 'Kenny'} while trial_patients: patient = trial_patients.pop() print(patient, end=':') prescription = patients[pa...
# Copyright 2016-2017 SAP SE # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import argparse import pymongo import uuid import datetime import pprint import copy from datetime import timedelta from starflyer import ScriptBase from camper.app import markdownify from logbook import Logger log = Logger('Migration') def daterange(start_date, end_date): for n in range(int ((end_date - start_d...
import json from datetime import datetime import time import PySimpleGUI as sg import os import keyring # for password storage import hashlib # import all the custom functions from functionalities import * # import all the window formats from windows import * if __name__ == "__main__" : # check if...
#To test how fast rotations.py is from rotations import * import numpy as np from timeit import default_timer as timer ranx5 = np.random.randint(10,size=(100000,3)) ranx6 = np.random.randint(10,size=(1000000,3)) ranx7 = np.random.randint(10,size=(10000000,3)) ranx8 = np.random.randint(10,size=(100000000,3)) start = t...
from os import getenv, getppid, kill, system from configparser import ConfigParser from typing import Union, Optional from psutil import process_iter from datetime import datetime from subprocess import Popen from signal import SIGHUP from pathlib import Path from sys import platform from re import match from typer im...
import stanza from stanza.protobuf import DependencyEnhancerRequest, Document, Language from stanza.server.java_protobuf_requests import send_request, add_sentence, JavaProtobufContext ENHANCER_JAVA = "edu.stanford.nlp.trees.ud.ProcessUniversalEnhancerRequest" def build_enhancer_request(doc, language, pronouns_patt...
from .pygbe import *
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities __...
import carla from leaderboard.envs.map_utils import * def viz(args): client = carla.Client('localhost', 2000) client.set_timeout(10.0) world = client.load_world(args.town_name) carla_map = world.get_map() spawn_points = carla_map.get_spawn_points() blueprint_library = world.get_bluepri...
import os import os.path as path import shutil import unittest from cache import Cache, format_as_timestamp from pathlib import Path from datetime import datetime, timedelta test_folder = 'test-files' db_file_name = path.join(test_folder, 'test.db') table_name = 'cache' folder_path = path.join(test_folder...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('api', '0...
import time import torch import numpy as np import pandas as pd import scipy from h5py import File import itertools, random from tqdm import tqdm from loguru import logger import torch.utils.data as tdata from typing import List, Dict class TrainHDF5Dataset(tdata.Dataset): """ HDF5 dataset indexed by a labels...
import utils.train as train class DataSet: def __init__(self, config, problem): self.config = config self. problem = problem self.update() def update(self): if not self.config.test: y_, x_, y_val_, x_val_ = ( train.setup_input_sc( ...
import json from pathlib import Path from typing import Dict import pandas as pd import sha_calc as sha_calc from gmhazard_calc.im import IM from gmhazard_calc import gm_data class BranchUniGCIM(sha_calc.UniIMiDist, sha_calc.CondIMjDist): """Represents the GCIM for a specific IMi and branch Parameters: ...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.ads.google_ads.v4.proto.resources import campaign_bid_modifier_pb2 as google_dot_ads_dot_googleads__v4_dot_proto_dot_resources_dot_campaign__bid__modifier__pb2 from google.ads.google_ads.v4.proto.services import campaign_bid_...
import os import matplotlib.pyplot as plt import matplotlib.pylab as pylab import time from subprocess import Popen, PIPE import numpy as np import pickle N = 20 def fail_if_error(error): if error: print(error) raise AssertionError() def remove_min_max(x): trimmed = x[:] trimmed.remove(ma...
from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from .validators import validate_file_size # Create your models here. #this models.py file means realtional table or schema in the databse and title, content etc are fields in the...
import pathlib from typing import Callable, Union import click __version__ = "21.5.16" APP_NAME = "cldb" app_dir = pathlib.Path(click.get_app_dir(APP_NAME, roaming=False, force_posix=True)) cache_root = app_dir / "cache" config = { "bs_features": "lxml", } from . import models # noqa: E402 SpecFetcher = Cal...
#!/usr/bin/env python # Copyright 2016 DIANA-HEP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
import time from environment_server.actor_data import ActorData import traceback def replay_buffer_process(params, batch_sizes, batch_addresses, transition_queue, replay_lock): try: from replay_buffer import replay_client import random batch_data = [ActorData(params, b, a) for b, a in zip(...
# (C) Copyright 2007-2021 Enthought, Inc., Austin, TX # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in LICENSE.txt and may be redistributed only under # the conditions described in the aforementioned license. The license # is also available online at...
# Models import tensorflow as tf import numpy as np from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2_as_graph import time import pickle import os import sklearn from sklearn.ensemble import RandomForestRegressor os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import warnings war...
import networkx as nx import numpy as np import matplotlib.pyplot as plt n = {'nodes':20,'edges':3} G = nx.barabasi_albert_graph(n['nodes'],n['edges']) max_degree = max(nx.degree(G).values()) min_sigmoid = 0.5 max_sigmoid = np.exp(1)/(1.+np.exp(1)) degrees = nx.degree(G) sigmoid = lambda value: (1./(1+np.exp(-valu...
#!/usr/bin/python2 import optparse import os import shutil import stat import subprocess import sys from builds.GpBuild import GpBuild def install_gpdb(dependency_name): status = subprocess.call("mkdir -p /usr/local/gpdb", shell=True) if status: return status status = subprocess.call( "ta...
''' Pulls segmentation masks from the database and exports them into folders with specifiable format (JPEG, TIFF, etc.). 2019 Benjamin Kellenberger ''' import os import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='Export segmentation map annotations from databa...
# -*- coding: utf-8 -*- from django.contrib.auth.models import User from django.urls import reverse from django.test import TestCase, Client import base64 import mock import adal class AuthTestCase(TestCase): client = Client() home_url = reverse('home') auth_url = reverse('auth') auth_ip_url = reverse...
from tempfile import NamedTemporaryFile from ..cache import get_cache_key, get_hexdigest, get_hashed_mtime from ..utils import compile_less from ..settings import LESS_EXECUTABLE, LESS_USE_CACHE,\ LESS_CACHE_TIMEOUT, LESS_ROOT, LESS_OUTPUT_DIR, LESS_DEVMODE,\ LESS_DEVMODE_WATCH_DIRS from django.conf import sett...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="deepof", version="0.1.4", author="Lucas Miranda", author_email="lucas_miranda@psych.mpg.de", description="deepof (Deep Open Field): Open Field animal pose classification tool ", long_d...
import pygame pygame.font.init() class Font(): title = pygame.font.SysFont('Arial', 60) place = pygame.font.SysFont('Arial', 32) normal_text_large = pygame.font.SysFont('Arial', 32) normal_text_small = pygame.font.SysFont('Arial', 24) card_energy = pygame.font.SysFont('Arial', 28) card_name = ...
#!/usr/bin/env python # # file: Connection.py # author: Cyrus Harrison <cyrush@llnl.gov> # created: 6/1/2010 # purpose: # Provides a 'Connection' class that interacts with a redmine instance to # extract results from redmine queries. # import urllib2,urllib,csv,getpass,warnings from collections import namedtuple fr...
# -*- coding: utf-8 -*- """ Created on Thu Mar 2 17:33:00 2017 @author: spauliuk """ """ File ODYM_Functions Check https://github.com/IndEcol/ODYM for latest version. Contains class definitions for ODYM standard abbreviation: msf (material-system-functions) dependencies: numpy >= 1.9 scipy >= 0.14 Reposi...
import inspect class ExecutionOrder(): """An Enum that is used to designate whether a TestSet's tests need to be run sequentially or can be run in any order.""" UNORDERED = 0 SEQUENTIAL = 1 class TestSet(): """A very general class that represents an arbitrary set of tests. By default each tes...
from . import EncodedNumber from . import RandomizedIterativeAffine from phe import paillier
""" data generator class """ import os import numpy as np import cv2 import copy from LibMccnn.util import readPfm import random from tensorflow import expand_dims #import matplotlib.pyplot as plt from skimage.feature import local_binary_pattern class ImageDataGenerator: """ input image patch pairs gen...
import pytest xgcm = pytest.importorskip("xgcm") from xarrayutils.build_grids import rebuild_grid from numpy.testing import assert_allclose from .datasets import datagrid_dimtest, datagrid_dimtest_ll @pytest.mark.parametrize( "test_coord", ["i", "j", "i_g", "j_g", "XC", "XG", "YC", "YG", "dxC", "dxG", "dyC",...
#!/usr/bin/env python from mailanalyzer import statistics from mailanalyzer import parsing from collections import defaultdict import datetime import csv import time # path to directory with Dovecot mailing list archive dir_name = '' # output path output = 'output/dovecot/{}_'.format(time.strftime('%Y%m%d_%H%M')) # ...
# -*- coding: utf-8 -*- """ Train a simple deep ResNet on the UPavia 2D dataset. Exception: Only layers of same output shape can be merged using sum mode. Layer shapes: [(None, 7, 7, 128), (None, 4, 4, 128)] """ from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.uti...
import numpy as np from datetime import datetime from twisted.internet.defer import inlineCallbacks from EGGS_labrad.lib.clients.cryovac_clients.RGA_gui import RGA_gui class RGA_client(RGA_gui): name = 'RGA Client' BUFFERID = 289961 def __init__(self, reactor, cxn=None, parent=None): super().__...
import glob import os import getpass print(" ------------------------\n| Piggy's Trolling Tools: |\n| :-: File Deleter :-: |\n ------------------------\n") where = input("Input directory where files should be deleted: ") regex = input("Enter regex to match files (example: important*.txt): ") os.chdir(whe...
""" Basic atmosphere functions This dark flight model predicts the landing sight of a meteoroid by propagating the position and velocity through the atmosphere using a 5th-order adaptive step size integrator (ODE45). Created on Mon Oct 17 10:59:00 2016 @author: Trent Jansen-Sturgeon """ import numpy as np from scipy.i...
#!/usr/bin/env python # -*- coding: utf-8 -*- import _env # noqa from controller._base import AdminHandler from misc._route import route @route('/category') class Index(AdminHandler): def get(self): self.render()
# -*- coding: utf-8 -*- from pydantic.datetime_parse import parse_datetime from .. import fhirtypes # noqa: F401 from .. import communication def test_Communication_1(base_settings): filename = ( base_settings["unittest_data_dir"] / "communication-example.canonical.json" ) inst = communication.C...
import argparse import os from util import util import torch import models import numpy as np class BaseOptions(): """This class defines options used during both training and test time. It also implements several helper functions such as parsing, printing, and saving the options. It also gath...
def qsort(arr): if len(arr) <= 1: return arr pivot = arr.pop() greater, lesser = [], [] for item in arr: if item > pivot: greater.append(item) else: lesser.append(item) return qsort(lesser) + [pivot] + qsort(greater)
from .MyMplCanvas import * from .MyMplCanvas import MyMplCanvas from .DataCanvas import * from .FitCanvas import * from .KineticsCanvas import * from .SpectrumCanvas import *
import pytest import pathlib from align.cell_fabric import Canvas, Pdk, Wire, Via mydir = pathlib.Path(__file__).resolve().parent pdkfile = mydir.parent.parent / 'pdks' / 'FinFET14nm_Mock_PDK' / 'layers.json' @pytest.fixture def setup(): p = Pdk().load(pdkfile) c = Canvas(p) c.addGen( Wire( nm='m1', laye...
from babelsubs.generators.base import register, BaseGenerator class DFXPGenerator(BaseGenerator): """ Since the internal storage is already in dfxp, the generator is just a small shim to keep the public interface between all generators regular. """ file_type = ['dfxp', 'xml' ] def __init_...
from ..iorw import GCSHandler class MockGCSFileSystem(object): def __init__(self): self._file = MockGCSFile() def open(self, *args, **kwargs): return self._file def ls(self, *args, **kwargs): return [] class MockGCSFile(object): def __enter__(self): self._value = 'd...
import boto3 exceptions = boto3.client('sdb').exceptions AttributeDoesNotExist = exceptions.AttributeDoesNotExist DuplicateItemName = exceptions.DuplicateItemName InvalidNextToken = exceptions.InvalidNextToken InvalidNumberPredicates = exceptions.InvalidNumberPredicates InvalidNumberValueTests = exceptions.InvalidNum...
import re from basic import * from amino_acids import amino_acids from tcr_distances_blosum import blosum from paths import path_to_db from translation import get_translation gap_character = '.' verbose = False #verbose = ( __name__ == '__main__' ) ## look at imgt cdrs ## http://www.imgt.org/IMGTScientificChart/Nome...
token = 'NDY2ODc4MzY3MTg3MDc1MDcz.DiqkoA.JVgJqYhnL6yyCnKeAnCHx5OvR3E' #Put Your bots token here prefix = '*' #put prefix here link = 'https://discordapp.com/api/oauth2/authorize?client_id=466878367187075073&permissions=0&scope=bot' #put bot invite link here ownerid = '329526048553172992' #put your id here
import numpy as np import torch from torch.utils import data from kaldi_io import read_mat import h5py # PyTorch Dataset class SpoofDatsetEval(data.Dataset): ''' Evaluation, no label ''' def __init__(self, scp_file): with open(scp_file) as f: temp = f.readlines() content = [x....
# lets create a class to hold our category data class Category: def __init__(self, name): self.name = name def __str__(self): return f"No Products in {self.name}" #How can you represent this class data as a string? My guess is __str__
import ConfigParser import os from StringIO import StringIO homedir = os.getenv('APPDATA' if os.name.lower() == 'nt' else 'HOME', None) default_cfg = StringIO(""" [visual] background = black foreground = white height = 800 width = 800 cortex = classic default_view = lateral [overlay] min_thresh = 2.0 max_thresh = rob...
import matplotlib.pyplot as plt import numpy as np def plot_bar_from_counter(counter, ax=None): """" This function creates a bar plot from a counter. :param counter: This is a counter object, a dictionary with the item as the key and the frequency as the value :param ax: an axis of matplotlib ...
from django import forms class LoginCustomerForm(forms.Form): email_address = forms.CharField(label='Email address', max_length=100) password = forms.CharField(label='Password', max_length=100, widget=forms.PasswordInput) class RegisterCustomerForm(forms.Form): first_name = forms.CharField(label='First na...
import datetime import textwrap import uuid from app_ccf.models import Application, StatusUpdate from app_ccf.models import VoucherCode, VoucherCodeBatch, VoucherCodeCheckStatus from shared.test_utils import DEFAULT_CCF_APP_FIELDS from . import base_test from . import utils class ApplicationTests(base_test.CcfBase...
# coding: utf-8 from binance_api.servicebase import ServiceBase import json from binance.client import Client from binance.exceptions import BinanceAPIException class Order(ServiceBase): def _get_filter(self, symbol, filter_name): if symbol is None: return None exinfo = self.binance.exchange_info ...
# Copyright 2019 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
# -*- coding: utf-8 -*- import logging from datetime import datetime, timedelta from dateutil import tz from django.conf import settings from django.contrib.auth.models import Group from django.contrib.auth import authenticate from django.db.models import Q, Prefetch, Sum from django.utils.translation import ugettext_l...
# Copyright (c) 2010 ActiveState Software Inc. All rights reserved. """Textual UI: progress bar and colprint""" import os import sys from datetime import datetime, timedelta from contextlib import contextmanager import logging import math import six LOG = logging.getLogger(__name__) __all__ = ['colprint', 'find_co...
import tensorflow as tf import numpy as np def reset_graph(seed=42): tf.reset_default_graph() tf.set_random_seed(seed) np.random.seed(seed) def neuron_layer(X, n_neurons, name, activation=None): with tf.name_scope(name): n_inputs = int(X.get_shape()[1]) stddev = 2/ np.sqrt(n_inputs) ...
import datetime import typing import uuid from commercetools import types from commercetools._schemas._api_client import ( ApiClientDraftSchema, ApiClientPagedQueryResponseSchema, ApiClientSchema, ) from commercetools.testing.abstract import BaseModel, ServiceBackend class ApiClientsModel(BaseModel): ...
import os import pandas as pd def test_wildcard_filter(): from pachypy.utils import wildcard_filter, wildcard_match x = ['a', 'ab', 'b'] assert wildcard_match('', None) is True assert wildcard_match('', '*') is True assert wildcard_match('', '?') is False assert wildcard_match('a', '*') is Tr...
import pytest def test_rnaseq_expression_init(): from genomic_data_service.rnaseq.domain.expression import Expression data = [ 'POMC', 'ENST000, ENST001', 0.03, 90.1, ] expression = Expression( *data ) assert isinstance(expression, Expression) assert...
import sys, os import pandas as pd import numpy as np file_path = os.path.dirname(os.path.realpath(__file__)) ps_calcs_lib_path = os.path.abspath(os.path.join(file_path, "../../", "lib/ps_calcs")) sys.path.insert(0, ps_calcs_lib_path) import ps_calcs def rdo(ybi, yi, year, depths): rca_dist_opp = [] for ...