content
stringlengths
5
1.05M
from math import floor class StepperError(Exception): pass class Stepper(): sMicrostep = (None, 1, 2, 2, 4, 8, 16, 32) # this might be wrong, confusing from uCtrl label sPulsePerRev = (None, 200, 400, 800, 1600, 3200, 6400) sCurrent = (0.5, 1.0, 1.5, 2.0, 2.5, 2.8, 3.0, 3.5) sPkCurrent = (0.7, 1.2...
# -*- coding: utf-8 -*- import time from concurrent.futures import as_completed from common.db import read_session_scope, write_session_scope from config.config_loader import logger, global_config from mall_spider.common.enums import RiskType, PickleFileType from mall_spider.dao.stream_risk_dao import get_stream_risk_...
import time import logging from instabot.api import api from instachatbot.nodes import Node, MenuNode from instachatbot.state import Conversation from instachatbot.storage import Storage class InstagramChatBot: def __init__(self, menu: MenuNode, storage: Storage = None, trigger=None): self.logger = logg...
import numpy as np def nextthing(): var = np.random.rand(1) if var<0.3: print('Attack human!') elif var<0.7: print('Be cute.') else: print('Make weird noises.')
import os from pathlib import Path from django.contrib import messages from django.contrib import admin from django.contrib.admin import display # was introduced in Django 3.2 from django.conf import settings from .models import Account from .models import Brand from .models import DataSource from .models import Data...
from userver.object.asserts import Assertions from userver.object.device import FieldDevice from utils.errors import PatchError from wtforms import Form, StringField, validators from wtforms.validators import StopValidation from userver.object.const import ClassType from binascii import unhexlify from .validators impo...
import fnmatch import re from pathlib import Path from typing import Iterable, List class PathList: def __init__(self, root: Path, *paths): self.root = root.resolve() self.paths = [] self.events = [] if paths: self.extend(paths) def glob(self, pattern: str): ...
# coding=utf-8 #给你一个正整数列表 L, 如 L=[2,8,3,50], 判断列表内所有数字乘积的最后一个非零数字的奇偶性, #奇数输出1,偶数输出0. 如样例输出应为0 L = [2,8,3,50] res = 1 for item in L: res *= item while not res % 10: res /= 10 print 1 if res % 2 else 0
""" Util module This module contains miscellaneous classes and constants that are used by the game engine """ import pygame import math SERVER = 0 CLIENT = 1 COMBINED = 2 with open('config') as f: try: configuration = {line.strip().split('=')[0] : line.strip().split('=')[1] for line in f} DEFAULT_...
""" This module contains the structures related to areas of interest. """ from typing import NamedTuple, Optional, Union class AreaOfInterest(NamedTuple): """ .. versionadded:: 2.3 This is the area of interest for: - Transformations - Querying for CRS data. """ #: The west bound in degr...
"""LimitlessLED Version 6 Bridge """ import types import math import logging import time from mookfist_lled_controller.colors import color_from_rgb from mookfist_lled_controller.bridge import BaseBridge, BaseGroup, Command import six import binascii GROUPS = (0, 1, 2, 3, 4, 'all') def format_hex(i): if i < 16: ...
""" source: https://stanford.edu/~shervine/blog/pytorch-how-to-generate-data-parallel """ import os import time import cv2 import numpy as np import shutil import sys from numpy.core.fromnumeric import argmax import torch import torch.optim as optim import torchvision from dataset.BDD100k import BDDDataset from model...
import base64 import json import pytest from unittest import mock from actions import user_actions def test_protect_resources(): """Verify exception when acting on protected resources.""" with pytest.raises(SystemExit): user_actions.protect_resources("admin") with pytest.raises(SystemExit): ...
# Copyright (c) 2017 NEC Corp. # 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...
# -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import Qt from pycoin.key.BIP32Node import BIP32Node from pycoin.cmds.ku import get_entropy from pycoin.networks.default import get_current_netcode from first_page import Ui_first from ..encoding.encoding import get_chain_secret_pair ...
""" .dat export base handler Overview =============================================================================== +----------+------------------------------------------------------------------+ | Path | PyPoE/cli/exporter/dat/handler.py | +----------+----------------------------...
''' Calculates the 12C(p,gamma) cross section and compares it to the Vogl data. "Free" parameters: * ANC (1/2-) * level energy (1/2+) * partial width (1/2+, elastic) * partial width (1/2+, capture) ''' import os import sys from multiprocessing import Pool import emcee import nu...
from fnmatch import fnmatch def test_fixture(regression_file_path): assert fnmatch(str(regression_file_path.relative), "[01].xmf") assert fnmatch( str(regression_file_path.absolute), "*/test_regression_file_path_fixture0/references/case/[01].xmf", )
import numpy as np from HungarianAlgorithm.model import hungarian from HungarianAlgorithm.matrix_generator import gen_matrix_given_permutation, gen_matrix if __name__ == '__main__': """ Some test ready to go, to see utilities and limitations. """ p = [0, 2, 3, 5, 1, 4] a = gen_matrix_given_permu...
from tests.graph_case import GraphTestCase class TestPlanner(GraphTestCase): @classmethod def setUpClass(cls): super(TestPlanner, cls).setUpClass() @classmethod def tearDownClass(cls): pass def test2_list_my_plans(self): my_plans = self.client.me.planner.plans.get().exec...
""" ゼロから学ぶスパイキングニューラルネットワーク - Spiking Neural Networks from Scratch Copyright (c) 2020 HiroshiARAKI. All Rights Reserved. """ import numpy as np import matplotlib.pyplot as plt class HodgkinHuxley: def __init__(self, time, dt, rest=-65., Cm=1.0, gNa=120., gK=36., gl=0.3, ENa=50., EK=-77., El=-54.387): ""...
""" All visualization performed my mdsea is contained in this directory. Different visualization platforms are developed in different files. """
"""Extract signatures from an image.""" import cv2 import matplotlib.pyplot as plt from skimage import measure, morphology from skimage.measure import regionprops def extractor(img): img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary # co...
users = {} messages = [] queues = []
import requests from bs4 import BeautifulSoup import time #BTC_URL = 'https://ru.investing.com/crypto/bitcoin/btc-usd' #convert = soup.findAll("span", {"class": "arial_26 inlineblock pid-1058142-last"}) #ETH_URL = 'https://ru.investing.com/crypto/ethereum/eth-usd' #convert = soup.findAll("span", {"class": "ar...
from functools import reduce import wx from vistas.core.observers.camera import CameraObservable from vistas.core.preferences import Preferences from vistas.ui.controllers.project import ProjectChangedEvent from vistas.ui.controls.viewer_panel import ViewerPanel from vistas.ui.events import EVT_CAMERA_MODE_CHANGED, E...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class RedHat(models.Model): PROTOCOL_CHOICES = ( #(0,''), ('rest', 'REST API'), ('soap', 'SOAP'), ('telnet', 'Telnet'), ('ssh', 'SSH'), ) hostnam...
#!/usr/bin/env python # Copyright 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Test variable expansion of '<!()' syntax commands where they are evaluated more than once from different directories. """ import...
#!/usr/bin/env python3 import time import datetime import dateutil.parser from difflib import SequenceMatcher import os import requests from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.su...
import numpy as np from pyhlm.model import WeakLimitHDPHLM, WeakLimitHDPHLMPython from pyhlm.internals.hlm_states import WeakLimitHDPHLMStates from pyhlm.word_model import LetterHSMM, LetterHSMMPython import pyhsmm from tqdm import trange import warnings warnings.filterwarnings('ignore') import time from argparse impor...
""" 2 3 2 3 ok 2 3 ok 3 1 3 1 errados 3 1 errados 5 5 5 5 ok 5 5 ok 5 4 5 4 errados 5 4 ok 5 4 5 4 errados 5 4 ok 9 9 9 9 ok 9 9 ok 0 0 0 0 errados 0 0 ok 0 1 0 1 ok 0 1 ok 1 0 1 0 errados 1 0 ok 89 25 89 25 errados 89 25 errados 4 5 4 5 ok 4 5 ok 10 12 10 12 errados 10 12 errados 10 11 10 11 ok 10 11 ok 11 10 11 10 er...
from django import template from ..apps.basket import my_middleware register = template.Library() @register.simple_tag def request_made(): my_middleware.my_list.append("end of request") return my_middleware.my_list[0:-1] @register.simple_tag def request_made_len(): return len(my_middleware.my...
# Copyright Indra Soluciones Tecnologías de la Información, S.L.U. # 2013-2019 SPAIN # # 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...
import datetime import dgl import errno import numpy as np import os import pickle import random import torch import nni from dgl.data.utils import download, get_download_dir, _get_dgl_url from pprint import pprint from scipy import sparse from scipy import io as sio def set_random_seed(seed=0): """Set random see...
import environ import socket ROOT_DIR = environ.Path(__file__) - 3 # (safe_relay_service/config/settings/base.py - 3 = safe-relay-service/) APPS_DIR = ROOT_DIR.path('safe_relay_service') env = environ.Env() READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False) DOT_ENV_FILE = env('DJANGO_DOT_ENV_FI...
__version__ = '1.5.4.0'
# Generated by Django 2.1.4 on 2018-12-11 04:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customer', fields=[ ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # ------------------------------------------------------------------------------ # Copyright 2020. NAVER Corp. # # 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 cop...
import json from bs4 import BeautifulSoup import pandas as pd import sys # Argparsing argument_index = 1 template = sys.argv[argument_index] argument_index +=1 recall_json = sys.argv[argument_index] argument_index +=1 recall_plot = sys.argv[argument_index] argument_index +=1 precision_jsons_list = [sys.argv[i] for ...
#!/usr/bin/env python """test-imu-plot.py: Ask multiwii for raw IMU and plot it using pyqtgraph.""" __author__ = "Aldo Vargas" __copyright__ = "Copyright 2016 Altax.net" __license__ = "GPL" __version__ = "1" __maintainer__ = "Aldo Vargas" __email__ = "[email protected]" __status__ = "Development" from pymultiwii im...
# -*- coding: UTF-8 -*- import requests import json def get_api(api_url, api_name, token, record_id=None): if not record_id: return requests.get('{}/{}/?token={}'.format(api_url, api_name, token)) return requests.get('{}/{}/{}?token={}'.format(api_url, api_name, ...
# to be defined once OK pass
''' # Criar variável para nome (str), idade (int), # altura (float) e peso (float) de uma pessoa # Criar variavel com ano atual (int) # Obter o ano de nascimento da pessoa (baseada na idade e no ano atual) # Obter o imc da pessoa com 2 casas decimais (peso e na altura da pesso) # Exibir um texto com todos os valores na...
#! 圆斑/重叠圆斑计数工具 import os import otsu import pylab import numpy as np import mahotas as mh from PIL import Image from PIL import ImageFilter from PIL import ImageEnhance FileName = input("输入测试图片名称(默认为edu.tif):") or "edu.tif" CurrentDir = os.getcwd() global new_img, r_criterion, g_criterion, b_criterion,...
""" No Prefix Set https://www.hackerrank.com/challenges/no-prefix-set/problem?h_r=next-challenge&h_v=zen Given strings. Each string contains only lowercase letters from (both inclusive). The set of strings is said to be GOOD SET if no string is prefix of another string else, it is BAD SET. (If two strings are identi...
import requests import sys import httplib import json from . import betfairng from datetime import datetime class BFGlobalService(object): def __init__(self, app_key, debuglevel=0, cert=None): self.cert = cert self.betting_api = betfairng.BettingApi(app_key=app_key, debuglevel=debuglevel) de...
from time import time as timeout_timer from .compat import XRANGE try: from __pypy__.time import clock_gettime from __pypy__.time import CLOCK_MONOTONIC def monotonic(): return clock_gettime(CLOCK_MONOTONIC) except ImportError: from timeit import default_timer else: default_timer = monoto...
import random import torch.optim.lr_scheduler as Sch class RandomSelect(object): def __init__(self, opt_list, stride=5): super().__init__() self.opt_list = opt_list self.stride = stride self.current = random.choice(self.opt_list) self.sch = [] self.count = 0 def ...
"""Platform Models.""" from marshmallow import fields, Schema from marshmallow.validate import OneOf from ..enums import * from ..models.BaseSchema import BaseSchema from .App import App from .AppInventory import AppInventory from .AppDomain import AppDomain class CreateApplicationRequest(BaseSchema): # Confi...
import pytest from server import create_app @pytest.fixture(scope='module') def test_client(): flask_app = create_app() testing_client = flask_app.test_client() ctx = flask_app.app_context() ctx.push() yield testing_client # this is where the testing happens! ctx.pop() def test_fetch_trans...
"""Main window class for TSL applications.""" from __future__ import annotations import json import logging from dataclasses import dataclass from typing import Optional from PyQt5.QtCore import QSettings, pyqtSlot from PyQt5.QtGui import QCloseEvent from PyQt5.QtWidgets import QMainWindow, QMessageBox, QWidget impo...
"""Use pretained resnet50 from tensorflow slim""" import tensorflow as tf import numpy as np import os from slim_dir.nets import resnet_v1, resnet_utils slim = tf.contrib.slim def resnet_v1_50(inputs, num_classes=None, is_training=True, global_pool=False, ...
from base import BaseInstanceStep from dbaas_credentials.models import CredentialType from util import get_credentials_for from util import build_context_script from util import exec_remote_command_host import logging from system.models import Configuration LOG = logging.getLogger(__name__) class MetricsCollector(Ba...
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: Mcl_Cmd_Firewall_Tasking.py CMD_ACTION_STATUS = 1 CMD_ACTION_ENABLE = 2 CMD_ACTION_DELETE = 3 CMD_PROTOCOL_TCP = 0 CMD_PROTOCOL_UDP = 1 CMD_DIRECTION...
import torch import torchvision.transforms as transforms import torch.nn.functional as F import numpy as np import math import clip from PIL import Image from ZSSGAN.utils.text_templates import imagenet_templates, part_templates, imagenet_templates_small class DirectionLoss(torch.nn.Module): def __init__(self,...
""" Primeira Classe - criada """ # Classe pep 8 - Função letra minuscula e Classe letra maiuscula # Colocar o estado de todos arquivos, tirando uma foto, fazendo o Push para enviar no repositorio no GitHub; direito na pasta -> Git - > Commit Directory # Subir no GitHub depois da Print, CTRl+SHIFT+K OU direito na pas...
import os import subprocess import sys import tarfile import tempfile from dataclasses import asdict import numpy as np import onnxruntime as ort import torch import torchvision import yaml from arachne.data import Model, ModelFormat, ModelSpec, TensorSpec from arachne.tools.torch2onnx import Torch2ONNX, Torch2ONNXCo...
# Generated by Django 2.2.8 on 2020-01-08 13:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('minke', '0005_auto_20190810_1412'), ] operations = [ migrations.AlterField( model_name='hostgroup', name='name', ...
from torch import nn class VentilatorNet(nn.Module): def __init__(self, input_dim: int = 4, lstm_dim: int = 256, dense_dim: int = 256, logit_dim: int = 256, n_classes: int = 1, ) -> None: """ Mode...
""" Reserve slots for teams. This module reserve slots for teams that have several competitors in the same brackets. In order to keep track of already existing team pairings it uses a dictionary: team_pairing_count. Is a dictionary of ordered tuples (min, max), with the count of times that...
# encoding: utf-8 # module Tessellation.Adapters calls itself Adapters # from Tessellation, Version=1.2.1.3083, Culture=neutral, PublicKeyToken=null # by generator 1.145 """ NamespaceTracker represent a CLS namespace. """ # no imports # no functions # classes class Cell2(TriangulationCell[Vertex2, Cell2]): ...
# Generated by Django 3.0.6 on 2020-05-22 04:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("teams", "0006_join_code_requires_less_states"), ("mediahub", "0006_require_fk_relationship"), ("events", "0005_make_fk_and_uuid_required"), ] ...
# -*- coding: utf-8 -*- import struct from src.crypt import gf28, sha256, crypt_modes from src.crypt.utils import rol_int_bytes, ror_int_bytes, get_byte_from_int, set_byte_in_int, add_padding_to_block, \ remove_padding_from_block __author__ = "zebraxxl" __sBox = [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0x...
''' Pandas Module for external dataframes Inherit and extend for particular patterns. It is a bit of a misnomer to use the term "dataframe", since there are very few expected attributes and they are by no means unique to pandas. ''' __author__ = 'Elisha Yadgaran' import pandas as pd from itertools import chain from...
"""The settings file migration base class.""" from typing import Dict from ...content_defs import ContentView from ...content_defs import SerializationFormat from ..ansi import COLOR from ..ansi import changed from ..ansi import info from ..serialize import Loader from ..serialize import serialize_write_file from .....
# syft relative from ..ast.globals import Globals from ..lib.python import create_python_ast from ..lib.torch import create_torch_ast from ..lib.torchvision import create_torchvision_ast from .misc import create_union_ast # now we need to load the relevant frameworks onto the node def create_lib_ast() -> Globals: ...
from abc import abstractmethod from dataclasses import dataclass from typing import Optional import pytest import sqlalchemy as sa from injector import ClassProvider from injector import inject from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import String fr...
from logger import logging, writelog import re def doc_preprocess(file_name): with open(file_name, 'r+') as file: text = file.read() # Remove comments (handled elsewhere but better safe than sorry) text = re.sub(r'(^.*?)(?=%.*$)', r'\0', text, flags=re.MULTILINE) # Remove \le...
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage def paginate(request, items, paginate_by=100): paginated_items = Paginator(items, paginate_by) page = request.GET.get('page', 1) try: page_items = paginated_items.get_page(page) except PageNotAnInteger: page_items...
import random import math async def message_to_xp(bot, discord, message, botconfig, platform, os, datetime, one_result, guild_result, localization, unix_time_millis, embed_color, connection, cursor, prefix): if len(message.content) > 10: #за каждое сообщение длиной > 10 символов... expi=one_result[8]+...
from qfunction import * from qfunction.quantum import * from qfunction.quantum.quantum_circuit import q_phi from numpy import sin,cos def q_vector_bloch(gamma,theta:float=False,q=1,israd=True): gamma,theta = radian(gamma) if(not israd) else gamma, radian(theta) if(not israd) else theta q = (q+1)/2 if(not(type(theta...
def textQueries(sentences, queries): sentences = [set(s.split(" ") for s in sentences)] queries = [q.split(" ") for q in queries] res = [] for q in queries: matches = [] for i in range(len(sentences)): isMatch = True for w in q: if w not in sentenc...
''' Thi is doc yes ''' a = 10
# Generated by Django 2.1.2 on 2018-11-11 17:28 import core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0009_user_user_type'), ] operations = [ migrations.AlterField( model_name='user', ...
class Solution: # @param tokens, a list of string # @return an integer def evalRPN(self, tokens): stack = [] for token in tokens: if token == '+': stack.append(stack.pop() + stack.pop()) elif token == '-': stack.append(-stack.p...
#main_test.py import unittest import main from unittest.mock import MagicMock, Mock class TestSolver(unittest.TestCase): """[summary] Args: unittest ([type]): [description] """ def etl_integration(self): main.load_naptan_data() pass def con_check_integration(self): ...
import unittest as u import os from lose import LOSE import lose import numpy as np import tables as t v = [int(i) for i in lose.__version__.split('.')] class Tests(u.TestCase): def setUp(self): if os.path.isfile('./temp.h5'): os.unlink('./temp.h5') self.l = LOSE('./temp.h5') def test_mk_group_valid(self):...
# flake8: noqa """ # 追加/更新股票基础信息 """ import os import sys import json from typing import Any from collections import OrderedDict import pandas as pd vnpy_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) if vnpy_root not in sys.path: sys.path.append(vnpy_root) os.environ["VNPY_TES...
# def too(*args, **kwargs) # host, port, user, user name and password to connect with data base # def connect_to_db(host, port, user, username, password, **kwargs) - splat operator # * is not a pointer like C # reference is copy by value .i.e you are passing a referernce who is having copy of value def swap(number...
from tests.test_base import app, client, login _SCRIPT_ID_HELLO = "pyscriptdemo.helloworld.HelloWorld" _SCRIPT_ID_HELLO_WITH_PARAMS = "pyscriptdemo.helloworld.HelloWorldWithParams" def test_hello(app, client): login(client) response = client.post("/api/scripts/" + _SCRIPT_ID_HELLO + "/_run") assert resp...
""" Support for Selve cover - shutters etc. """ import logging import voluptuous as vol from homeassistant.components.cover import ( CoverEntity, ATTR_POSITION, SUPPORT_OPEN, SUPPORT_CLOSE, SUPPORT_STOP, SUPPORT_OPEN_TILT, SUPPORT_CLOSE_TILT, SUPPORT_STOP_TILT, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION,...
from .tg_conv import TGConvModel from .tg_policy import TGPolicyModel from .tg_rec import TGRecModel
from templates.codepipeline.pipeline import NewPipeline from templates.pipeline_template import NewTemplate from troposphere import Template from tools.validates import change_yml_to_json import pytest import time import json import os import sys import shutil class TestCodePipeline: @pytest.fixture def param...
from config import Config from ..datastore import db from ..user import HasUser from datetime import datetime from sqlalchemy_utils import EncryptedType class Vendor(db.Model, HasUser): id = db.Column(db.Integer(), primary_key=True) slug = db.Column(db.Unicode()...
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-02-06 12:38 from __future__ import unicode_literals import autoslug.fields from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migr...
import SimpleITK import sys if len ( sys.argv ) < 4: print "Usage: MathematicalMorphology <input> <operation> <output>"; print "operation: 0=binary erode, 1=binary dilate, 2=grayscale erode, 3=grayscale dilate"; sys.exit ( 1 ) reader = SimpleITK.ImageFileReader() reader.SetFileName ( sys.argv[1] ) image...
"""Data analytics functions for processing neuroimaging data Functions: parse_volumes -> dataframe find_largest_volume -> tuple load_scan(path) -> array get_pixels_hu -> array show_scan extract_pixels -> array flatten -> array flat_wrapper -> array show_dist show_cluster_...
from conftest import add_permissions, check_json_response from core import cache, db from forums.models import ( Forum, ForumSubscription, ForumThread, ForumThreadSubscription, ) from forums.permissions import ForumPermissions def test_subscribe_to_forum(app, authed_client): add_permissions(app, '...
import numpy as np import xml.etree.ElementTree as ET import sys import glob import os import matplotlib.pyplot as plt tableau_colors = ( (114/255., 158/255., 206/255.), (255/255., 158/255., 74/255.), (103/255., 191/255., 92/255.), (237/255., 102/255., 93/255.), (173/255., 139/255., 201/255.), ...
import datetime as dt import json import logging import os import boto3 logger = logging.getLogger() logger.setLevel(logging.INFO) logging.basicConfig(format="%(asctime)s - %(message)s", level=logging.INFO) # Retrieve region where Lambda is being executed region_name = os.environ["AWS_REGION"] # "ap-southeast-1" #...
#!/usr/bin/python3 #sudo pm2 start led_manager.py --name led_manager --interpreter python3 import signal import time import sys import paho.mqtt.client as mqtt import json import random import subprocess import re import threading mqttClient = None canPublish = False connected_to_wifi = False charging_battery = Fals...
#!/usr/bin/env python3 """ NAME: lf_cleanup.py PURPOSE: clean up stations, cross connects and endpoints EXAMPLE: ./lf_cleanup.py --mgr <lanforge ip> Copyright 2021 Candela Technologies Inc License: Free to distribute and modify. LANforge systems must be licensed. """ import sys import os import importlib import arg...
# Copyright 2020 Dylan Baker # 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, sof...
"""Main library entrypoint.""" import copy import json import io import os import sys import random import numpy as np import tensorflow as tf from tensorflow.python.estimator.util import fn_args from google.protobuf import text_format from opennmt.utils import hooks, checkpoint, misc from opennmt.utils.evaluator ...
from setuptools import setup, find_packages from setuptools.extension import Extension try: from Cython.Distutils import build_ext USE_CYTHON = True except ImportError: USE_CYTHON = False import os packages = ['lely_io'] package_data = {} package_dir = {} for pkg in packages: package_data[pkg] = ['*....
''' Notes: https://stackoverflow.com/questions/12193013/flask-python-trying-to-return-list-or-dict-to-ajax-call ''' from flask import Flask, render_template from flask import jsonify import os from flask import request import time app = Flask(__name__) #app.register_blueprint() import base64 import ...
def default_config_path(agent_name, env_name): return 'configs/{}_{}.json'.format(agent_name, env_name) def default_save_folder(agent_name, env_name): return '{}_{}_save_point'.format(agent_name, env_name) __all__ = ['default_config_path', 'default_save_folder']
#!/usr/bin/env python # -*- encoding: utf-8 -*- import os from functools import partial from pathlib import Path import pytest import torch.cuda import torch.distributed as dist import torch.multiprocessing as mp from torch.utils.data import DataLoader import colossalai from colossalai.builder import build_dataset, ...
from __future__ import absolute_import, division, print_function, unicode_literals import torch from tests import utils class SimpleAbsModule(torch.nn.Module): def __init__(self): super(SimpleAbsModule, self).__init__() def forward(self, a): return torch.abs(a + a) class TestAbs(utils.Torc...
# create a simple dictionary myDict = {"key1":1, "key2":2, "key3":3} print myDict print myDict["key1"] print " " # add a key:pair -- notice that the values can be any data type myDict["newkey"] = "new" print myDict # and so can the keys myDict[5] = 5 print myDict print " " # loop over the elements for k, v in myD...