content
stringlengths
5
1.05M
#!/usr/bin/env python """ Requirements: * Python >= 3.6.2 * Pandas * NumPy Copyright (c) 2020 Georgios Fotakis <[email protected]> MIT License <http://opensource.org/licenses/MIT> """ RELEASE = False __version_info__ = ('0', '3', ) __version__ = '.'.join(__version_info__) __version__ += '-dev...
# Python import re # Django from django.core.validators import RegexValidator from django.db import models from django.utils.timezone import now from django.utils.translation import ugettext_lazy as _ # Django OAuth Toolkit from oauth2_provider.models import AbstractApplication, AbstractAccessToken DATA_URI_RE = re...
import configparser from os import path class Config: def __init__(self): self.config = None self.section = None def load(self, cfg_file, section): if not path.exists(cfg_file): raise FileNotFoundError() self.config = configparser.ConfigParser() self.conf...
import threading import __init__ import paho.mqtt.client as client_lib import time from sistem_climatizare.senzori_centralizare.basic_sensor import BasicSensor class Display(threading.Thread): @staticmethod def fnc_activa(client, user_data, message): print("Temperatura primita: ", str(message.payload...
from tkinter import * root = Tk() class Cell (Button): Dead = 0 Live = 1 def __init__ (self,parent): Button.__init__(self,parent, relief = "raised" , width = 2 , borderwidth = 1 , command = self.onpress) self.displayState(Cell.Dead) def onpress (self): if self.stat...
import json import unittest from localstack.utils.aws import aws_stack from localstack.utils.common import short_uid TEST_QUEUE_NAME = 'TestQueue' TEST_POLICY = """ { "Version":"2012-10-17", "Statement":[ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "sqs:SendMessage", "...
def relevant_paths(root_dir, only_title, only_part): """We may want to filter the paths we search in to those relevant to a particular cfr title/part. Most index entries encode this as their first two path components""" prefix_path = root_dir.path for sub_entry in root_dir.sub_entries(): suf...
import math import torch import torch.nn as nn import torch.nn.functional as F from models.flowplusplus.act_norm import ActNorm from models.flowplusplus.act_norm import CondNorm from models.flowplusplus.inv_conv import InvConv from models.flowplusplus.nn import GatedConv from models.flowplusplus.coupling import Coupli...
#%% import datetime import ephem import time import urllib.request from dateutil import tz import libs.rigctllib as rigctllib from sys import platform from RPLCD import i2c from config.satlist import SAT_LIST import json from libs.satlib import * from libs.lcdlib import * import RPi.GPIO as GPIO gpio_pins = ["CLK", "D...
import os import svg_tools try: columns, rows = os.get_terminal_size(0) except OSError: columns, rows = os.get_terminal_size(1) def print_centered(text): print(text.center(columns)[:-1]) print_centered("~~~ SVG to GD ~~~") print_centered("Made by jaan and camila314") print() print_centered("It's recom...
#!/usr/bin/env python3.6 """ Purpose: Script responsible for helping organize music files in a specified directory and of a specific music filetype Steps: - Parse Location of Music from CLI - Determine Music Extension (Default .mp3) - Find all music files in the directory...
import numpy as np def findPaperLen(pairs): max_x = 0; max_y = 0; for (x, y) in pairs: if x > max_x: max_x = x if y > max_y: max_y = y return (max_x, max_y) def day13_part1(paper, foldcmd): (axis, val) = foldcmd if axis == 'y': top = paper[:...
from bs4 import BeautifulSoup from requests import get import json def contact_scrape(link,output): key = ['name','email','twitter','facebook','instagram','youtube'] val = [] soup = BeautifulSoup(get('https://su.sheffield.ac.uk' + link).text, 'html.parser') #======================# # Extract s...
#!/usr/bin/python3 import timeit import time import os import matplotlib.pyplot as plt from tqdm import trange from injectSeed import * from subprocess import call def getRuntime(bytecode): """ executes program and returns running time """ start = time.time() exec(bytecode) end = time.time() return...
from p5 import * class Slider: def __init__(self,low,high,default): '''slider has range from low to high and is set to default''' self.low = low self.high = high self.val = default self.clicked = False def position(self,x,y): '''slide...
#!/usr/bin/env python # # Copyright 2018 Espressif Systems (Shanghai) PTE LTD # # 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 req...
#!/usr/bin/python # -*- coding: utf-8 -*- # # stride-ios-relay.py - Stride TCP connection relay for iOS devices to Windows developer host (using usbmuxd) # # Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) #...
# -*- coding: utf-8 -*- ''' .. created on 21.08.2016 .. by Christoph Schmitt ''' from __future__ import print_function, absolute_import, division, unicode_literals from reflexif.compat import * from reflexif.compat import PY2 import io import os import unittest from reflexif.io import Frame, SourceWrapper, FileSourc...
"""Unit tests for the Hyperbolic space using Poincaré Ball Model. We verify poincare ball model by compare results of squared distance computed with inner_product (using RiemannianMetric methods) and distance defined in PoincareBall. We also verify the distance is the same using differents coordinates systems. """ i...
#!/usr/bin/env python import os import yaml import pandas as pd import argparse __author__ = 'Teruaki Enoto' __version__ = '0.01' # v0.01 : 2020-08-12 : original version def get_parser(): """ Creates a new argument parser. """ parser = argparse.ArgumentParser('niauto.py', usage='%(prog)s -o obsid', descripti...
print "\nSTRINGS" s = 'hello' print ('h' in s) == True print ('H' in s) == False print ('e' not in s) == False print ('L' not in s) == True print ('hello' + ' world') == 'hello world' print 'a'*3 == 'aaa' print 2*'hello' == 'hellohello' s = '01234' print s[4] == '4' print s[-1] == '4' print s[0:3] == s[:3] == s[None:3]...
#Done by Carlos Amaral (20/07/2020) #try 15.5- Refactoring """ The fill_walk() method is lengthy. Create a new method called get_step() to determine the direction and distance for each step, and then calculate the step. You should end up with two calls to get_step() in fill_walk() : x_step = self.get_step() y_step =...
from torchtext import data import os class SST1Dataset(data.TabularDataset): dirname = 'data' @classmethod def splits(cls, text_field, label_field, train='phrases.train.tsv', validation='dev.tsv', test='test.tsv'): prefix_name = 'stsa.fine.' path = './data' return su...
from dataloader import dataloader from dataloader.db.session import mapping_session objectList = ['obj A', 'obj B'] #export sf = dataloader(instance = 'test', userName = '<source-username>', password = '<source-password>', securityToken = '<source-token>' )...
import sys from weird_mesh import getWeirdMesh argument = sys.argv[1] n = int(sys.argv[2]) maillages = {"cartesian": "o", "triangle": "/\\//", "checkerboard": "o+", "raf_loc": "o123456789"} xmin, xmax, ymin, ymax = 0., 1., 0., 1. if argument == "raf_loc": f = lambda x, y: 2 * (int(x > 0.5 and y < 0.5) + int(x > 0.75...
import pandas as pd import json def create_hourly_elective_prob_json( path_to_patient_df_csv: str, output_directory: str = "." ) -> pd.DataFrame: """ This function uses data from "patient_df.csv" to create "hourly_elective_prob.json". This is needed to create the forecast. It is important that "patien...
import datasetRead import dataInputFormat import pickle from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from datasetRead import Dataset from dataInputFormat import DataInput_Categorical, DataInput_L...
print(__file__) print("Loading isstools, preparing GUI...") import functools import isstools.xlive import collections import atexit import PyQt5 from bluesky.examples import motor motor.move = motor.set detector_dictionary = {colmirror_diag.name: {'obj': colmirror_diag, 'elements': [colmirror_diag.stats1.total.nam...
def suggest_params(trial): dropout = trial.suggest_float('dropout', 0, 0.3, step=0.05) # used twice activation = trial.suggest_categorical('activation', ['linear', 'leakyrelu']) # used for conditional sampling rna_hidden = trial.suggest_int('rna_hidden', 500, 2000, step=250) # hdim should be less than rn...
import copy import torch from federatedscope.core.auxiliaries.optimizer_builder import get_optimizer from federatedscope.core.trainers.trainer import GeneralTorchTrainer from federatedscope.core.optimizer import wrap_regularized_optimizer from typing import Type def wrap_DittoTrainer( base_trainer: Type[Gen...
from __future__ import print_function, unicode_literals, absolute_import __all__=["emacs", "notemacs", "vi"] from . import emacs, notemacs, vi editingmodes = [emacs.EmacsMode, notemacs.NotEmacsMode, vi.ViMode] #add check to ensure all modes have unique mode names
# # The Template-Python distribution is Copyright (C) Sean McAfee 2007-2008, # derived from the Perl Template Toolkit Copyright (C) 1996-2007 Andy # Wardley. All Rights Reserved. # # The file "LICENSE" at the top level of this source distribution describes # the terms under which this file may be distributed. # ...
import numpy as np import torch from torch.autograd import Variable from tqdm import tqdm import utils from Classifiers.Fashion_Classifier import Fashion_Classifier from Classifiers.Mnist_Classifier import Mnist_Classifier from Classifiers.Cifar_Classifier import Cifar_Classifier from Data.load_dataset import load_dat...
from django.conf.urls import patterns, url from django.utils.translation import ugettext_lazy as _ from connect.discover import views urlpatterns = patterns( '', url(_(r'^map/$'), views.member_map, name='map'), )
from django.db.models import Model, CharField, DecimalField class LeasingMode(Model): """yearly and weekly costs to own a vehicle""" name = CharField(max_length=127) factor_yearly = DecimalField(max_digits=4, decimal_places=2) factor_weekly = DecimalField(max_digits=4, decimal_places=2) def __str...
from tensorflow import keras import tensorflow as tf from tensorflow.keras.applications import vgg16 from tensorflow.keras.layers import Input def get_loss_network(): loss_net = vgg16.VGG16(include_top=False, weights="imagenet", input_tensor=Input(shape=(256,256,3))) loss_net_outputs = dict([(layer.name, laye...
# Copyright 2021 Huawei Technologies Co., Ltd # # 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...
from go_ml_transpiler.model.xgboost.regressor import Regressor from go_ml_transpiler.utils.model.xgboost import build_tree import os class XGBRegressor(Regressor): SUPPORTED_OBJECTIVE = [ "reg:linear" ] SUPPORTED_BOOSTER = [ "gbtree", "dart", ] def __init__(self, model, ...
from dataclasses import dataclass from typing import List, Optional @dataclass class User: id: int username: str nickname: Optional[str] = "" avatar: str = None email: Optional[str] = None school: Optional[str] = None def __repr__(self) -> str: return f"<User {self.username}>" ...
#!/usr/bin/python3 # 文件名:mysql_createtable.py import pymysql # 打开数据库连接 db = pymysql.connect('localhost','root','1234','fdtest') # 使用cursor()方法创建一个游标对象cursor cursor = db.cursor() # 使用execute() 方法执行SQL查询 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # 使用预处理语句创建表 sql = """CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20...
#Parts of code in this file have been taken (copied) from https://github.com/ml-jku/lsc #Copyright (C) 2018 Andreas Mayr nrLayers = hyperParams.iloc[paramNr].nrLayers nrNodes = hyperParams.iloc[paramNr].nrNodes basicArchitecture = hyperParams.iloc[paramNr].basicArchitecture nrInputFeatures = nrDenseFeatures + nrSparse...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayOpenAppYiyiyiwuQueryResponse(AlipayResponse): def __init__(self): super(AlipayOpenAppYiyiyiwuQueryResponse, self).__init__() self._chucan = None @property ...
def leiaInt(txt): while True: try: n = int(input(txt)) except: print('ERRO! DIGITE UM NÚMERO INTEIRO VÁLIDO!') else: break return n def leiaFloat(txt): while True: try: n = float(input(txt).replace(',', '.')) except: ...
""" Created by Epic at 9/1/20 """ import logging from asyncio import AbstractEventLoop __all__ = ("OpcodeDispatcher", "EventDispatcher") class OpcodeDispatcher: """ Receives events identified by their opcode, and handles them by running them through the event loop. Parameters ---------- loop: A...
from elasticsearch import Elasticsearch from elasticsearch.helpers import bulk from elasticsearch import helpers import json import time class ElasticSearchClient(object): # 实例和事务化单个node,若需要多个node,需要重构代码 def __init__(self, host="localhost", port=9200): self.host = host self.port = p...
import csv import encoding_fix import json ###if you don't have access to the API #### with open("data/residential_permits_2010-2016.json") as json_infile: bp_api_data = json.load(json_infile) json_infile.close() #read through the JSON file line by line and write it to CSV with open('data/residential_perm...
from pwn import * flag = input("flag: ").replace("\n", "") ip, port = input("service: ").split(":") r = remote(str(ip), int(port)) r.sendline("l") r.sendline("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") r.sendline("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbtaw") r.sendline("n") r.sendline("Fetch watpop KNAAN 𝓯𝓵𝓪𝓰") res = str(r.recvunt...
"""User API endpoints test module.""" from tests import utils class UserAPITests(utils.APITestBase): """User API integration tests."""
__title__ = "mpsiem_api" __description__ = "Basic MaxPatrol SEIM API wrapper" __version__ = "0.0.2"
import typing import discord from discord.ext import commands class Guilds(commands.Cog): def __init__(self, client): self.client = client async def on_guild_join(self, guild): channel = self.client.get_channel(604741076900642826) await self.client.pool.execute('''INSERT INTO guilds(...
from pathlib import Path from pylexibank.dataset import Dataset as BaseDataset from pylexibank.util import pb from pylexibank.forms import FormSpec # Customize your basic data. # if you need to store other data in columns than the lexibank defaults, then over-ride # the table type and add the required columns e.g. # ...
from abc import ABC, abstractmethod from collections.abc import Mapping from typing import Any, Optional __all__ = ["Client"] class Client(ABC): @abstractmethod async def request( self, method: str, url: str, *, headers: Optional[Mapping[str, str]] = None, ) -> Any...
#! python3 import spiceypy as spice import numpy as np from numpy.linalg import norm if __name__ == "__main__": #1. spice.furnsh('lessons/insitu_sensing/kernels/lsk/naif0012.tls') cass = -82 utc = '2004-06-11T19:32:00' et = spice.utc2et(utcstr=utc) print(f'Date and Time: {utc}') print(f'I...
from crypto.constants import TRANSACTION_TIMELOCK_TRANSFER from crypto.transactions.builder.base import BaseTransactionBuilder class TimelockTransfer(BaseTransactionBuilder): transaction_type = TRANSACTION_TIMELOCK_TRANSFER def __init__(self, fee=None): """Create a timelock transaction Args...
solution = NumberOfValidWordsForEachPuzzle() assert X == solution.findNumOfValidWords( )
import torch from new_model import NetworkNew import argparse import torch.backends.cudnn as cudnn parser = argparse.ArgumentParser(description='PyTorch Digital Mammography Training') parser.add_argument('--group_id', default=0, type=int, help='the id of compressed layer, starting from 0') args = parser.parse_args() ...
import os import re import tempfile from datetime import date import chirps import geopandas as gpd import pytest import rasterio import responses from click.testing import CliRunner from fsspec.implementations.http import HTTPFileSystem from fsspec.implementations.local import LocalFileSystem from s3fs import S3FileS...
# Copyright 2014 Baidu, Inc. # # 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, softwa...
import pytest from d3rlpy.argument_utility import ( check_action_scaler, check_encoder, check_q_func, check_scaler, check_use_gpu, ) from d3rlpy.gpu import Device from d3rlpy.models.encoders import DefaultEncoderFactory from d3rlpy.models.q_functions import MeanQFunctionFactory from d3rlpy.preproce...
import pickle import os import sys import time import numpy as np from colorama import Fore, Back, Style from ACSN_processing import ACSN_processing from ACSN_initialization import ACSN_initialization from ACSN_processing_parallel import ACSN_processing_parallel from ACSN_processing_video import ACSN_process...
import os.path from SConsRevision import SCons_revision from Utilities import is_windows, whereis, platform, deb_date from zip_utils import unzipit, zipit, zcat from soe_utils import soelim, soscan, soelimbuilder # from epydoc import epydoc_cli, epydoc_commands from BuildCommandLine import BuildCommandLine gzip = whe...
import os import sys import numpy as np import keras from keras_bert import load_vocabulary, load_trained_model_from_checkpoint, Tokenizer from keras_bert.layers import MaskedGlobalMaxPool1D if len(sys.argv) != 2: print('python load_model.py UNZIPPED_MODEL_PATH') sys.exit(-1) print('This demo demonstrates ho...
import numpy as np import os.path as osp import cv2 import torch import torch.nn.functional as F from pointmvsnet.utils.io import mkdir from pointmvsnet.functions.functions import get_pixel_grids def file_logger(data_batch, preds, step, output_dir, prefix): step_dir = osp.join(output_dir, "{}_step{:05d}".format...
import re test_string = "123qwe678 -ABC91011- vyz"
from __future__ import print_function import numpy as np import yt from hyperion.model import Model import matplotlib as mpl mpl.use('Agg') import powderday.config as cfg from powderday.grid_construction import arepo_vornoi_grid_generate from hyperion.dust import SphericalDust from powderday.helpers import energy_...
# -- coding: utf-8 -- import tensorflow as tf import scipy.sparse as sp import pandas as pd import numpy as np def get_position(num_roads=49): ''' :return: shape is [1, 49] 49 represents the numbers of road ''' return np.array([[i for i in range(num_roads)]], dtype=np.int32) def sparse_to_tuple(s...
''' @Title: Exploring ruins @Problem Statement: Edward is playing a simplified version of game called "Dorsplen". This game is played with gems of three different colors: red, green and blue. Initially player has no gem and there are infinitely many gems of each color on the table. On each turn a player can either...
# 1.15 通过某个字段将记录分组 rows = [ {'address': '5412 N CLARK', 'date': '07/01/2012'}, {'address': '5148 N CLARK', 'date': '07/04/2012'}, {'address': '5800 E 58TH', 'date': '07/02/2012'}, {'address': '2122 N CLARK', 'date': '07/03/2012'}, {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'}, {'addres...
import logging logger = logging.getLogger(__name__) import os import pipeline.libs.config as cfg import maya.mel as mel import maya.cmds as cmds import pymel.core as pm # import pipeline.libs.meta as meta import pipeline.maya_libs.maya_warpper as maya import pymel.core.nodetypes as nt # def create_group(name, parent=...
from mongoengine import Q from mist.api.tag.models import Tag from mist.api.helpers import trigger_session_update from mist.api.helpers import get_object_with_id def get_tags_for_resource(owner, resource_obj, *args, **kwargs): return [{'key': tag.key, 'value': tag.value} for tag in Tag.objects(owner=o...
''' shift registers type:class\n name-format: shift_register_[name]\n SIPO\n PISO\n SISO\n PIPO ''' '''SIPO''' class shift_register_SIPO(): def __init__(self,level,inputno = None): self.level = level self.inputno = inputno def sr_set(self,inputno): #list inpu...
import numba as nb import pytest from numba.typed import Dict from respy.parallelization import _infer_dense_keys_from_arguments from respy.parallelization import _is_dense_dictionary_argument from respy.parallelization import _is_dictionary_with_integer_keys def _typeddict_wo_integer_keys(): dictionary = Dict.e...
#!/usr/bin/python # Copyright (c) 2014 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """This script handles all of the processing for versioning packages. package_version.py manages all of the various operations do...
""" Copyright © retnikt <[email protected]> 2020 This software is licensed under the MIT Licence: https://opensource.org/licenses/MIT """ import secrets from typing import TYPE_CHECKING, List, Optional, Union from argon2 import ( # type: ignore DEFAULT_MEMORY_COST, DEFAULT_PARALLELISM, DEFAULT_TIME_COST, ) fro...
import time import os from funboost import boost @boost('test_f1_queue', qps=0.5) def f1(x): time.sleep(3) print(f'x: {x}') for j in range(1, 5): f2.push(x * j) @boost('test_f2_queue', qps=2) def f2(y): time.sleep(5) print(f'y: {y}') if __name__ == '__main__': f1.clear() f2.cl...
from django.conf.urls import url from . import views urlpatterns= [ url(r'^hello-view',views.HelloApiView.as_view()), ]
from dockit.backends.indexer import BaseIndexer from backend import MongoIndexStorage try: from bson.objectid import ObjectId except ImportError: from pymongo.objectid import ObjectId class MongoIndexer(BaseIndexer): def _get_key_value(self): dotpath = self.filter_operation.dotpath() valu...
def main(): numbers = sorted([int(x) for x in input().split()]) diffs = [numbers[i+1] - numbers[i] for i in range(len(numbers) - 1)] if diffs[0] == diffs[1]: print(max(numbers) + diffs[0]) else: if diffs[0] > diffs[1]: print(numbers[0] + diffs[1]) else: ...
# import setup import os.path import json import sys if __name__ == "__main__": assert sys.version_info >= (3, 7), "Minimum Python version: 3.7.0" """ if not os.path.exists("./configinfo.json"): with open("./configinfo.json", "w") as configinfo_json: json.dump({"first_time_setup": False...
int_ = 2 list_ = [1, 2, 3]
""" add account_session table """ from yoyo import step __depends__ = {'20210808_01_sS1X2-add-table-for-processed-sub-ids'} steps = [ step(""" CREATE TABLE account_session ( id serial primary key, account_id int not null references account(id), service varchar(20) not ...
#!/usr/bin/python # -*- coding: utf-8 -*- from app.models.tables import Role as RoleTable class Role: pass
import time import os import math import argparse from glob import glob from collections import OrderedDict import random import warnings from datetime import datetime import joblib from tqdm import tqdm import numpy as np import pandas as pd from sklearn.model_selection import KFold, StratifiedKFold import facenet imp...
# -*- coding: utf-8 -*- """ @brief test log(time=60s) """ import sys import os import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, is_travis_or_appveyor from pyquickhelper.pycode import fix_tkinter_issues_virtualenv from pyquickhelper.ipythonhelper import exe...
# ---------------------------------------------------------------------- # OID Rule Loader # ---------------------------------------------------------------------- # Copyright (C) 2007-2018 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Python modul...
# -*- coding: utf-8 -*- from base64 import urlsafe_b64encode, urlsafe_b64decode from Cryptodome import Random from Cryptodome.Util import Padding from Cryptodome.Cipher import AES from conf import conf class AESCipher: def __init__(self): self.key = conf['SECRET_KEY']['secret_key'].encode() def enc...
from pytransform import pyarmor_runtime pyarmor_runtime() __pyarmor__(__name__, __file__, b'\x50\x59\x41\x52\x4d\x4f\x52\x00\x00\x03\x09\x00\x61\x0d\x0d\x0a\x08\x2d\xa0\x01\x00\x00\x00\x00\x01\x00\x00\x00\x40\x00\x00\x00\x2d\x7c\x00\x00\x00\x00\x00\x18\xa3\x54\xc0\x8b\xd9\xf4\x9f\x8f\x59\x62\xb7\xbb\xfb\x46\x82\xe7\x...
from flask import Blueprint, render_template, request, redirect, url_for, flash from .forms import LoginForm, RegisterForm from flask_login import login_user, logout_user, login_required from ..models import User from .. import db main = Blueprint('main', __name__) @main.route('/', methods=['GET']) def index(): ...
import numpy as np import cv2 # create a VideoCapture object cap = cv2.VideoCapture('kntu-computer.avi') # sometimes this is needed: #if not cap.isOpened(): # cap.open(); while True: # Capture frame-by-frame ret, I = cap.read() if ret == False: # end of video (perhaps) break # ...
""" services.py: queries models to get required inputs to launch a task in the background. - this scripts abstracts the functions specified in tasks.py """ import uuid from io import StringIO import os import pandas as pd from django.urls import reverse from django.contrib.sites.shortcuts import get_current_site from ...
import _plotly_utils.basevalidators class FitboundsValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="fitbounds", parent_name="layout.geo", **kwargs): super(FitboundsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_nam...
from enum import Enum from typing import cast, Union, List from typing_extensions import Literal from pydantic import BaseModel, Field from .constrained_types import UnitFloat, PositiveInt from .shared_blocking_config import BlockingConfigBase class PSigFilterConfigBase(BaseModel): type: str class PSigFilterR...
""" spider to get pratices of china.cssc.org """ import requests from bs4 import BeautifulSoup from flask import Flask, request app = Flask(__name__) global href_list href_list = [] global base_url base_url = "" def get_raw_html(url): """get raw html from url""" response = requests.get(url) response.enc...
""" Tests for calculations """ from __future__ import print_function from __future__ import absolute_import import aiida_qeq.tests as tests from aiida.engine import run # pylint: disable=too-many-arguments,unused-argument def test_submit(aiida_profile, clear_database, ionization_file, charge_file, h...
""" Docstring .. pii: A long description that spans multiple lines .. pii_types: id, name """
# -*- coding: utf-8 -*- """ Created on Fri Feb 22 10:20:10 2019 @author: lwg """ # http://www.numpy.org/ import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1+np.exp(-x)) x = np.arange(-5.0, 5.0, 0.1) y = sigmoid(x) plt.plot(x, y) plt.ylim(-0.1, 1.1) # y轴范围 plt.show()
from forcuanteller.main import loader, transformer, reporter, sender from forcuanteller.main.utils.config import config from forcuanteller.main.utils.gmail import validate_gmail from forcuanteller.main.utils.logger import logger from forcuanteller.main.utils.runner import runner import schedule import time from forcua...
#!/usr/bin/env python3 import sys import os.path from setuptools import setup from subprocess import check_output import platform import warnings SDL_VERSION_NEEDED = (2, 0, 5) def get_version(): """Get the current version from a git tag, or by reading tcod/version.py""" try: tag = check_output( ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound from django.shortcuts import render import redis from django.views.decorators.csrf import csrf_exempt r_db = redis.StrictRedis(host='localhost', port=6379, db=0) # Creat...
# a small script which shows some of the possiblities of the # LKOpticalTrack filter # LKOpitcal is good low resource algorithm which is good at tracking points through a video # stream from org.myrobotlab.opencv import OpenCVFilterLKOpticalTrack # create services opencv = Runtime.createAndStart("opencv","OpenCV") #...