content
stringlengths
5
1.05M
from qtpy import QtCore from qtpy import QtWidgets class ToolBar(QtWidgets.QToolBar): def __init__(self, title): super(ToolBar, self).__init__(title) layout = self.layout() m = (0, 0, 0, 0) layout.setSpacing(0) layout.setContentsMargins(*m) self.setContentsMargins(*...
# A001 test case - New user registration with user name, email and password # User login data should be provided in data/users.txt file. Arbitrary number of users can be tested. import data.data_tcA001 as da01 import func.func_01 as fu01 from selenium import webdriver from selenium.webdriver.common.by import By impo...
# Generated by Django 2.0 on 2018-01-12 12:21 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] opera...
import functools import inspect from operator import methodcaller import sys from contextlib import contextmanager from html import escape as escape_html from types import MappingProxyType as mappingproxy from math import ceil def exc_clear(): # exc_clear was removed in Python 3. The except statement automaticall...
from system import System_25D import os import util.fill_space import subprocess class PassiveInterposer(System_25D): """docstring for Passive""" def __init__(self): self.chiplet_count = 0 self.width = [None] * self.chiplet_count self.height = [None] * self.chiplet_count self.hubump = [None] * sel...
""" Experiment for NN4(RI) Aim: To find the best max_epochs for NN4(*, 1024, 1024, 1024) + RI(k = 3, m = 200) max_epochs: [22, 24, ... ,98, 140] Averaging 20 models Summary epochs 88 , loss 0.421860471364 Time:3:40:30 on i7-4790k 32G MEM GTX660 I got a different result, epochs 112 loss 0.422868, before I...
""" SECS utils """ import numpy as np d2r = np.pi/180 MU0 = 4 * np.pi * 1e-7 RE = 6371.2 * 1e3 def dpclip(x, delta = 1e-7): """ dot product clip: clip x to values between -1 + delta and 1 - delta """ return np.clip(x, -1 + delta, 1 - delta) def get_theta(lat, lon, lat_secs, lon_secs, return_d...
import itertools words = [] with open('words.italian.txt') as f: words = f.read().split('\n') def charCount(word): dict = {} for i in word: dict[i] = dict.get(i, 0) + 1 return dict def possible_words(lwords, charSet): l = [] for word in lwords: flag = 1 c...
from bs4 import BeautifulSoup as bs import pyperclip as pc import requests import re import search def t1337x_search(query): ''' Search for torrents and return results if find anything and print no result were found and start process again ''' url='https://1337x.to/search/'+query+'/1/' headers = ...
# -*- coding: utf-8 -*- """ Demonstrate use of GLLinePlotItem to draw cross-sections of a surface. """ ## Add path to library (just for examples; you do not need this) import initExample from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph.opengl as gl import pyqtgraph as pg import numpy as np app = ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from flask import Flask, request, render_template, Response from flask_restplus import Api, Resource, fields, reqparse, abort, fields, Model import logging import json import time from argparse import ArgumentParser from importlib ...
import os import sys sys.path.append(os.path.realpath(os.path.join(os.path.split(__file__)[0], '..', '..'))) import numpy as np def cents_repr(amout_in_cents, upper_case=True): if amout_in_cents < 100: res = f"{amout_in_cents} USD CENTS" else: res = f"{amout_in_cents/100} USD" if upper_cas...
from django.db import connection, transaction from django.db.models import get_model ProductRecord = get_model('analytics', 'ProductRecord') Product = get_model('catalogue', 'Product') class Calculator(object): # Map of field name to weight weights = {'num_views': 1, 'num_basket_additions': 3...
from resources import *
''' Created on Apr 19, 2016 @author: Rohan Achar ''' import json from time import sleep from pcc.recursive_dictionary import RecursiveDictionary from common.wire_formats import FORMATS from datamodel.all import DATAMODEL_TYPES from pcc.dataframe.dataframe_threading import dataframe_wrapper as dataframe from pcc.datafr...
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.13.7 # kernelspec: # display_name: Python [conda env:bandit_38] # language: python # name: conda-env-bandi...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyYtopt(PythonPackage): """Ytopt package implements search using Random Forest (SuRF), an ...
# Copyright 2018 Autodesk, Inc. All rights reserved. # # Use of this software is subject to the terms of the Autodesk license agreement # provided at the time of installation or download, or which otherwise accompanies # this software in either electronic or hard copy form. # from __future__ import print_function imp...
from typing import TYPE_CHECKING, Generator from .base import EXEC_NAMESPACE, EXPS_NAMESPACE, EXPS_STASH, ExpRefInfo if TYPE_CHECKING: from dvc.scm.git import Git def exp_refs(scm: "Git") -> Generator["ExpRefInfo", None, None]: """Iterate over all experiment refs.""" for ref in scm.iter_refs(base=EXPS_N...
import requests import json from time import sleep def main(): while True: search_user_name = input('What user do you want to search?\n > ') github = requests.get(f'https://api.github.com/users/{search_user_name}') response = json.loads(github.text) if 'message' in response: print('User not fo...
from django.contrib import admin from django.urls import path, include from webdev.home_view import home urlpatterns = [ path('admin/', admin.site.urls), path('', home), path('tarefas/', include('webdev.tarefas.urls')) ]
from django.contrib.auth.models import User from django.test import Client, TestCase from django.urls import reverse from apps.ldap.test_helpers import LDAPTestCase from .models import ( Officer, Officership, Person, Politburo, PolitburoMembership, Semester, ) from .staff_views import update_o...
import requests BASE_URL = 'https://covid-193.p.rapidapi.com/' ENDPOINT = 'history' API_KEY = '687dbfe6b7msh0e5814a43c930b7p11d7cdjsn493dc356cfb6' def history(day, country): params = { 'country': country, 'day': day } headers = { 'x-rapidapi-key': API_KEY, } response = re...
''' 2014314433 lee young suk ''' userinputa=input("Enter the first integer : ") userinputb=input("Enter the second integer : ") if int(userinputa)%2==0 and int(userinputb)%2==0: print("Both a and b are even numbers") elif int(userinputa)%2==0 or int(userinputb)%2==0: print("Either a or b is an even number") ...
import numpy import sys def in_fault_window(line): line = line.strip() timestamp = line.split()[1] time_segments = timestamp.split(':') hour = int(time_segments[0]) minute = int(time_segments[1]) return hour % 3 == 0 and minute >= 30 and minute <= 45 def print_summary(data): print 'Data po...
# -*- coding: utf-8 -*- from math import atan2, degrees from ..Qt import QtCore, QtGui from ..Point import Point from .. import functions as fn from .GraphicsObject import GraphicsObject __all__ = ['TextItem'] class TextItem(GraphicsObject): """ GraphicsItem displaying unscaled text (the text will always appe...
"""Test config flow.""" from unittest.mock import patch from aiomusiccast import MusicCastConnectionException import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components import ssdp from homeassistant.components.yamaha_musiccast.const import DOMAIN from homeassistant.config_...
"""Alarm App.""" import json from pathlib import Path import dash_auth import dash_bootstrap_components as dbc import dash_html_components as html from dash_charts.utils_app import AppBase from dash_charts.utils_fig import map_args, map_outputs class AppAlarm(AppBase): """PiAlarm UI.""" name = 'PiAlarm' ...
#!/usr/bin/sudo python from scapy.all import * from scapy.layers.inet import TCP, IP from filter import TrafficFilter, CallBackFilter src = '192.168.1.63' dst = '192.168.1.94' verbose = True def log(data: str): if verbose: print(data) def throttle_data_from_destination(pkt: Packet): ip, tcp = pk...
#!/usr/bin/env python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ---------------------------------------------...
#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 import sys import django django.setup() # pylint: disable=wrong-import-position import cavedb.utils from cavedb.generate_docs import write_global_bulletin_files from cavedb.generate_docs import write_bulletin_files from cavedb.generate_docs import run_bui...
import parsy def between(p_open, p_close, p): """ -- | @'between' open close p@ parses @open@, followed by @p@ and @close@. -- Returns the value returned by @p@. -- -- > braces = between (symbol "{") (symbol "}") between_brackets = partial(between, symbol("["), symbol("]")) """ return...
import numpy from stl import mesh # find the max dimensions, so we can know the bounding box, getting the height, # width, length (because these are the step size)... def find_mins_maxs(obj): minx = obj.x.min() maxx = obj.x.max() miny = obj.y.min() maxy = obj.y.max() minz = obj.z.min() ...
# 입력 n = int(input()) # 브루트포스 cnt = 0 # 박수 친 횟수 for num in range(1, n+1): for i in str(num): if i == '3' or i == '6' or i == '9': cnt += 1 print(cnt)
# -*- test-case-name: axiom.test.test_scheduler -*- import warnings from zope.interface import implements from twisted.internet import reactor from twisted.application.service import IService, Service from twisted.python import log, failure from epsilon.extime import Time from axiom.iaxiom import IScheduler from ...
import math def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('Bad operand type') if x >= 0: return x else: return -x def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny n = my_abs(-20) print(n...
import tensorflow as tf def smooth_l1_loss(bbox_prediction, bbox_target, sigma=3.0): """ Return Smooth L1 Loss for bounding box prediction. Args: bbox_prediction: shape (1, H, W, num_anchors * 4) bbox_target: shape (1, H, W, num_anchors * 4) Smooth L1 loss is defined as: 0....
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'regenerateaddresses.ui' # # Created: Sun Sep 15 23:50:23 2013 # by: PyQt4 UI code generator 4.10.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 e...
#!/usr/bin/python3 import schedule class VKBot: def __init__(self): self.session = None def on_message(self, message, session) -> bool: ''' Do any needed actions on this message, possibly using the session object. If the session object is used, it is not cached. Return ...
import numpy as np import pandas as pd import torch import os import argparse from torch.utils.data import DataLoader, sampler, TensorDataset, ConcatDataset from attack_functions import * from trojai_utils import * from boundary_geometry import * parser = argparse.ArgumentParser(description="TrojAI Round 5 script for ...
# # Low-level object abstraction in cDatabase # import os import json import yaml from cdatabase.config import cfg from cdatabase.cdata import cData import cdatabase.utils as utils class cObject(object): ########################################################################### def __init__...
import matplotlib.pyplot as plt import numpy as np import pickle from collections import defaultdict from shapely.geometry import Point, Polygon # Init NuScenes. Requires the dataset to be stored on disk. from nuscenes.nuscenes import NuScenes from nuscenes.map_expansion.map_api import NuScenesMap nusc = NuScenes(ve...
from functools import wraps def if_arg(func): @wraps(func) def run_function_only_if_arg(*args): if args[0]: return func(*args) else: return { "valid": None, "value": None } return run_function_only_if_arg
""" Qscattering =========== """ # sphinx_gallery_thumbnail_path = '../images/Experiment_QextVSDiameter.png' def run(): import numpy as np from PyMieSim.Experiment import SphereSet, SourceSet, Setup scatSet = SphereSet( Diameter = np.linspace(100e-9, 10000e-9, 400), Index ...
from django.shortcuts import render from .models import Subscribe from .forms import NewsletterForm, SubscribeForm import sendmail from markdown import markdown from django.http import HttpResponseRedirect def newsletter(request): if request.user.is_authenticated(): form=NewsletterForm(request.POST, request.FILES) ...
# -*- python -*- load( "@drake//tools/workspace:execute.bzl", "execute_and_return", ) def setup_new_deb_archive(repo_ctx): """Behaves like new_deb_archive, except that (1) this is a macro instead of a rule and (2) this macro returns an error status instead of fail()ing. The return value is a struc...
from typing import Any, Dict, Sequence from coba.exceptions import CobaException from coba.utilities import PackageChecker from coba.environments import Context, Action from coba.pipes import Flatten from coba.encodings import InteractionsEncoder from coba.learners.primitives import Probs, Info, Learner class LinUCB...
#!/usr/bin/env python """ Classes: Game: The game object which holds utility methods for printing the game board, calculating winner, making moves AI: The AI player """ from random import randint from typing import List import argparse class Game(): """ Class for the game itself """ # ...
from dtech_instagram.InstagramAPI.src.http.Response.Objects.Location import Location from .Response import Response class LocationResponse(Response): def __init__(self, response): self.venues = None if self.STATUS_OK == response['status']: locations = [] for location in re...
import MonsterBuilder def create(lb,xpos): xml = """ <level> <!-- watchtower --> <sprite type = 'ZoomTrigger.ZoomTriggerSprite' x='0' y='250' width='100' height='500' zoom_fact='1.0'/> <sprite type = 'ZoomTrigger.ZoomTriggerSprite' x='165' y='260' width='128' height='100' zoom_fact='0.1666'/> <sprite type ...
# Note: Be sure to clean up output and dask work-space before running test import argparse import os import time import cudf from dask.distributed import Client, performance_report from dask_cuda import LocalCUDACluster from nvtabular import Dataset, Workflow from nvtabular import io as nvt_io from nvtabular import ...
# -*- coding: utf-8 -*- # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Kite install utilities test.""" # Local imports import os import re import sys # Third-party imports import pytest # Local imports from spyder.plugins.completion...
__author__ = 'asistente' from unittest import TestCase from selenium import webdriver from selenium.webdriver.common.by import By class FunctionalTest(TestCase): def setUp(self): self.browser = webdriver.Chrome() self.browser.implicitly_wait(2) def tearDown(self): self.browser.quit()...
# Generated by Django 2.0.2 on 2018-02-27 13:49 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Author', fields=[ ...
#pocket/__init__.py from flask import Flask app = Flask(__name__) import pocket.views
""" Copyright 2012-2019 Ministerie van Sociale Zaken en Werkgelegenheid 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...
from .. import ast from .base import BaseNodeTransformer from typing import List, Union def _find_bool(nodes: Union[List[ast.AST], List[ast.expr]]) -> bool: for node in nodes: if isinstance(node, ast.Name): if node.id == '__bool__': return True elif isinstance(node, ast....
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class BeltConfig(AppConfig): """Django Belt AppConfig.""" name = "belt" verbose_name = _("Belt")
import sys from textwrap import dedent import pytest from IPython.testing import globalipapp from julia import magic @pytest.fixture def julia_magics(julia): return magic.JuliaMagics(shell=globalipapp.get_ipython()) # fmt: off @pytest.fixture def run_cell(julia_magics): # a more convenient way to run st...
import numpy as np import sys import os stderr = sys.stderr sys.stderr = open(os.devnull, 'w') from tensorflow.python.keras.models import model_from_yaml sys.stderr = stderr # disable any warnings by TensorFlow. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' name = 'NeuralNet_TF_2L' # dir = '/Users/sangtruong_2021/Documen...
""" Python Flight Mechanics Engine (PyFME). Copyright (c) AeroPython Development Team. Distributed under the terms of the MIT License. Acceleration ------------ """ from abc import abstractmethod import numpy as np from pyfme.utils.coordinates import body2hor, hor2body class Acceleration: """Acceleration ...
from keras import Model from abc import ABCMeta, abstractclassmethod class Autoencoder(metaclass=ABCMeta): @abstractclassmethod def encoder(self) -> Model: raise NotImplementedError @abstractclassmethod def decoder(self) -> Model: raise NotImplementedError @abstractclassmethod ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** 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...
# -*- coding: utf-8 -*- """The BitLocker Drive Encryption (BDE) credentials.""" from __future__ import unicode_literals from dfvfs.credentials import credentials from dfvfs.credentials import manager from dfvfs.lib import definitions # TODO: add means to set the credentials in the bde_volume using the helper? cla...
#!/usr/bin/env python # Copyright (c) 2016, wradlib developers. # Distributed under the MIT License. See LICENSE.txt for more info. import unittest import numpy as np import wradlib.trafo as trafo class TransformationTest(unittest.TestCase): def setUp(self): self.rvp = np.array([0., 128., 255....
class DataProcJob(object): def __init__(self, client, project, region, response): self.client = client self.project = project self.region = region self.response = response @classmethod def from_id(cls, client, project, job_id, region="global"): return DataProcJob(cli...
market=list() def getLowestcap(): lowest=market[0][1] coin="" for item in market: if lowest>=item[1]: coin=item[0] index=0 for coinsss in market: if coinsss[0] == coin: market.pop(index) break else: ...
import base64 import sys import warnings from typing import ( AbstractSet, Any, Callable, Dict, List, Mapping, MutableSequence, Optional, Set, TYPE_CHECKING, Tuple, Type, Union, cast, ) try: import orjson as json except ImportError: # pragma: no cover im...
import unittest import torch from joeynmt.data import load_data from joeynmt.helpers import expand_reverse_index from joeynmt.model import build_model from joeynmt.prediction import parse_test_args, validate_on_data # TODO make sure rnn also returns the nbest list in the resorted order class TestHelpers(unittest.T...
from dbaas_zabbix.database_providers import DatabaseZabbixProvider class Host(object): def __init__(self, address, dns): self.address = address self.hostname = dns class Engine(object): def __init__(self, name, version='0.0.0'): self.engine_type = EngineType(name) self.versio...
import aioredis import asyncio import base64 import concurrent import json import logging import os import uvloop from aiohttp import web import kubernetes_asyncio as kube from prometheus_async.aio.web import server_stats # type: ignore from hailtop.config import get_deploy_config from hailtop.google_storage import G...
#!/usr/bin/python # -*- coding: utf-8 -*- # Hive Appier Framework # Copyright (c) 2008-2021 Hive Solutions Lda. # # This file is part of Hive Appier Framework. # # Hive Appier Framework is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by the Apach...
def dF(x, a, theta): """ Population activation function. Args: x : the population input a : the gain of the function theta : the threshold of the function Returns: dFdx : the population activation response F(x) for input x """ # Calculate the population activation dFdx = a * np...
import pyrealsense2 as rs width = 848 height = 480 fps = 30 config = rs.config() config.enable_stream(rs.stream.color, width, height, rs.format.bgr8, fps) config.enable_stream(rs.stream.depth, width, height, rs.format.z16, fps) # ストリーミング開始 pipeline = rs.pipeline() profile = pipeline.start(config) depth_intrinsics = ...
'''Implementation Vibrator for Android.''' from jnius import autoclass from plyer_lach.facades import Vibrator from plyer_lach.platforms.android import activity from plyer_lach.platforms.android import SDK_INT Context = autoclass('android.content.Context') vibrator = activity.getSystemService(Context.VIBRATOR_SERVICE...
import csv import sys import re if len(sys.argv) != 3: print("Usage: python dna.py data.csv sequence.txt") # Read DNA sequence with open(sys.argv[2], "r") as txt: dna = txt.read(-1) # Open CSV file with open(sys.argv[1], "r") as data: # Open CSV to get the key read = csv.DictReader(data) for row ...
"""Sweep tests""" import wandb def test_create_sweep(live_mock_server, test_settings): live_mock_server.set_ctx({"resume": True}) sweep_config = { "name": "My Sweep", "method": "grid", "parameters": {"parameter1": {"values": [1, 2, 3]}}, } sweep_id = wandb.sweep(sweep_config) ...
def setup(): size(500, 500) smooth() background(255) strokeWeight(30) noLoop() def draw(): stroke(20) i=0 while i < 7: i=i+1 line(i*50, 200, 150 + (i-1)*50, 300)
# Copyright (C) 2011 Google Inc. All rights reserved. # # 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 above copyright # notice, this list of conditions and the ...
import pytest from ddht.tools.factories.alexandria import AdvertisementFactory from ddht.v5_1.alexandria.broadcast_log import BroadcastLog @pytest.mark.trio async def test_broadcast_log(alice, bob, conn): ad_a = AdvertisementFactory(private_key=alice.private_key) ad_b = AdvertisementFactory(private_key=alice...
import py, os, sys from pytest import mark, raises from .support import setup_make noboost = False if not (os.path.exists(os.path.join(os.path.sep, 'usr', 'include', 'boost')) or \ os.path.exists(os.path.join(os.path.sep, 'usr', 'local', 'include', 'boost'))): noboost = True @mark.skipif(noboost == True,...
import operator import os import traceback import warnings import numpy as np import pandas as pd import tables from pandas.errors import PerformanceWarning from tables.exceptions import NaturalNameWarning from tqdm import tqdm from .._utils import std_out_err_redirect_tqdm from ..instruments import _get_dataset_inst...
#!python from distutils.core import setup description = 'Generate randomized strings of characters using a template' with open('README.txt') as file: long_description = file.read() setup(name='StringGenerator', description=description, url='https://github.com/paul-wolf/strgen', author='Paul Wol...
import asyncio import json import logging import random import time from json import JSONDecodeError from struct import pack, unpack from xml.etree import ElementTree from xmlrpc.client import ServerProxy import aiohttp from others.settings import * class BilibiliClient: def __init__(self, url_room_id): ...
from gocept.amqprun.readfiles import FileStoreReader, FileStoreDataManager from unittest import mock import gocept.amqprun.interfaces import gocept.amqprun.testing import os import shutil import tempfile import unittest import zope.component import time class ReaderTest(unittest.TestCase): def setUp(self): ...
cubos = [] for value in range(1,11): cubos.append(value**3) for cubo in cubos: print(cubo)
import datetime from dateutil.parser import parse import re from aws.api import CloudTrail class Trail(): def __init__(self, cloudTrailDict): self.isMultiRegionTrail = cloudTrailDict['IsMultiRegionTrail'] self.logFileValidationEnabled = cloudTrailDict['LogFileValidationEnabled'] self.name =...
from .utils.Classes.RegEx import RegEx from .utils.assert_string import assert_string def is_full_width(input: str) -> bool: input = assert_string(input) full_width_pattern = RegEx(r"[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]") return full_width_pattern.match(input)
from mongoengine.fields import ( StringField, DBRef, ListField, ObjectIdField, ReferenceField, DictField, BooleanField, ) from .nanopublication import Nanopublication from .entity_base import EntityBase class Workflow(EntityBase): meta = {"collection": "workflows"} # identify ...
import numpy as np from scipy.special import j0 as BesselJ0, j1 as BesselJ1, jn as BesselJ from scipy.optimize import root def shoot_S1(central_value: float, w: float, R: np.ndarray, coeffs: np.ndarray, S_harmonics: np.ndarray = None) -> np.ndarray: """ Shoo...
import requests import structlog from datetime import datetime log = structlog.get_logger(__name__) def register(explorer_endpoint, rsk_address, rns_domain): try: if rns_domain is None: rns_domain = '' data_registry = {'node_address': rsk_address, 'rns_addre...
import os import torch import torchvision import cv2 import numpy as np from torch.utils.data import Dataset from PIL import Image from functools import reduce class PipelineFacesDatasetGenerator(Dataset): negative_extensions = ['.txt'] def folder_filter(self, _path): return reduce( lam...
import printer # Possibly refactor out to a message exception base class class SymbolNotFound(Exception): def __init__(self, symbol): self.symbol = symbol def __repr__(self): return "'" + self.symbol + "' not found" class Env: def __init__(self, outer=None): self.outer = outer ...
import rospy from std_msgs.msg import Bool from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport from geometry_msgs.msg import TwistStamped import math from pid import PID from yaw_controller import YawController from lowpass import LowPassFilter GAS_DENSITY = 2.858 ONE_MPH = 0.44704 cla...
# Generated by Django 3.1.7 on 2021-03-30 02:51 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('company', '0005_company_description'), ] operati...
# -*- coding: utf-8 -*- """Unit test package for ndexnetworkcollapse."""
from newim import get_info, get_vtn import requests import json import logging from sqlalchemy import create_engine import pytricia pyt = pytricia.PyTricia() e = create_engine('sqlite:///database/wim_info.db') def setRules(cond_name, in_seg,out_seg,ordered_pop,index): logging.debug("Ordered PoPs are:") logging.d...
# -*- coding: utf-8 -*- from unittest import TestCase import sympy as sp import numpy as np class TestParserNonLinearInputData(TestCase): def test_hyperbox_states(self): from ETCetera.util.parsing.parser_nonlinear_systems import parse_nonlinear self.assertTrue(np.allclose(parse_nonlinear('Hyper...
import gym from vel.api.base import LinearBackboneModel, Model, ModelFactory from vel.rl.api import Evaluator, Rollout from vel.rl.modules.q_head import QHead class QModelEvaluator(Evaluator): """ Evaluate simple q-model """ def __init__(self, model: 'QModel', rollout: Rollout): super().__init__(roll...
import cv2 from threading import Thread class Webcam: def __init__(self): self.video_capture = cv2.VideoCapture(0) self.current_frame = self.video_capture.read()[1] # create thread for capturing images def start(self): Thread(target=self._update_frame, args=()).start() def _u...