content
stringlengths
5
1.05M
import os from setuptools import find_packages, setup requirements = [ # mjolnir requirements 'requests', 'kafka-python<2.0', 'pyyaml', 'hyperopt<0.2.0', 'elasticsearch>=5.0.0,<6.0.0', 'jsonschema', 'prometheus_client', 'xgboost==0.90', # hyperopt requires networkx < 2.0, but d...
import requests data = { 'field': 'don\'t you like quotes', } response = requests.post('http://localhost:28139', data=data)
import random import math import numpy as np issortedAndUnique = lambda l: np.all([l[i] < l[i+1] for i in xrange(len(l)-1)]) class RandomArbitraryInteger(): '''Random integer numbers from an arbitrary distribution. This algorithm is based on Vose, A Linear Algorithm For Generating Random Numbers Wit...
""" makefolders.py --tkp Makes financial folders for a given year. Example usage: python makefinfolders.py --root /root -y 2016 --prefix "FY " /root /FY 2016 /2016-01 Jan /2016-02 Feb """ import argparse import os from datetime import datetime from time import str...
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI HealFrequency = 30.0 class SafeZoneManagerAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory('SafeZoneManagerAI') def enterSafeZone(self): avId = self.ai...
import pandas as pd import sqlite3 def hourly_to_daily_ERA5(DB_PATH): conn = sqlite3.connect(DB_PATH) sql = """ SELECT * FROM META_TS WHERE PAS_DE_TEMPS = "1_H" AND SOURCE = "ERA5" ORDER BY ID_SERIE """ df_sup1 = ...
import json import pathlib def get_value(key): with pathlib.Path(__file__).with_name('installation.json').open() as f: data = json.load(f) return data[key] def get_directory(key): path = pathlib.Path(__file__).parent.joinpath(get_value(key)) path.mkdir(parents=True, exist_ok=True) return...
"""HXL filter for previewing a dataset.""" import hxl class PreviewFilter(hxl.Dataset): """Show only up to the first n rows of a dataset.""" def __init__(self, source, max_rows=10): self.source = source self.max_rows = max_rows self.has_more_rows = False self.total_rows = 0 ...
import numpy as np import xobjects as xo import xtrack as xt import xpart as xp import ducktrack as dtk from scipy.constants import m_p as pmass_kg from scipy.constants import e as qe from scipy.constants import c as clight pmass = pmass_kg*clight**2/qe def test_beambeam(): for context in xo.context.get_test_co...
from tkinter import * from tkinter import filedialog import os import sys import time from tkinter import messagebox from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.s...
import jinja2 import jinja2.ext # canhaz block class CanHazExtension(jinja2.ext.Extension): """ Wraps a section of code in <script type="text/html" id="ID"> ID is a required argument. Example, using underscore/ejs:: {% canhaz "user" %} <div class="user"> <p><%= name %></...
from base import BasePartition class MSDOSPartition(BasePartition): """Represents an MS-DOS partition """ def __init__(self, size, filesystem, format_command, mountopts, name, previous): """ :param Bytes size: Size of the partition :param str filesystem: Filesystem the partition sh...
# Author: Jimmy Huang (1902161621@qq.com) # License: WTFPL import re import logging global g_logger g_logger = logging.getLogger('ECY_server') # local lib import ECY.utils.fuzzy_match as fm class Operate(object): def __init__(self): self.fuzzy_match = fm.FuzzyMatch() self.start_position = {} ...
# Author: Nam Nguyen Hoai # coding: utf-8 import logging from database import repos sqla_logger = logging.getLogger('sqlalchemy.engine.base.Engine') sqla_logger.disabled = True TEST_NAME = 'name' def main(): while True: session2 = repos.get_session_2() records = repos.get_records(session2, TEST_...
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Organization, OrganizationMember, OrganizationMemberRole class OrganizationMemberInline(admin.TabularInline): model = Organization.users.through extra = 0 @admin.register(Organization) class OrganizationAdmin(admin.ModelAdmin): #...
import numpy as np from sklearn.preprocessing import PolynomialFeatures X = np.arange(6).reshape(3, 2) poly = PolynomialFeatures(degree=2 , include_bias = True) poly.fit_transform(X) poly = PolynomialFeatures(interaction_only=True) poly.fit_transform(X)
import numpy as np from os import path import pytest import autoarray as aa from autoarray.mock.mock import ( MockLinearObjFunc, MockMapper, MockRegularization, MockLEq, MockInversion, ) from autoarray import exc directory = path.dirname(path.realpath(__file__)) def test__...
from troposphere import ( Parameter, Template, Equals, GetAtt, Ref, Sub ) from troposphere.awslambda import ( Function, LayerVersion, Permission, Alias, Version, Code, Environment ) from ozone.outputs import object_outputs from ozone.filters.arns import ( iam_ro...
# # default.py # # The default script run by the "Python" application in Series 60 Python # environment. Offers menu options for running scripts that are found in # application's directory, or in the \my -directory below it (this is # where the application manager copies the plain Python scripts sent to # device's inbo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import audioop import time import pyaudio class LoudSoundTrigger: CHUNK = 1024 THRESHOLD = 1000 CHANNELS = 1 RATE = 44100 def __init__(self, callback, *args, chunk=CHUNK, threshold=THRESHOLD, **kwargs): self.callback = callback self...
from __future__ import print_function from builtins import object class WfTemplate(object): def get_create_connection_template(self, params): create_connection = {'parameters': [{'description': 'Connection name', 'name': 'name', 'type': 'string', 'value': {'string': {'value...
#!/usr/bin/env python3 import argparse from collections import OrderedDict from gibson2.envs.igibson_env import iGibsonEnv import gym import numpy as np from . import render, datautils, pfnet_loss import sys def set_path(path: str): try: sys.path.index(path) except ValueError: sys.path.insert(...
from django.urls import path, include from rest_framework.serializers import CharField from baserow.api.user_files.serializers import UserFileField from baserow.core.user_files.handler import UserFileHandler from baserow.contrib.database.api.views.form.errors import ( ERROR_FORM_VIEW_FIELD_TYPE_IS_NOT_SUPPORTED, ...
import sys import os import pprint import numpy import getpass import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from sqlalchemy import create_engine from sqlalchemy import orm from utilities import hydroshare from odm2api.ODM2.services.readService import * from odm2api.ODM2.services.createSer...
import csv import os import sys from typing import Iterable from ..errors import InvalidDamageValueError, SeedNotFoundError from ..tracker import FFXRNGTracker from ..utils import s32 from .file_functions import get_resource_path def get_seed(damage_values: Iterable[int]) -> int: if len(damage_values) < DAMAGE_V...
import asyncio import os from typing import TYPE_CHECKING, Dict, NamedTuple from prometheus_client import CollectorRegistry, Gauge, write_to_textfile # type: ignore if TYPE_CHECKING: from txstratum.manager import TxMiningManager # Define prometheus metrics. # Key: str = name of the metric # Value: Tuple[str, C...
#!/usr/bin/env python import sys import os import time import traceback from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import WebDriverException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.r...
#!/bin/python3 # https://www.hackerrank.com/challenges/one-week-preparation-kit-balanced-brackets/ # import os def isBalanced(s): if len(s) % 2 != 0: # If the string is not even it's impossible for it to be balanced return "NO" stack = [ ] pairs = { "{":"}", "[":"]", ...
from rest_framework import serializers from rest_framework.serializers import HyperlinkedRelatedField from authentication.serializers import UserSerializer from authentication.models import Account from posts.models import Post, Comment, PostUpvote, CommentUpvote class PostSerializer(serializers.ModelSerializer): ...
"""pycstruct library pycstruct is a python library for converting binary data to and from ordinary python dictionaries or specific instance objects. Data is defined similar to what is done in C language structs, unions, bitfields and enums. Typical usage of this library is read/write binary files or binary data tran...
import os from inspect import getsourcefile import pytest from faker import Faker TEST_RESOURCES_ROOT = os.path.abspath( os.path.join(getsourcefile(lambda: 0), '..', 'fixtures') ) fake = Faker()
# Translating operators from/to Armory player from mathutils import Matrix import bpy import arm.utils import arm.make_state as state try: import barmory except ImportError: pass def parse_operator(text): if text == None: return cmd = text.split('|') # Reflect commands from Armory player in...
from copy import deepcopy import rastervision as rv from rastervision.command import (AnalyzeCommand, CommandConfig, CommandConfigBuilder, NoOpCommand) from rastervision.protos.command_pb2 \ import CommandConfig as CommandConfigMsg from rastervision.command.utils import (check_sce...
#!/usr/bin/python2 from app import app app.run(debug=True)
from src.database.datatypes import Datatype from src.database.table import Table import unittest class TableTest(unittest.TestCase): def test_cols_num(self): tab = Table("name") self.assertTrue(tab.cols_num() == 0) tab.add_column(("col1", Datatype.ITEGER)) self.assertTrue(tab.co...
# Generated by Django 3.1.4 on 2021-01-05 02:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('network', '0002_follower_post'), ] operations = [ migrations.AlterField( model_name='post', name='dislike', ...
#!/usr/bin/env pyhton # -*- coding: UTF-8 -*- __author__ = 'Chao Wu' __date__ = '8/26/2020' __version__ = '1.3' import os import re import numpy as np import pandas as pd from pandas import IndexSlice as idx from numpy.random import uniform, normal, choice from scipy.stats import alpha, beta, triang, pareto from py...
from __future__ import division, print_function from numpy import (zeros, zeros_like, ones_like, complex128, float64, dot, argwhere, where, sqrt, log, pi, abs, arange, exp, linspace) from scipy.linalg.lapack import zggev import itertools as it __all__ = ['generate_u', 'gen_amplitudes', 'solve_fdm', 'make_lore...
import cv2 import matplotlib.image as mpimg import numpy as np from skimage.feature import hog COLORS_SPACE_MAP = { 'RGB': lambda x: np.copy(x), 'HSV': lambda x: cv2.cvtColor(x, cv2.COLOR_RGB2HSV), 'LUV': lambda x: cv2.cvtColor(x, cv2.COLOR_RGB2LUV), 'HLS': lambda x: cv2.cvtColor(x, cv2.COLOR_RGB2HLS),...
""" MIT License Copyright (c) 2018 Breee@github 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 without restriction, including without limitation the rights to use, copy, modify, merge, publish, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- #---------------------------------------------------------------------------------------------------------------------------------- # includes # 2+3 compat from __future__ import absolute_import, division, print_function, unicode_literals # standards import json # alcaz...
#! /usr/bin/env python import rospy from ac_msgs.msg import drive_params from std_msgs.msg import Bool import time from sensor_msgs.msg import LaserScan msg = drive_params() msg.angle = 0.5 def lidar_callback(scans): distances = scans.ranges num_scans = len(distances) max_distance = 0.0 for sample in d...
class Solution(object): def numRookCaptures(self, board): """ :type board: List[List[str]] :rtype: int """ for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 'R': startx = i starty =...
from .NotifierClass import Notifier import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse, logging, json, re, random from urllib.parse import urlsplit class SlackNotifier(Notifier): def __init__(self,cfgParser,insec): self.header = insec self.webhook = cfgParser.get(inse...
# coding: utf-8 # DJANGO IMPORTS try: from django.conf.urls import url, patterns except ImportError: # for Django version less then 1.4 from django.conf.urls.defaults import url, patterns from django.views.generic.base import TemplateView from .views.related import RelatedLookup, M2MLookup, Autocomplete...
import time from django.shortcuts import redirect from datetime import datetime from rest_framework.views import APIView from pay_demo.utils.alipay import AliPay, AlipayAuthorization from config.settings.base import APP_PRIVATE_KEY, ALIPAY_PUBLIC_KEY, APP_NOTIFY_URL, RETURN_URL, APPID from django.conf import settings f...
from sqlalchemy import Boolean, Column, Integer, ForeignKey, String from sqlalchemy.dialects.mysql import INTEGER from sqlalchemy.orm import relationship from database import Base ''' # Default from sqlalchemy import Integer Integer: signed integer, length 11 # MySQL from sqlalchemy.dialects.mysql import INTEGER INT...
""" Employee class using property""" class Employee: """Employee class""" def __init__(self, name=''): # Constructor self.name = name @property def name(self): return self._name @name.setter def name(self, value): #validate if the value and then set the property...
# -*- coding: utf-8 -*- # Copyright (c) 2019, 2020 boringhexi """common.py - common utils and such for the gitarootools test suite""" import os from typing import Optional from PIL import Image from gitarootools.image.imximage import read_imx try: # noinspection PyProtectedMember from importlib import reso...
# Copyright 2021 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. """Functions for querying ResultDB, via the "rdb rpc" subcommand.""" import datetime import subprocess import json import re from typing import Optional, Tup...
#!/usr/bin/env python3.6 # -*- coding: utf-8 -*- # # Copyright 2015 Alec Golibroda # Впринцепе, Это "тулБокс" - ящик с инструментами просто пользователя # надо сюда добавить # список ПОльзователей # список Групп # # ArticleControl.py import bcrypt import concurrent.futures import os.path impo...
from flask import current_app from . import coinserv def payout_many(recip): fee = current_app.config['payout_fee'] current_app.logger.info("Setting tx fee: %s" % coinserv.settxfee(fee)) passphrase = current_app.config['coinserv']['wallet_pass'] if passphrase: wallet = coinserv.walletpassphra...
# -*-coding:Utf-8 -* # Copyright (c) 2014 LE GOFF Vincent # 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 # lis...
from ai.ai import AI class Strategy(AI): """Will indicate preferred fields""" def __init__(self, buttons, board, game, starter=True) -> None: self.buttons = buttons self.board = board self.game = game self.starter = starter self.opponent_sign = self.game.sign_player2 ...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------...
import skimage import os import random import matplotlib.pylab as plt from glob import glob import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from skimage import io from skimage.transform import rescale, resize def proc_image_dir(Images_Path): image_classes = sorted([...
nome = input('Qual o seu nome? ') print(f'Olá, seja bem vindo {nome}!')
import os import json import logging from datetime import datetime from dateutil import tz import time import inflection import splunklib.client as splunk_client import util from dateutil import parser logger = logging.getLogger('cloud_log_poller') class SplunkTransport: def __init__(self, config): self.config...
import os import errno import json from datetime import datetime def validate_or_make_directory(directory_string): """ Check if a directory exists. If it doesn't, then create it. :param directory_string: The relative directory string (ex: ../.config/secrets.json) :type directory_string: str """ ...
# Exercício de tabuada utilizando comando for. n = int(input('Digite um número inteiro: ')) for c in range(1, 11): print('{} x {} = {}'.format(n, c, n*c))
import json base_raw = """ { "name": "sim-hist-2-%d", "description": "Using different histogram approaches for index selection. Index out of bounds error in equiwidth and not enought time for voptimal. Out of time issues. Added more details for statistics. And optimal performance overall stats", "github_url...
from rest_framework import serializers from waypoints.models import Waypoint from .models import Carrier, PostalCode, Address, Contact, Shipment, ExternalShipment from .models import State class StateSerializer(serializers.ModelSerializer): """ Serializer that allows you to get the details of a given state. ...
# coding: utf-8 """ Mux Python - Copyright 2019 Mux Inc. NOTE: This class is auto generated. Do not edit the class manually. """ from __future__ import absolute_import import unittest import mux_python from mux_python.models.list_filter_values_response import ListFilterValuesResponse # noqa: E501 from mux_python...
def reverseToSort(inputArray): for i in range(len(inputArray)): for j in range(i + 1, len(inputArray) + 1): left = inputArray[:i] middle = inputArray[i:j] middle.reverse() right = inputArray[j:] result = [] correct = True ...
from easygraphics.turtle import * def inner_tri(size, level): if level == 0: return fd(size / 2) rt(60) inner_tri(size / 2, level - 1) lt(60) fd(size / 2) rt(120) fd(size) rt(120) fd(size) rt(120) create_world(800, 600) set_speed(100) setxy(-300, -250) rt(30) i...
from plugins.polio.preparedness.calculator import get_preparedness_score from django.db.models import fields from rest_framework import serializers from iaso.models import Group, OrgUnit from .models import Preparedness, Round, Campaign from .preparedness.parser import ( open_sheet_by_url, get_regional_level_pr...
def area(a, b): terreno = (a * b) print(f'A área de um terremo com {a} de largura e {b} de comprimento é {terreno} m².') larg = float(input('Insira a largura do seu terreno em metros: ')) comp = float(input('Insira o comprimento do seu terreno em metros: ')) area(larg, comp)
import numpy as np from tqdm import tqdm from concurrent.futures import ThreadPoolExecutor from transE import distanceL1 h_rank = [] t_rank = [] def worker_h(triple, entityList, relationList, entityVector, relationVector): h, t, r = triple h_vec, t_vec, r_vec = entityVector[h], entityVector[t], r...
class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ p, q = 1, x while abs(p-q) > 0.001: p = (p+q) / 2 q = x / p return int((p+q)/2)
# Разработать класс SuperStr, который наследует функциональность стандартного типа str и содержит 2 новых метода: # 1. метод is_palindrome(), который возвращает True или False в зависимости от того, # является ли строка палиндромом. Регистрами символов пренебрегать. # Пустую строку считать палиндромом. # 2. метод onl...
# -*- coding: utf-8 -*- """ Solution to Project Euler problem X Author: Jaime Liew https://github.com/jaimeliew1/Project_Euler_Solutions """ from collections import Counter suits = ('H','C','S','D') values = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'T':10,'J':11,'Q':12,'K':13,'A':14} hands = {'HC':100,'P':20...
from unittest import TestCase from os.path import join, dirname from pyspark.sql import dataframe from iod.data import SparkDataWrangler class TestSparkDataWrangler(TestCase): datawgl = SparkDataWrangler() def test_init(self): df: dataframe = self.datawgl.create_file_datasource(join(dirname(__file...
#! /usr/bin/python3 # # Copyright (c) 2017 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 import ttbl.power target = ttbl.test_target("t0") ttbl.config.target_add(target) target.interface_add( "power", ttbl.power.interface( ( 'ex', ttbl.power.fake_c(explicit = 'both') ), ( 'fp1', ttbl.p...
from django.db import migrations, models from django.contrib.postgres.fields import ArrayField from api.semantic_search.semantic_search import semantic_search_instance class Migration(migrations.Migration): dependencies = [ ('api', '0008_remove_image_path'), ] operations = [ migratio...
# coding: utf-8 __author__ = 'salvia' from queue import Empty from socketserver import TCPServer, StreamRequestHandler, ThreadingMixIn from _socket import SHUT_RDWR import socket from functools import partial from socket import error from multiprocessing import Process, Value, Queue import sys import select import err...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import subprocess from cpt.packager import ConanMultiPackager def get_branch(): try: for line in subprocess.check_output("git branch", shell=True).decode().splitlines(): line = line.strip() if line.startswith("*") a...
from typing import Union # Worker name per weekday name WORKER_BY_WEEKDAY = { "Monday" : "James", "Tuesday" : "John", "Wednesday": "Robert", "Thursday" : "Michael", "Friday" : "William" } def task(weekday: str, number: int, cost: Union[int,float]) -> str: name = WORKER_BY_WEEKDAY[weekday]...
from functools import reduce import numpy as np from geoprocessing.raytracing.renderer import L, E, rgb, raytrace class PhongMat: def __init__(self, color, refractive=0.5): self.diffuse = color self.refractive = refractive def diffuse_color(self, M): return self.diffuse...
import time import glob import parse from Crispin.bash import bash_command import Crispin.bash as bash from Function_Module import perc, curr, ptime def fname(archive): return 'models_GBB/nodedata/{}.dat'.format(archive) def nd_cat(nf, *ofs): if len(ofs) == 1 and hasattr(ofs[0], '__iter__'): nd_ca...
#!/usr/bin/env python from setuptools import setup setup( # Application name: name='download_espa_order', # Version number: version='2.1.0', # Application author details: author='David V. Hill', license=open('LICENSE.txt').read(), description='Client for downloading ESPA scenes.', ...
"""empty message Revision ID: 09012561ef02 Revises: Create Date: 2021-03-09 18:35:03.835368 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '09012561ef02' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
from socket import ( socket, SOCK_DGRAM, SOL_SOCKET, SO_REUSEADDR, SOCK_STREAM, SO_BROADCAST, ) from time import sleep from json import dumps, loads from threading import Thread, Semaphore from inspect import signature from io import BytesIO from functools import wraps from hashlib import sha1 f...
import os import sys import shutil from vseq.settings import DATA_DIRECTORY, SOURCE_DIRECTORY dataset = sys.argv[1] assert isinstance(dataset, str) and len(dataset) > 0 data_dir = os.path.join(DATA_DIRECTORY, dataset) sourcefile_dir = os.path.join(SOURCE_DIRECTORY, dataset) assert os.path.exists(data_dir), "Datase...
#!/usr/bin/env python # LICENSE # # Copyright (C) 2010-2018 GEM Foundation, G. Weatherill, M. Pagani, D. Monelli # # The Hazard Modeller's Toolkit (openquake.hmtk) is free software: you can # redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by the Free Software Fo...
import numpy as np import os import csv import physics as phys import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from matplotlib.pyplot import figure import matplotlib.pylab as pylab import DataAnalysis as Data import utils import GenerationRate.BandToBandTunneling as BTB from scipy.optimize imp...
"""Test user module functionality.""" import base64 import json import unittest import flask from googleapiclient import errors from mock import MagicMock from mock import patch from werkzeug.datastructures import MultiDict from werkzeug.datastructures import ImmutableMultiDict import ufo from ufo import base_test fr...
from sqlite3 import Connection class SiDB(Connection): def __init__(self, database): self.database = database super(self.__class__, self).__init__(self.database) self.cursor = self.cursor() def insert(self, table, data): """Inserts data in the table and returns ID of the last ...
from django.urls import path, include from rest_framework.routers import DefaultRouter from activity import views router = DefaultRouter() router.register('activities', views.ActivityViewSet) app_name = 'activity' urlpatterns = [ path('', include(router.urls)) ]
import itertools from collections import defaultdict import re import random from NumberAnalysysBase import NumberAnalysisBase class PowerBallAnalysis (NumberAnalysisBase): pickedFile = "numberValidation/PowerballPicked.txt" def __init__(self): super().__init__(self) class SuperLottoAnalysis (N...
# SPDX-FileCopyrightText: Copyright (c) 2020 ladyada for Adafruit Industries # # SPDX-License-Identifier: MIT import time import busio import board import adafruit_aw9523 i2c = busio.I2C(board.SCL, board.SDA) aw = adafruit_aw9523.AW9523(i2c) print("Found AW9523") # set all pins to be inputs aw.directio...
from flask import Flask, render_template, request, make_response, Response app = Flask(__name__) #default page of our web-app @app.route('/') def home(): return render_template('index.html') #Starting the Flask Server if __name__ == '__main__': app.debug = True app.run()
from typing import Union x: Union[int, str] x = "7" x = 3 x = []
import setuptools with open("README.rst", "r") as fh: long_description = fh.read() setuptools.setup( name='pynmsnn', version='0.0.3', scripts=['pynmsnn_package'], install_requires=[ "pandas", "numpy", "torch", "seaborn", "xgboost", "scipy", "...
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class AdvertsAppConfig(AppConfig): name = 'apps.adverts' verbose_name = _('Adverts')
r""" Visualization ############# **Create Basic Views** This module contains functions for quickly visualizing 3D images in 2D views. .. currentmodule:: porespy .. autosummary:: :template: mybase.rst :toctree: generated/ visualization.bar visualization.imshow visualization.prep_for_imshow vi...
# create 6 VMs and register them to a application load balancer import boto3 import sys import time INST_NUM = 6 ec2 = None key = None def createSecurityGroup(gname, ports): print("Create security group") try: sg = ec2.create_security_group( Description='boto3 allow ' + ' '.join(str(n) for...
import uvicorn if __name__ == '__main__': uvicorn.run("qa_serve.app:app", workers=3)
import os import cv2 import time import numpy as np import matplotlib.pyplot as plt def get_position_by_threshold(video_name, hours = 1, threshold = 70, fps = 25): K_0 = 0 num_frame = int(fps * 60 * 60 *hours) position = [] videoCapture = cv2.VideoCapture(video_name) for K_0 in range(nu...
import threading from time import sleep import zmq from databasemanager import DatabaseManager from decorators.singleton import Singleton @Singleton class NewNodePublisher(threading.Thread): context = None publisher = None def __init__(self): threading.Thread.__init__(self) self.daemon =...
import os import time from gluon.scheduler import Scheduler db_dal = os.path.abspath(os.path.join(request.folder, '..', '..', 'dummy2.db')) sched_dal = DAL('sqlite://%s' % db_dal, folder=os.path.dirname(db_dal)) sched = Scheduler(sched_dal, max_empty_runs=15, migrate=False, heartbeat=1) def termination(): ...