content
stringlengths
5
1.05M
from settings import * from managers.resourcemanager import ResourceManager as GR from managers.soundcontroller import SoundController as SC from escenas.gui.buttons import ToogleButton, LevelButton, ClasicButton from escenas.menu import Menu """ Menú de Ajustes """ class Settings(Menu): def __init__(self,direct...
import numpy as np import gym from gym import logger class Box(gym.Space): """ A box in R^n. I.e., each coordinate is bounded. Example usage: self.action_space = spaces.Box(low=-10, high=10, shape=(1,)) """ def __init__(self, low=None, high=None, shape=None, dtype=None): """ ...
import torch class SharedAdam(torch.optim.Adam): # extend a pytorch optimizer so it shares grads across processes def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0): super(SharedAdam, self).__init__(params, lr, betas, eps, weight_decay) for group in self.param_groups: ...
# encoding=utf8 # pylint: disable=mixed-indentation, multiple-statements, old-style-class from NiaPy.tests.test_algorithm import AlgorithmTestCase, MyBenchmark from NiaPy.benchmarks.griewank import Griewank from NiaPy.algorithms.basic import KrillHerdV1, KrillHerdV2, KrillHerdV3, KrillHerdV4, KrillHerdV11 class KHV1Te...
from functools import partial from typing import List, Dict, Tuple, Set from fastapi import FastAPI, WebSocket, WebSocketDisconnect from central_server.models.check_in import CheckIn, CheckInStatus from central_server.models.temp_log import TempLog, EventType from central_server.models.room import Room from central_se...
class Segment(object): # Название сегмента. NAME = "" # Тип сегмента. TYPE = "" # Параметры для сегмента. PARAMS = None def __init__(self): pass def add_segment(self, name: str, type: str, params: dict = None) -> None: """ Добавление сегмента. :param n...
import os.path as op from sphinx_gallery.scrapers import matplotlib_scraper from sphinx_gallery.sorting import FileNameSortKey class matplotlib_format_scraper(object): def __repr__(self): return self.__class__.__name__ def __call__(self, block, block_vars, gallery_conf): kwargs = dict() ...
import os import json from myclient import SyncSample username = "ham@example.com" password = "spam" passphrase = "s-pamsp-amspa-mspam-spams-pamsp" def update_bookmarks(filepath=os.path.join(os.environ['HOME'],'Documents','bookmarks.json')): s = SyncSample(username, password, passphrase) meta = s.get_meta() ...
import os import sys import random import logging from PIL import Image import numpy as np def encode_img2mask(image): """ Function to encode a synthetic image saved as opencv BGR as HxWx3 tensor to a HxWx1 where the last channel represents the occlusion category ID """ image = image.astype(int) ...
#!/usr/bin/env python import os import numpy as np from selfdrive.can.parser import CANParser from cereal import car RADAR_MSGS = range(0x500, 0x540) def _create_radar_can_parser(): dbc_f = 'ford_fusion_2018_adas.dbc' msg_n = len(RADAR_MSGS) signals = list(zip(['X_Rel'] * msg_n + ['Angle'] * msg_n + ['V_Rel'] *...
from distutils.core import setup, Extension luckybit_hash_module = Extension('luckybit_hash', sources = ['luckybitmodule.c', 'luckybit.c', 'sha3/neoscrypt.c'], i...
import tensorflow as tf import config import numpy as np import json import time from models.model_factory import get_models from utils.data_utils import load_image, test_10_crop_iterator from utils.train_utils import cross_entropy_batch, l2_loss from utils.augment_utils import test_10_crop import os os.envir...
""" Goal: Store helper functions not tied to a specific module @authors: Andrei Sura <sura.andrei@gmail.com> Ruchi Vivek Desai <ruchivdesai@gmail.com> Sanath Pasumarthy <sanath@ufl.edu> """ import os import ast import json from datetime import datetime, timedelta from itsdangerous ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # 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 agr...
import hashlib, requests, os, collections def compare(self, oth,count=True,lst='short',sect='CMORvar' ): n0 = 0 n1 = 0 n2 = 0 this = self.coll[sect].items[0] that = oth.coll[sect].items[0] lstValid = [None,'short','long'] assert lst in lstValid, 'Value of lst [%s] not valid, one of: %s' % (...
import numpy as np import cv2 from operator import ne, eq import skvideo.io import notes as rs def toByte(value): if value <= 0: return 0 if value >= 255: return 255 return value def getMask(color, cv2_image, range=120): # calculating upper and lower shades lower_color = np.array...
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # Test core.clickhouse package # ---------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # -------------------------------------------------...
import sys from IPy import IP from time import time from tqdm import tqdm from json import dumps from os.path import join from dns.query import xfr from ipwhois import IPWhois from dns.zone import from_xfr from termcolor import colored from dns.name import EmptyLabel from dns.exception import DNSException from ssl impo...
import argparse import logging class Coroner: """ Main Coroner Class""" def __init__(self): logging.debug("Coroner Constructed") if __name__ == "__main__": logging.basicConfig(format="[%(levelname)s] %(filename)s:%(lineno)s: %(message)s", level=logging.DEBUG) coroner = Coroner()
from django.http import HttpResponse def ping(request): return HttpResponse("<h1>Ping Received for tejasbaindur.com</h1>")
import cv2 import numpy import os def task2_2(): matstack = numpy.identity(3) matlog = [] p = '../datasets/traffic/' inp = ['input/' + x for x in os.listdir(p + 'input/')] inp.sort() gth = ['groundtruth/' + x for x in os.listdir(p + 'groundtruth/')] gth.sort() phv = '../datasets/highway...
import unittest from maml.utils import ConstantValue, LinearProfile class TestValueProfile(unittest.TestCase): def test_constant(self): constant_profile = ConstantValue(0.1) constant_profile.increment_step() self.assertEqual(constant_profile.step, 1) self.assertAlmostEqual(constan...
# Copyright 2016 Spanish National Research Council # # 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...
from pytest import raises from numpy import arange, prod, array, full from hypothesis import given, example from hypothesis.strategies import integers, one_of from ..ndindex import ndindex from ..tuple import Tuple from ..integer import Integer from .helpers import ndindices, check_same, short_shapes @example(..., ...
# -*- coding: utf-8 -*- ## 时间: 2015-02-13 ## 跟新内容: ## 增加URL请求时间计算 ## 时间: 2015-04-01 ## 跟新内容: ## 将指定的测试文件名写入配置文件中,同时增加一个获取当前路径的类 ## from pathlib import Path import json import io import sys import traceback import os import os.path import time import gc sys.path.append(os.path.join(os.path.dirname(__file__),r'...
# -*- coding: utf-8 -*- from watson.validators import abc class Range(abc.Validator): """Validates the length of a string. Example: .. code-block:: python validator = Length(1, 10) validator('Test') # True validator('Testing maximum') # raises ValueError """ def __in...
#!/usr/bin/env python3 # std import os from pathlib import Path import sys import logging # 3rd import matplotlib.pyplot as plt # ours sys.path.insert(0, "../..") import ankipandas from ankipandas.util.log import get_logger class Loader(object): def __init__(self): this_dir = Path(__file__).parent ...
# Generated by Django 3.2.4 on 2021-06-29 23:08 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('cantiin', '0001_initial'...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2022/3/29 2:15 下午 # @Author : xinming # @File : 300_length_of_LIS.py from typing import List class Solution: def lengthOfLIS(self, nums: List[int]) -> int: n = len(nums) dp = [1 for i in range(n)] for i in range(1, n): ...
import argparse import json import os from dataclasses import dataclass from typing import List, Dict, Any, Optional, Union from Abilities import AbilityData, get_ability_and_references from Actions import Action, get_text_label, get_action_and_associated from Common import run_common @dataclass class SkillData: ...
from suls.caches.triecache import TrieCache from suls.rersconnectorv3 import RERSConnectorV3 from suls.rersconnectorv4 import RERSConnectorV4 from suls.rersconnectorv2 import RERSConnectorV2 from numpy.random import choice import time from pygtrie import StringTrie from suls.rerssoconnector import RERSSOConnector pat...
# This file was generated automatically and will be overwritten # with next generation. Make changes with caution import sqlalchemy as sa from ermaket.models.base import Base __all__ = ['Er1UserIsAssignedToTask'] class Er1UserIsAssignedToTask(Base): __tablename__ = 'user_is_assigned_to_task' __table_args__...
import threading from threading import Thread import time ''' Python 3.X threading 模块演示 Demo threading 的 Thread 类基本使用方式(继承重写 run 方法及直接传递方法) ''' class NormalThread(Thread): ''' 重写类比 Java 的 Runnable 中 run 方法方式 ''' def __init__(self, name=None): Thread.__init__(self, name=name) self.count...
#!/usr/bin/env python """ Copyright 2020 Johns Hopkins University (Author: Jesus Villalba) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ import sys import os from jsonargparse import ( ArgumentParser, ActionConfigFile, ActionParser, namespace_to_dict, ) import time import logging f...
""" An example of highlighting "linked" artists. When one is selected, its partner will be highlighted in addition to the original artist. Illustrates subclassing a DataCursor. """ import numpy as np import matplotlib.pyplot as plt import mpldatacursor def main(): fig, axes = plt.subplots(ncols=2) num = 5 ...
import json import jwt from flask import Flask, request, jsonify from mongoengine.queryset.visitor import Q from datetime import datetime from app import app from app import db from Models.UserLogin import UserLogins from Models.UserDetails import UserDetails from Models.SnippetPost import SnippetPost from Models.Po...
from e2etests.config import url from e2etests.util import create_project_upload_fake_data, create_project_no_data, get_runs, post_run, \ temporary_blank_project def test_empty_list_run(requests): with temporary_blank_project(requests) as project: r = get_runs(requests, project) assert r == [] ...
from AppKit import NSDocument from PyObjCTools import NibClassBuilder, AppHelper from tinyTextEditorDocumentWindow import TinyTextEditorDocumentWindow NibClassBuilder.extractClasses("MainMenu") class TinyTextEditorDocument(NSDocument): def init(self): self = super(TinyTextEditorDocument, self).init...
import os import subprocess from PIL import Image, ImageDraw, ImageFont from src.constants import POSITION, TEXT_COLOR, TEXT_FONT, TEXT_SIZE, PATH_TO_FFMPEG class GifGenerator: def __init__(self): self.frames = [] self.font = ImageFont.truetype(TEXT_FONT, TEXT_SIZE) self.text_position = ...
import numpy as np import warnings from scipy.sparse.csgraph import minimum_spanning_tree, connected_components from sklearn.metrics import euclidean_distances def tree_information(X, y): """Computes mutual information objective using MST entropy estimate. Parameters ---------- X: numpy array, shape...
import os from dotenv import load_dotenv import openai load_dotenv() openai.organization = "org-D2FBgBhwLFkKAOsgtSp86b4i" openai.api_key = os.getenv("OPENAI_API_KEY") remote_files = openai.File.list()["data"] fine_tune_training_files = filter(lambda f: "fine_tune.jsonl" in f["filename"], remote_files) latest_fine_tu...
class OfflineArgs: def __init__(self, n_hands, hero_file_path, villain_file_path, hero_use_canonical, villain_use_canonical): self.n_hands = n_hands self.hero_file_path = hero_file_path self.villain_file_path = villain_file_path self.hero_use_canonical = hero_use_ca...
from setuptools import setup, find_packages setup( name='munimap', version="1.0", url='<enter URL here>', license='BSD', maintainer='terrestris GmbH & Co. KG', maintainer_email='info@terrestris.de', description='Municipality map with street index, search grid, etc.', packages=find_packa...
import asyncio from datetime import datetime as dt async def timed_call(timeout,callback,duration=5,args=None): loop = asyncio.get_running_loop() end_time = loop.time() + duration while timeout>0: if loop.is_running(): if args is not None: callback(args) els...
# flake8: noqa """ Tune's Scikit Learn Adapters ============================ Scikit-Learn is one of the most widely used tools in the ML community for working with data, offering dozens of easy-to-use machine learning algorithms. However, to achieve high performance for these algorithms, you often need to perform **mo...
from .monomodule import MonoModule import json import requests import datetime from requests_oauthlib import OAuth1Session description = '''This module searches Twitter with Twitter API. https://developer.twitter.com/en/docs/twitter-api/v1/tweets/search/api-reference/get-search-tweets This module reqires T...
# -*- coding: utf-8 -*- """Run tests for writing.""" # Author: Eric Larson <larson.eric.d@gmail.com> # # License: BSD-3-Clause import pytest from mne.io.constants import FIFF from mne.io.write import start_file, write_int def test_write_int(tmp_path): """Test that write_int raises an error on bad values.""" ...
from typing import Any, Generic, List, Optional, Tuple, TypeVar, cast import numpy as np import torch from torch import nn from mlprogram.actions import ActionSequence from mlprogram.builtins import Environment from mlprogram.encoders import ActionSequenceEncoder from mlprogram.languages import Parser, Token Code = ...
import torch import torchvision # model_fastercnn = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) # modules_2 = list(model_fastercnn.children()) # for iter, module in enumerate(modules_2): # print("###### {} ######".format(iter)) # print(module) # print(model_fastercnn.roi_heads.box_...
"""Manually define the number, shape and position of the renderers inside the rendering window""" from vedo import * settings.immediateRendering = False # faster for multi-renderers # (0,0) is the bottom-left corner of the window, (1,1) the top-right # the order in the list defines the priority when overlapping cust...
# coding utf-8 """ Creates edges out of the RDF graph :author: Asan Agibetov """ from rdflib import RDF, RDFS, OWL, BNode from grontocrawler.utils import utils def get_direct_superclasses(resource, g): """ (rdflib.URI, rdflib.Graph) -> { short_names: [label or short_name], u...
from django.shortcuts import render, redirect from django.template.loader import get_template # Create your views here. def device_index(request): if not request.user.is_authenticated: return redirect('/') cd = {} cd['dash_index'] = get_template('rooms/rooms_index.html').render() return render(request,'common/i...
from enum import Enum from typing import Union, List, Dict def adcard(): def wrapper(K): setattr(K, "get_element", get_element) return K return wrapper def isFilled(value): if value == None: return False return True def get_element(self): ret = {} if self == None: ...
from behave import * from selenium import webdriver @given("I am hungry") def step_impl(context): pass @when("my mother is shopping") def step_impl(context): url = 'http://www.seleniumframework.com' context.browser.get(url) @then("I cook a meal") def step_impl(context): print ("print debug #1") ...
""" Mail Settings """ import os """ |-------------------------------------------------------------------------- | From Address |-------------------------------------------------------------------------- | | This value will be used for the default address when sending emails from | your application. | """ FROM = { ...
from ..utils import to_value, len_batch from .callback_tensorboard import CallbackTensorboardBased from ..train import utilities from ..train import outputs_trw as O import functools import collections import torch import numpy as np import logging logger = logging.getLogger(__name__) def get_as_image(images): ...
from analysis.all_plot_modules import density_map import numpy as np import matplotlib.pyplot as plt def lambda_vs_density(allresults, out_dir="./"): """ What..? """ den_cmap = "YlGnBu_r" allids = [gal.id for gal in allresults] allids=[] lambda_r=[] eps=[] mgal=[] mgas_c=[] ...
#! /usr/bin/env python3 """Freeze a Python script into a binary. usage: freeze [options...] script [module]... Options: -p prefix: This is the prefix used when you ran ``make install'' in the Python build directory. (If you never ran this, freeze won't work.) The default ...
# The function to find if the string is a palindrome or not def is_palindrome(s): # Check if string is equal to its reverse. s = s.lower() return s == s[::-1] # The driver code if __name__ == '__main__': s = str(raw_input("Ask user for something: ")) IS_PALINDROME = is_palindrome(s) if IS_PALI...
import plenum.common.log # this is to stop logging from being configured when other imported modules are # parsed # IT MUST BE RUN AT THE EARLIEST POSSIBLE MOMENT if plenum.common.log.loggingConfigured: raise ImportError("logging cannot be configured by this point; " "make sure no other impor...
""" Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. ---------- Compute upper and lower limits on word perplexity for convlm models Command : python3 compute_lower_ppl_c...
import pprint from . import get_temp_dict_location import os import pickle import copy import numpy as np from . import get_qubit_count from . import config as cfg # TODO: docstrings ################################ # Calibration Dictionary ################################ def get_calibration_dict(): """ Fu...
import socket from datetime import datetime as dt from time import sleep from typing import List, Tuple from lights.core import Assignment, Group, Pulse, create_message # General constants RATE = 10 NUM_LIGHTS = 75 # Must fit in a single byte # Send in a something def main() -> None: recorded = [...
from radixlib.api_types.identifiers import NetworkIdentifier from typing import Dict import unittest class TestNetworkIdentifier(unittest.TestCase): """ Unit tests for the NetworkIdentifier class """ NetworkIdentifierDict: Dict[str, str] = { "network": "mainnet" } def test_from_dict(self): ...
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras import initializers from tensorflow.keras import activations from tensorflow.keras import regularizers import random from utils import * from tensorflow.compat.v1 import ConfigProto from ten...
import os import logging import configparser logger = logging.getLogger() config_pathname = os.getenv("TWITTERBOT_CONFIG", 'main.properties') config = configparser.RawConfigParser() config.read(config_pathname) def envFromProps(userID, key, required): propKey = f'twitter.{userID}.{key}' try: os.envi...
# Copyright 2017 Intel Corporation. # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. # The Material contains proprietary information of Intel...
# Lyes @2022 # The data could be found in http://keddiyan.com/files/PowerForecast.html # and T.-Y. Kim and S.-B. Cho, ‘‘Predicting residential energy consumption using CNN–LSTM neural networks,’’ Energy, vol. 182, pp. 72–81, Sep. 2019. # https://towardsdatascience.com/the-time-series-transformer-2a521a0efad3 import...
# -*- coding: utf-8 -*- """ TakeFixedArm: always select a fixed arm. This is the perfect static policy if armIndex = bestArmIndex (not realistic, for test only). """ from __future__ import division, print_function # Python 2 compatibility __author__ = "Lilian Besson" __version__ = "0.9" try: from .BasePolicy imp...
from load_non_oh import * from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error import sys if __name__ == '__main__': random.seed(42) np.random.seed(42) if len(sys.argv) < 3: print('Usage: python _ data_dir ws') exit() data_dir = sys.argv[...
"""Provides OAuth2 for HomeControl""" from typing import Callable import logging from json import JSONDecodeError from datetime import timedelta from aiohttp import web, hdrs import voluptuous as vol from homecontrol.dependencies.json_response import JSONResponse from homecontrol.dependencies.resolve_path import resolv...
from . import db from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from datetime import datetime class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer,primary_key = True) username = db.Column(db.String(255)) email...
from django.urls import path, include from rest_framework import routers from .views import APITokenViewSet router = routers.SimpleRouter() router.register(r"api-tokens", APITokenViewSet, basename="api-tokens") urlpatterns = [ path("", include(router.urls)), ]
#!/usr/bin/env python """Run the ltd-keeper app in development or production mode. If this is a new deployment, run ./run.py db upgrade ./run.py init To run in development mode:: ./run.py runserver In production:: export LTD_KEEPER_PROFILE=production ./run.py run.py runserver (Though in the Kuber...
import requests from scrapy.selector import Selector from datetime import date def scrape_alachua_county(): # Hardcode data for this county county = 'Alachua' state = 'Florida' state_abbreviation = 'FL' # data manually grabbed from the page # was much easier than scraping hours = '9 a.m. t...
import os import pandas as pd from tqdm import tqdm import pipelines.p1_orca_by_stop as p1 from utils import constants, data_utils NAME = 'p2_aggregate_orca' WRITE_DIR = os.path.join(constants.PIPELINE_OUTPUTS_DIR, NAME) def load_input(): path = os.path.join(constants.PIPELINE_OUTPUTS_DIR, f'{p1.NAME}.csv') ...
from convlab2.e2e.sequicity.camrest.sequicity import Sequicity
import builtins import collections import contextlib import glob import io import os import string from typing import Dict, Any, Tuple, List, Collection, Optional import attrs import pandas as pd from databutler.pat import astlib from databutler.pat.analysis.type_analysis.mypy_types import SerializedMypyType DF_TYPE...
# coding=utf-8 """ flask_resteasy.parsers ~~~~~~~~~~~~~~~~~~~~~~ """ from abc import abstractmethod from flask import request, current_app from flask_resteasy.errors import UnableToProcess class RequestParser(object): """Parses Route and Query parameters for an HTTP request. :param cfg: :class:`flas...
from __future__ import print_function import re,string def findUniqueSeed(hltPath,ExprStr): ''' given a hltpath and its L1SeedExpression, find the L1 bit name can return None if hltPath contains the following, skip do not parse seed. FakeHLTPATH*, HLT_Physics*, HLT_*Calibration*, HLT_HFThr...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import GLAccount, GLPeriodClosure, GLTransactionEntry admin.site.register(GLAccount) admin.site.register(GLPeriodClosure) admin.site.register(GLTransactionEntry)
import logging import json import os import pandas as pd import numpy as np import pytest from pandas.testing import assert_frame_equal from schematic.schemas.explorer import SchemaExplorer from schematic.schemas import df_parser from schematic.utils import general from schematic.utils import cli_utils from schemati...
#!/usr/bin/env python import abc import StringIO from ansible import errors try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser from InventoryFilter import InventoryFilter class GCloudInventory(InventoryFilter): def get_host_ips(self, topo): host_p...
# Loading data using sklearn dataset from sklearn.datasets import load_breast_cancer from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_...
""" Inequality metrics for STARS ---------------------------------------------------------------------- Distributional inequalities module for Space-Time Analysis of Regional Systems ---------------------------------------------------------------------- AUTHOR(S): Sergio J. Rey sjrey@users.sourceforge.net ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' def process_xml_string(xml_string): """ Функция из текста выдирает строку с xml -- она должна начинаться на < и заканчиваться > """ start = xml_string.index('<') end = xml_string.rindex('>') return xml_string[start:e...
# coding:utf-8 """ Fun begins here! """ from ... import * from nose.tools import * from mock import * from flanker.mime import create from flanker.mime.message.threading import * from flanker.mime.message.headers import MessageId @patch.object(MessageId, 'is_valid', Mock(return_value=True)) def test_wrapper_creates_...
# Generated by Django 3.0.3 on 2020-04-02 11:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0003_auto_20200402_1004'), ('mood_groups', '0002_auto_20200329_1653'), ] operations = [ mi...
import envs import gym import pandas as pd import numpy as np import os from datetime import datetime import torch import math import re from typing import List, Tuple maze_parser = re.compile(r"""Maze_\((\d+),(\d+),(\d+),(\d*\.\d+|\d+),(\d*\.\d+|\d+)\)""") import glob DIRPATH = os.path.dirname(os.path.realpath(__f...
import glob import serial import time import usb import string import sys # Arm controller serial properties. BAUD_RATE = 19200 PARITY = serial.PARITY_NONE STOP_BITS = serial.STOPBITS_TWO BYTE_SIZE = serial.EIGHTBITS OUTPUT_ENCODING = 'latin_1' # The read timeout is intentionally long, so that a complete calibratio...
# Outputs: # vgg loss between target and test1: 0.3948165476322174 # vgg loss between target and test2: 0.44597795605659485 # vgg loss between target and test3: 0.713489830493927 # vgg loss between target and test4: 0.9643082022666931 import numpy as np import torch as th from torchvision.models import vgg19 from torc...
"""One-dimensional kernel density estimate plots.""" import numpy as np import matplotlib.pyplot as plt from scipy.signal import gaussian, convolve, convolve2d # pylint: disable=no-name-in-module from scipy.sparse import coo_matrix from scipy.stats import entropy def plot_kde(values, values2=None, contour=True, ax=N...
import tensorflow as tf from utils.classifier_utils import TextLoader flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('map_file_path', None, 'standard data path') flags.DEFINE_string("model_path", None, "checkpoint dir from predicting") flags.DEFINE_string('test_data_path', None, 'test data path') flags....
"""Test BoB Token API""" import logging import os import unittest from datetime import datetime, timezone import dateutil.parser from bobby_client.env import TestEnvironment from bobby_client.utils import b64e class TestTokenAPI(unittest.TestCase): def setUp(self): logging.basicConfig(level=logging.IN...
#! /usr/bin/env python ########################################################################################## # BBB_MotorInterrupts.py # # Basic use of interrupts on the Beagle Bone Black to start/stop a motor # using the Pololu High-power motor driver - https://www.pololu.com/product/755 # # Requires - Adafruit B...
''' Created on Mar 10, 2017 @author: cesar ''' import unittest import json import matplotlib.pyplot as plt from tag2hierarchy.hierarchy import HTMLPLOT from tag2hierarchy.hierarchy import tree2Dict from tag2hierarchy.hierarchy import treeHandlers class Test(unittest.TestCase): def jsonToTree(self): ...
#emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- #ex: set sts=4 ts=4 sw=4 noet: """ LICENSE: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software ...
class AlreadyQueued(Exception): """ Raised when a trying to queue document already in the queue """ pass class OCRError(Exception): """ Raised by the OCR backend """ pass class UnpaperError(Exception): """ Raised by unpaper """ pass class ReQueueError(Exception): ...
#!/usr/env python def quick_sort(array, start, end): if(start < end): i = start j = end base_value = array[i] while i < j : while (i < j and array[j] >= base_value): j = j - 1 if(i < j): array[i] = array[j] i = ...
from roonapi import RoonApi appinfo = { "extension_id": "python_roon_test", "display_name": "Python library for Roon", "display_version": "1.0.0", "publisher": "gregd", "email": "mygreat@emailaddress.com", } server = "192.168.3.60" target_zone = "Mixing Speakers" # Can be None if you don't yet hav...