text
stringlengths
1
927k
from tree import Node, BinaryTree from tree import BinarySearchTree import pytest # 5 tests passing -- CC#16 >>>> # 1. happy path # @pytest.mark.skip("pending") def test_happy_path_max(create_int_tree): tree = create_int_tree actual = tree.find_maximum_value(tree.root) expected = 15 assert actual == ...
from torchflare.batch_mixers.mixers import cutmix, mixup, get_collate_fn import torch x = torch.randn(4, 3, 256, 256) targets = torch.tensor([0, 1, 0, 1]) ds = torch.utils.data.TensorDataset(x, targets) def test_mixup(): dl = torch.utils.data.DataLoader(ds, batch_size=2) batch = next(iter(dl)) op, y = ...
import os import pickle import time _KEEPTIME = 300 # 5 minutes class CacheItem(object): def __init__(self, etag, content, cached_at): self.etag = etag self.content = content self.cached_at = cached_at class URLCache(object): """ URLCache is a simple pickle cache, intended ...
# Copyright 2020 The TensorFlow 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 applica...
from conans.model.options import Options, PackageOptions, OptionsValues from conans.model.requires import Requirements from conans.model.build_info import DepsCppInfo from conans import tools # @UnusedImport KEEP THIS! Needed for pyinstaller to copy to exe. from conans.errors import ConanException from conans.model.en...
from topicblob import TopicBlob text1 = "The titular threat of The Blob has always struck me as the ultimate moviemonster: an insatiably hungry, amoeba-like mass able to penetrate virtually any safeguard, capable of as a doomed doctor chillingly describes it assimilating flesh on contact. Snide comparisons to gelatin...
# Web Development from flask import Flask, render_template, request, redirect, url_for, flash # Login Manager from flask_login import LoginManager, login_user, logout_user, login_required, current_user from werkzeug.security import generate_password_hash, check_password_hash # Forms from forms import LoginForm, Registe...
""" Handlers for predicates related to set membership: integer, rational, etc. """ from __future__ import print_function, division from sympy.assumptions import Q, ask from sympy.assumptions.handlers import CommonHandler, test_closed_group from sympy.core.numbers import pi from sympy.core.logic import fuzzy_bool from ...
from django.urls import path from . import views urlpatterns = [ path("signup/", views.SignUpView.as_view(), name="signup"), ]
from pathlib import Path from lxml import etree import wx from rapidmaps.map.shape import Shape, ImageShape class ShapeExistException(Exception): pass class ShapeNotExistException(Exception): pass class ShapeParameter(object): pass class ShapeCreator(object): def __init__(self, param: ShapePar...
import argparse from defusedxml.ElementTree import parse from automaton.builder.common import allow_local_module_if_requested from automaton.builder.XmlBuilder import AutomatonXmlBuilder from automaton.runner.Runner import Runner from automaton.runner.ErrorHandler import ErrorHandlerXmlBuilder from automaton.runner.A...
import sys import os from loguru import logger from ..vars import BASE_DIR, LOGGING_FILE ROTATION = "10 MB" class Logger(object): def __init__(self): self.logger = logger self.logger.remove() self._console = None self._file = None self._log_to_file() self._log_to_...
# -*- coding: utf-8 -*- from django.db.models import F from django.db.models.expressions import BaseExpression from djmoney.money import Money from moneyed import Money as OldMoney MONEY_CLASSES = (Money, OldMoney) def get_currency_field_name(name): return '%s_currency' % name def get_amount(value): """ ...
from io import BytesIO from tds.base import StreamSerializer class ALTRowStream(StreamSerializer): TOKEN_TYPE = 0xD3 def unmarshal(self, buf): """ :param BytesIO buf: :rtype: bool """
# Copyright 2018 Google LLC # # 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, s...
from simp_py import tft lcd = tft.tft lcd.clear() from machine import Pin btnA = Pin(39, Pin.IN) while True: if btnA.value() == 0: lcd.text(10,10,'A is pressed ') else: lcd.text(10,10,'A is released') time.sleep(0.1)
#!/usr/bin/env python # Copyright (c) 2007, 2008 Rocco Rutte <pdmef@gmx.net> and others. # License: MIT <http://www.opensource.org/licenses/mit-license.php> from mercurial import node from hg2git import setup_repo,fixup_user,get_branch,get_changeset from hg2git import load_cache,save_cache,get_git_sha1,set_default_br...
import maskgen.video_tools """ Save Audio channels to a WAV file """ def transform(img, source, target, **kwargs): maskgen.video_tools.toAudio(source, outputName=target) return None, None def operation(): return {'name': 'OutputWAV', 'category': 'Output', 'description': 'Extract...
version_info = (0, 35, 2) __version__ = '.'.join(map(str, version_info)) try: import pyuv_cffi # only to compile the shared library before monkey-patching from . import greenpool from . import queue from .hubs.switch import gyield, trampoline from .greenthread import sleep, spawn, spawn_n, spawn_...
#!/usr/bin/env python """ Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): def __init__(self): GenericSyntax.__init__(self) @staticmethod de...
# -*- coding: utf-8 -*- """ Dummy conftest.py for lilo_scraper. If you don't know what this is for, just leave it empty. Read more about conftest.py under: https://pytest.org/latest/plugins.html """ # import pytest
from __future__ import absolute_import import json from createsend.createsend import CreateSendBase from createsend.utils import json_to_py class Segment(CreateSendBase): """Represents a subscriber list segment and associated functionality.""" def __init__(self, auth=None, segment_id=None): self.se...
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/45_collab.ipynb (unless otherwise specified). from __future__ import annotations __all__ = ['TabularCollab', 'CollabDataLoaders', 'EmbeddingDotBias', 'EmbeddingNN', 'collab_learner'] # Cell #nbdev_comment from __future__ import annotations from .tabular.all import * ...
import numpy as np from mpl_toolkits.basemap import pyproj from datetime import datetime try: import netCDF4 as netCDF except: import netCDF3 as netCDF def make_remap_grid_file(grd): #create remap file remap_filename = 'remap_grid_' + grd.name + '_t.nc' nc = netCDF.Dataset(remap_filename, 'w', format...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. r""" Basic training script for PyTorch """ # Set up custom environment before nearly anything else is imported # NOTE: this should be the first import (no not reorder) from fcos_core.utils.env import setup_environment # noqa F401 isort:skip impo...
#!/usr/bin/python import sys, getopt from impacket.dcerpc.v5 import transport from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_NONE from impacket.dcerpc.v5.dcomrt import IObjectExporter def main(argv): try: opts, args = getopt.getopt(argv,"ht:",["target="]) except getopt.GetoptError: p...
"""Module that provides magnetic vector potentials.""" import numpy def constant_field(X, B): """Converts a spatially constant magnetic field B at X into a corresponding potential. """ # This is one particular choice that works. return 0.5 * numpy.cross(B, X) def magnetic_dipole(x, x0, m): "...
from abc import ABCMeta, abstractmethod __author__ = "Vincent Levorato" __credits__ = "https://github.com/octo-technology/bdacore" __license__ = "Apache 2.0" class KerasFactory: """ Abstract class template for all keras neural nets factories """ __metaclass__ = ABCMeta @abstractmethod def cr...
"""Support for KNX/IP sensors.""" from __future__ import annotations from typing import Any, Callable, Iterable from xknx.devices import Sensor as XknxSensor from homeassistant.components.sensor import DEVICE_CLASSES, SensorEntity from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import ...
# Copyright (c) OpenMMLab. All rights reserved. from .builder import build_linear_layer, build_transformer from .conv_upsample import ConvUpsample from .csp_layer import CSPLayer from .gaussian_target import gaussian_radius, gen_gaussian_target from .inverted_residual import InvertedResidual from .make_divisible import...
import os from abc import ABCMeta from munch import Munch DIFFLR_MODULE_PATH = os.path.dirname(os.path.abspath(__file__)) DIFFLR_DATA_PATH = os.path.dirname(os.path.abspath(__file__)) + '/data/' DIFFLR_EXPERIMENTS_PATH = os.path.dirname(os.path.abspath(__file__)) + '/experiments/' DIFFLR_EXPERIMENTS_RUNS_PATH = os.pat...
# Tic Tac Toe game with GUI # using tkinter # importing all necessary libraries import random import tkinter from tkinter import * from functools import partial from tkinter import messagebox from copy import deepcopy # sign variable to decide the turn of which player sign = 0 # Creates an empty board global board b...
from frappe import _ def get_data(): return [ { "module_name": "Nano", "color": "grey", "icon": "octicon octicon-file-directory", "type": "module", "label": _("Nano") } ]
from .. import models, schemas, oauth2 from sqlalchemy.orm import Session from fastapi import status, HTTPException, Depends, APIRouter from ..database import get_db router = APIRouter(prefix = "/votes" ,tags = ["Votes"]) @router.post("/", status_code = status.HTTP_201_CREATED) def vote(vote : schemas.VoteData, db : ...
import torch, numpy as np, scipy.sparse as sp from torch.nn import functional as F from tqdm import tqdm def adjacency(H): """ construct adjacency for recursive hypergraph arguments: H: recursive hypergraph """ A = np.eye(H['n']) E = H['D0'] for k in tqdm(E): e = list(E[k...
import socket import threading # Connection Data host = '127.0.0.1' port = 3415 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((host, port)) server.listen() clients = [] nicknames = [] def broadcast(message): for client in clients: client.send(message) def handle(client): ...
import cv2 lena = cv2.imread(r"..\lena.jpg") cv2.imshow("cat1", lena) b = lena[:, :, 0] g = lena[:, :, 1] r = lena[:, :, 2] cv2.imshow("b", b) cv2.imshow("g", g) cv2.imshow("r", r) lena[:, :, 0] = 0 cv2.imshow("catb0", lena) lena[:, :, 1] = 0 cv2.imshow("catb0g0", lena) cv2.waitKey() cv2.destroyAllWindows()
""" Gripper for Franka's Panda (has two fingers). """ import numpy as np from robosuite.utils.mjcf_utils import xml_path_completion from robosuite.models.grippers.gripper import Gripper class PandaGripperBase(Gripper): """ Gripper for Franka's Panda (has two fingers). """ def __init__(self, path=None...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from parlai.agents.bert_ranker.bert_dictionary import BertDictionaryAgent from parlai.agents.bert_ranker.helpers import B...
#! /usr/bin/env python import argparse import os import numpy as np import json from voc import parse_voc_annotation from yolo import create_yolov3_model, dummy_loss from generator import BatchGenerator from utils.utils import normalize, evaluate, makedirs from keras.callbacks import EarlyStopping, ReduceLROnPlateau f...
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Download files from Google Storage based on SHA1 sums.""" import hashlib import optparse import os import Queue import re impo...
my_contacts = ["Ankita", "Bhai"] # Note that the names you add here should match the format of your contact list in your whatsapp
# -*- coding: utf-8 -*- """ This is the canonical _config.py with all default settings. Individual sites have a _config.py which can override these settings. """ # site URL site.url = "http://www.yoursite.com" blog = controllers.blog blog.enabled = False # blog path relative to site URL blog.path = "/blog" blog...
''' INFO this class implements the scheduler Uses the AddressSpace for the movement of pages between NVM-DRAM. This class mainly classifies which pages should be moved takes as input: trafficGen , AddressSpace,policy, number of requests per interval ,and DRAM/NVM ratio) After running the scheduler we c...
from os.path import join, abspath from pygame.mixer import Sound def get_song(song: str) -> Sound: return Sound(get_path(song)) def get_path(name: str): return join(abspath(""), "source", "sounds", name)
"""This problem was asked by Google. Explain the difference between composition and inheritance. In which cases would you use each? """
import unittest import sys sys.path.append('..') import chocolatedistribution.getcuts class TestScoreMethod(unittest.TestCase): """Class with the unit tests. """ def test_given(self): chocolates = [2, 5, 7] children = [3, 2, 5, 1] cuts = chocolatedistribution.getcuts.giveChocolate(...
#coding:utf-8 # # id: bugs.core_5147 # title: create trigger fails with ambiguous field name between table B and table A error # decription: # tracker_id: CORE-5147 # min_versions: ['3.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action ...
import torch import numpy as np from mannequinchallenge.options.train_options import TrainOptions from mannequinchallenge.loaders import aligned_data_loader from mannequinchallenge.models import pix2pix_model model = None class DictX(dict): def __getattr__(self, key): try: return self[key] ...
#!/usr/bin/env python import pickle from collections import Counter import re import string import gensim, logging import multiprocessing logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) MODEL_PATH = 'songs.model' TRACKS_INFO_PATH = 'tracks-info.pickle' def main(): songs...
from typing import Union, Iterable import yaml from prefect.run_configs.base import RunConfig from prefect.utilities.filesystems import parse_path class ECSRun(RunConfig): """Configure a flow-run to run as an ECS Task. ECS Tasks are composed of task definitions and runtime parameters. Task definitions...
# Generated by Django 3.2.8 on 2021-11-11 15:06 import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_m...
#!/usr/bin/env python3 # Copyright (c) 2014-2019 The BitPal Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the rawtransaction RPCs. Test the following RPCs: - createrawtransaction - signrawtransactio...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2 from telethon.tl.types import ChannelParticipantsAdmins from darkbot.utils import admin_cmd, sudo_cmd, edit_or_reply from us...
from scipy.signal import spectrogram import numpy as np import matplotlib.pyplot as plt import torch import torchaudio from wettbewerb import load_references if __name__ == '__main__': ecg_leads = load_references("../data/training/")[0] for ecg_lead_ in ecg_leads: if ecg_lead_.shape[0] == 18000: ...
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # Name: reduction.py # Purpose: Tools for creating a score reduction. # # Authors: Christopher Ariza # Michael Scott Cuthbert # # Copyright: Copyright © 2011-2013 Michael Scott Cut...
"""CAN bus specific implementation of UDS packets.""" __all__ = ["CanPacket", "AnyCanPacket"] from typing import Optional, Any from warnings import warn from uds.utilities import Nibble, RawByte, RawBytes, RawBytesTuple, validate_raw_bytes, \ AmbiguityError, UnusedArgumentWarning from uds.transmission_attributes...
# coding: utf-8 """ N32 Handshake API N32-c Handshake Service. © 2020, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. # noqa: E501 The version of the OpenAPI document: 1.1.0.alpha-3 Generated by: https://openapi-generator.tech """ import pprint impo...
# -*- coding: utf-8 -*- import ldap import six from girder import events, logger from girder.api import access from girder.api.describe import autoDescribeRoute, Description from girder.api.rest import boundHandler from girder.exceptions import ValidationException from girder.models.setting import Setting from girder....
""" Free modules """ #***************************************************************************** # Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>, # 2007-2009 Nicolas M. Thiery <nthiery at users.sf.net> # 2010 Christian Stump <christian.stump@univie.ac.at> ...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # """ InferSent models. See https://github.com/facebookresearch/InferSent. """ from __future__ import absolute_import, division,...
from django.conf.urls import url import voxel_globe.task.views urlpatterns = [ url(r'^status/$', voxel_globe.task.views.status, name='status'), url(r'^revoke/$', voxel_globe.task.views.revoke, name='revoke'), url(r'^mark_as_read/$', voxel_globe.task.views.mark_as_read, name='mark_as_read') ]
import datetime import enum import flask_sqlalchemy as fsql import json import os import sqlite3 import typing import uuid import redis import redis_lock import sqlalchemy as sql import sqlalchemy.ext.declarative as sqldec import sqlalchemy.orm as sqlorm import app.common.utils as utils import app.common.firebase_not...
# -*- coding: utf-8 -*- """ Created on Fri Sep 29 11:11:23 2017 @author: tkoller """ import time import warnings import numpy as np from scipy.spatial.qhull import ConvexHull from . import utils_ellipsoid from .safempc_cem import MpcResult from .sampling_models import MonteCarloSafetyVerification from .utils import ...
import os import ptah import shutil import tempfile from pyramid.config import ConfigurationConflictError ptah.register_migration('ptah', 'ptah:tests/migrations') class TestRegisterMigration(ptah.PtahTestCase): _init_ptah = False _auto_commit = False def test_register(self): from ptah.migrate i...
# See LICENSE for licensing information. # # Copyright (c) 2016-2019 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # from signal_grid import signal_grid from grid_pa...
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # # License: BSD (3-clause) import os from ..bem import fit_sphere_to_headshape from ..io import read_raw_fif from ..utils import logger,...
from __future__ import print_function import json import os import subprocess import time import logging import uuid import shutil from multiprocessing import Process from wes_service.util import WESBackend logging.basicConfig(level=logging.INFO) class ToilWorkflow(object): def __init__(self, run_id): "...
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ...
''' Author Junbong Jang Date 9/2/2020 Contains debugging functions useful for deep learning research ''' import sys sys.path.append('..') sys.path.append('../data_handle') from UserParams import UserParams from data_processor import get_std_mean_from_images import math import os import cv2 import numpy as np import ...
print("telnet") import time import telnetlib __all__ = ["CiscoTelnet"] class CiscoTelnet: def __init__(self, ip, username, password, enable, disable_paging=True): self.telnet = telnetlib.Telnet(ip) self.telnet.read_until(b"Username:") self.telnet.write(username.encode("utf-8") + b"\n") ...
# Generated by Django 2.2.4 on 2019-09-03 00:19 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('laxy_backend', '0007_auto_20190805_0451'), ] operations = [ migrations.Alt...
# Copyright (c) 2020 Huawei Technologies Co., Ltd # Copyright (c) 2019, Facebook CORPORATION. # All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/lice...
''' Encapsulation : Part 1 Encapsulation is the process of restricting access to methods and variables in a class in order to prevent direct data modification so it prevents accidental data modification. Encapsulation basically allows the internal representation of an object to be hidden from the view o...
# coding=utf-8 from datetime import date import pytest from sqlalchemy.exc import IntegrityError import marcottievents.models.common.enums as enums import marcottievents.models.common.overview as mco import marcottievents.models.common.personnel as mcp def test_person_generic_insert(session, person_data): """Pe...
#!/usr/bin/python # -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # Copyright (c) 2021, One Identity LLC # File: ad_group_conflicts_filters.py # Desc: Ansible filters for ad_group_conflicts role # Auth: Laszlo Nagy # Note: # -------------------------------------...
# Copyright (c) 2018 PaddlePaddle 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 app...
import string from Bio import Alphabet, Seq from Bio.Alphabet import IUPAC class Transcribe: def __init__(self, dna_alphabet, rna_alphabet): self.dna_alphabet = dna_alphabet self.rna_alphabet = rna_alphabet def transcribe(self, dna): assert dna.alphabet == self.dna_alphabet, \...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
import fastestimator as fe import tensorflow as tf from fastestimator.op.numpyop.meta import Sometimes from fastestimator.op.numpyop.multivariate import HorizontalFlip, PadIfNeeded, RandomCrop from fastestimator.op.numpyop.univariate import CoarseDropout, Normalize from fastestimator.op.tensorop.loss import CrossEntrop...
def plot_history(hist): import matplotlib.pyplot as plt plt.figure() plt.xlabel('Epoch') plt.ylabel('Mean Squared Error') plt.plot(hist['epoch'], hist['mean_squared_error'], label='Train Error') plt.plot(hist['epoch'], hist['val_mean_squared_error'], label = 'Val Error') ...
# Write a program that prints a multiplication table. # Functions are for single unit tasks. Make a function for the printheader and the sequence(innerds of the table). def positiveinteger(N): try: posnum = int(N) except: raise ValueError('Not an integer.') if posnum <0: raise Value...
# -*- coding: utf-8 -*- # Copyright (C) 2012, Almar Klein # This code is subject to the (new) BSD license: # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the a...
import math import uuid from optur.proto.study_pb2 import ObjectiveValue, Target, Trial from optur.utils.sorted_trials import ( SortedTrials, TrialKeyGenerator, TrialQualityFilter, ) def test_trial_quality_filter_remove_unknown() -> None: assert not TrialQualityFilter(filter_unknown=True)(Trial(last_...
from abc import ABCMeta, abstractmethod class Serializable: """Interface for Serialization. """ __metaclass__ = ABCMeta @abstractmethod def read(self, in_stream: bytes): """Convert from bytes to Serializable Args: in_stream (bytes): Input of bytes to deserialize ...
import six import random from datetime import datetime from Crypto.Cipher import AES import json from binascii import unhexlify MODHEX_DICT = { "0": "c", "1": "b", "2": "d", "3": 'e', "4": 'f', "5": 'g', "6": 'h', "7": 'i', "8": 'j', "9": 'k', "a": 'l', "b": 'n', "c...
import unittest from pyinfrabox import ValidationError from pyinfrabox.infrabox import validate_json class TestDockerCompose(unittest.TestCase): def raises_expect(self, data, expected): try: validate_json(data) assert False except ValidationError as e: self.asse...
import boto3 from botocore.exceptions import ClientError import json import os import time import datetime from dateutil import tz from lib.account import * from lib.common import * import logging logger = logging.getLogger() logger.setLevel(logging.INFO) logging.getLogger('botocore').setLevel(logging.WARNING) loggi...
from typing import Callable, Tuple, Union import numpy as np from tqdm import tqdm from model.forcing import ( Forcing, StandardForcingGenerator, ForcingGenerator, PulseParameters, ) from model.pulse_shape import ( ShortPulseGenerator, ExponentialShortPulseGenerator, PulseGenerator, ) from ...
import datetime from decimal import Decimal from typing import Optional, NamedTuple from enum import Enum, unique @unique class Signal(Enum): UNKNOWN = 0 SELL = 1 UNDERPERFORM = 2 NEUTRAL = 3 HOLD = 4 OUTPERFORM = 5 BUY = 6 @classmethod def from_text(cls, value: str) -> Enum: ...
"""Core definitions of MPT framework""" class MptException(Exception): pass class BadCrcException(MptException): pass class CommandTooLongException(MptException): def __init__(self): MptException.__init__(self) self.message = "Command is limited to 253 bytes!" class NotConnectedExcep...
import pytest from pytest import ( raises, ) from vyper import ( compiler, ) from vyper.exceptions import ( FunctionDeclarationException, ) fail_list = [ """ @public def foo(max: int128) -> int128: return max """, """ @public def foo(len: int128, sha3: int128) -> int128: return len+sha...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """Tests for the flow database api.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import random import time from future.builtins import range from future.utils import iteritems import mock import queue ...
import os import matplotlib.pyplot as plt import open3d from utils import * def render_image_with_boxes(img, objects, calib): """ Show image with 3D boxes """ # projection matrix P_rect2cam2 = calib['P2'].reshape((3, 4)) img1 = np.copy(img) for obj in objects: if obj.type == 'Do...
import os import time import numpy as np import pickle import torch import torch.nn as nn from super_model import Network_ImageNet from torch.autograd import Variable from config import config import sys sys.setrecursionlimit(10000) import functools import copy print=functools.partial(print,flush=True) from angle impor...
#!/usr/bin/env python import json, os, uuid, requests, msal, atexit, blinkt, app_config from datetime import datetime, timedelta from flask import Flask, jsonify, make_response, Response, request, redirect, session, url_for, render_template from flask_apscheduler import APScheduler from pyngrok import ngrok ########...
"""Trainining script for WaveNet vocoder usage: train.py [options] options: --dump-root=<dir> Directory contains preprocessed features. --checkpoint-dir=<dir> Directory where to save model checkpoints [default: checkpoints]. --hparams=<parmas> Hyper parameters [default: ]. -...
""" Support for Melnor RainCloud sprinkler water timer. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.raincloud/ """ import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.componen...
#! /usr/bin/env python3 # # Given a Flywheel job id, this script will generate a local testing directory # within which you can run the job locally, using Docker, as it ran in Flywheel. # # This code generates a directory structure that mimics exactly what the Gear would # get when running in Flywheel. Importantly, thi...