content
stringlengths
5
1.05M
#//////////////////////////////////////////////////////////////////// #//////////////////////////////////////////////////////////////////// # script: fusionDetectionPipelineManual.py # author: Lincoln # date: 1.9.19 # # FUCK REFLOW # usage: # ipython fusionDetectionPipelineManual.py # # RUN FROM SCREEN SESSION!! #/...
from unittest import TestCase from aazdev.app import create_app from utils.config import Config import os import shutil class ApiTestCase(TestCase): AAZ_DEV_FOLDER = os.path.expanduser(os.path.join('~', '.aaz_dev_test')) def __init__(self, *args, **kwargs): self.cleanup_dev_folder() Config.AA...
__author__ = 'brett' from rest_framework import viewsets, exceptions from ..models import MatchResult from .serializers import MatchResultSerializer class MatchResultViewSet(viewsets.ReadOnlyModelViewSet): queryset = MatchResult.objects.all().select_related('home_team', 'away_team') def get_queryset(self):...
""" Module contain all need parameters to create a board. It has two specific pair of variables: - width and height of the chess board - width and height of the field on the chess board, witch is a 1/64 part of whole board Code using this module has to handle following exceptions: AttributeError,TypeError: invalid ty...
''' 1. 登录认证; 2. 增删改查和搜索 3.1 增 add # add monkey 12 132xxx monkey@51reboot.com 3.2 删 delete # delete monkey 3.3 改 update # update monkey set age = 18 3.4 查 list # list 3.5 搜 find # find monkey 3. 格式化输出 ''' # 标准模块 import sys # 定义变量 RESULT = [] INIT_FAIL_CNT ...
# # PySNMP MIB module WL400-SNMPGEN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WL400-SNMPGEN-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:29:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
"""Constants for the TickTick integration.""" DOMAIN = "ticktick"
import argparse import os import time import wave import numpy as np import pyaudio import utils import model import tensorflow parser = argparse.ArgumentParser() # set up training configuration. parser.add_argument('--n_classes', default=5994, type=int, help='class dim number') parser.add_argument('--audio_db', defau...
from pygears import gear, registry from pygears.typing import Union from pygears.common.demux import demux from pygears.common.mux import mux from pygears.common.shred import shred def fill_type(din_t, union_t, sel): dtypes = union_t.types.copy() dtypes[sel] = din_t return Union[tuple(dtypes)] @gear de...
""" Script for making various plots for optimisation of regularisation parameters, as provided by RooUnfoldParms class: http://hepunx.rl.ac.uk/~adye/software/unfold/htmldoc/RooUnfoldParms.html Plots produced: - Chi squared values vs regularisation parameter - RMS of the residuals given by the true and the unfolded dis...
# BAREOS - Backup Archiving REcovery Open Sourced # # Copyright (C) 2013-2014 Bareos GmbH & Co. KG # # This program is Free Software; you can redistribute it and/or # modify it under the terms of version three of the GNU Affero General Public # License as published by the Free Software Foundation, which is # listed in ...
#! /usr/bin/env python # -*- coding: utf-8 -*- import json import datetime import decimal from sqlalchemy.ext.declarative import DeclarativeMeta class AlchemyJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj.__class__, DeclarativeMeta): # an SQLAlchemy class ...
from django.db import models from mptt.models import MPTTModel, TreeForeignKey from django.db.models.fields.files import FieldFile from . import tgupload import os from django.core.exceptions import SuspiciousFileOperation from django.conf import settings from django.contrib.auth import get_user_model class RemoteFiel...
import tba_config from controllers.base_controller import LoggedInHandler from helpers.suggestions.suggestion_test_creator import SuggestionTestCreator class AdminCreateTestSuggestions(LoggedInHandler): """ Create test suggestions. """ def get(self): self._require_admin() if tba_confi...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import numpy as np import tensorflow as tf import tensorlight as light def sse(outputs, targets, name=None): """Sum of squared error (SSE) between images. Parameters ---------- outputs: Tensor [batch_size, ...] of type float32 The first tensor. targets: Tensor [batch_size, ...] of type flo...
import sys import os sys.path.append(os.path.abspath("../")) from unittest import TestCase from unittest.mock import patch from unit_test.util import Util from icon_servicenow.actions.get_attachments_for_an_incident import GetAttachmentsForAnIncident from icon_servicenow.actions.get_attachments_for_an_incident.schema...
# Generated by Django 1.11.20 on 2019-04-09 19:32 import django.db.models.deletion import django.utils.timezone import model_utils.fields import simple_history.models from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencie...
nota1 = float(input()) nota2 = float(input()) nota3 = float(input()) med = (nota1 + nota2 + nota3)/3 print(round(med,2))
from cffi import FFI ffibuilder = FFI() ffibuilder.cdef(""" void binary_gaussian_elimination(int **A, int m, int n); void mat_vec_mod2(int **A, int *x, int *y, int m, int n); void print_mat(int **A, int m, int n); """) ffibuilder.set_source("mm2r", """ void binary_gaussian_elimination(int **A, int m, int n); void mat...
class Settlement: def __init__(self, req): self.req = req async def fetch(self, **kwargs): """ :param kwargs: :return: """ endpoint = 'settlement' return await self.req.get(endpoint=endpoint, params=kwargs) if kwargs else await self.req.get(endpoint=end...
# Practical subset usage # PyTorch dataset import numpy as np import torch from torch.utils.data import Dataset train_set = np.load('./train.npy') train_label = np.load('./train_label.npy') class EyeTrackingDataset(Dataset): def __init__(self, train_set, train_label): self.train_set = train_set ...
def threeSum(nums: 'List[int]') -> 'List[List[int]]': nums.sort() result = [] for i in range(len(nums)-2): if (i>0 and nums[i-1]==nums[i]): continue lo, hi = i+1, len(nums)-1 while lo<hi: sum = nums[i]+nums[lo]+nums[hi] if (sum==0): ...
import glob, os, warnings import pandas as pd import numpy as np from datetime import datetime from posenet.constants import * def count_files(path): path = path + "\*.jpg" return len(glob.glob(path)) def append_part(arr, path): df = pd.DataFrame(arr) df.to_csv(path, encoding="utf-8", index=False,...
#!/usr/bin/python3 import os import sys import cv2 import time import torch import rospy import torch.optim as optim import torch.nn as nn from PIL import Image from sensor_msgs.msg import CompressedImage from torchvision import datasets, transforms from matplotlib import patches, patheffects from paramiko import SSHC...
""" Register the top menu for the frontend. """ from flask_nav import Nav from flask_nav.elements import ( Navbar, View, Link ) nav = Nav() nav.register_element('frontend_top', Navbar( View('Home', 'frontend_blueprint.index'), View('Processors', 'processors_blueprint.processors'), View('Chains...
#! /usr/bin/env python from __future__ import print_function import numpy as np import hello_helpers.hello_misc as hm from hello_helpers.gripper_conversion import GripperConversion class SimpleCommandGroup: def __init__(self, joint_name, joint_range, acceptable_joint_error=0.015): """Simple command group...
#%% # These algorithm were create in my early learning times when i did not know # the time and space complexities and all so these are just for educational purpose only. import os import pandas as pd #%% class Searches(): def __init__(self, paths_csv_file): # reads paths as data frame and initiali...
from turkey import Turkey class WildTurkey(Turkey): def gobble(self): print('Gobble gobble') def fly(self): print('I am flying a short distance')
import argparse import joblib from typing import Mapping from pathlib import Path from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, accuracy_score from sklearn.ensemble import RandomForestClassifier from nu...
n = int(input()) for i in range(n): print(' '*(n-i-1)+chr(65+i),end=' ') if i>0: print(' '*(2*i-1)+chr(65+i),end='') print() for i in range(n-1): print(' '*(i+1)+chr(65+n-i-2),end='') if i<n-2: print(' '*(2*(n-i-2)-1)+' '+chr(65+n-i-2))
# ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # -------------------------------------------------------------------...
class Nave: id_nave = None id_fabricante = None nome = None modelo = None tripulacao = None passageiros = None capacidade_carga = None preco = None def getIdNave(self): return self.id_nave def setIdNave(self, idnave): self.id_nave = idnave def getIdFabrican...
# 06 # group sizes with histogram import tacoma as tc from demo_utils import pl, disp from tacoma.analysis import plot_group_size_histogram hs13 = tc.load_json_taco('~/.tacoma/hs13.taco') groups = tc.measure_group_sizes_and_durations(hs13) fig, ax = pl.subplots(1,1) plot_group_size_histogram(groups,ax) pl.show...
from django.urls import path, include from rest_framework import routers from greenbudget.app.history.urls import ( actuals_history_urlpatterns, actual_history_urlpatterns) from .views import ( ActualsViewSet, AccountActualsViewSet, SubAccountActualsViewSet, BudgetActualsViewSet) app_name = "actual" ac...
""" The visualization module contains tools for real-time visualization as well as utilities to help in plotting. """ from .instrument_monitor import InstrumentMonitor from .pyqt_plotmon import PlotMonitor_pyqt __all__ = ["PlotMonitor_pyqt", "InstrumentMonitor"]
GLOBAL_SETTINGS = { "SITES" : ["enwiki","frwiki","arwiki","ruwiki"], "NAME_INSTANCES" : ["Q101352","Q202444","Q3409032","Q11879590","Q12308941","Q1243157","Q1076664","Q110874"], "DISAMBIGUATION_INSTANCES" : ["Q4167410"], "CREDENTIALS_PATH": '../conf/local/credentials.yml' }
# Generated by Django 3.0.3 on 2020-02-22 00:26 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0003_auto_20200217_1548'), ] operations = [ migrations.RemoveField( model_name='service'...
""" An example how to plot animation like in README Please replace the regex string for your batch log output """ from hsicbt.utils import plot import matplotlib.pyplot as plt import numpy as np import glob def plot_needle_distribution(): regex = "./assets/activation/raw/070820_152112_needle-hsictrain-mnist-*.npy...
''' while em Python Utilizado para realizar ações enquanto uma condição for verdadeira. ''' x = 0 while x < 10: print(x) x = x + 1 print('FIM!') print('-'*12) y = 0 while y < 10: if y == 3: y = y + 1 #continue #break print(y) y = y + 1 print('-'*12) x = 0 # coluna while x ...
import json from os import walk import numpy as np import pandas as pd import plotly.express as px from py4j.java_gateway import JavaGateway import itertools DISTR_SRC_FILE_PATH = '../../java/pt/ist/socialsoftware/mono2micro/utils/mojoCalculator/src/main/resources/distrSrc.rsf' DISTR_TARGET_FILE_PATH = '../../java/pt/i...
# Copyright (c) 2014-2020 Cloudify Platform Ltd. 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 ...
import socket # http层 # tcp udp # socket是操作系统用来进行网络通信的底层方案 # 1. create socket # 2. connect domain port # 3. create request # 4. unicode -> encode -> binary binary -> decode -> str # 5. socket send # 6. socket recv # 参数 socket.AF_INET 表示是 ipv4 协议 # 参数 socket.SOCK_STREAM 表示是 tcp 协议 # 这是普通的 http socket,不是https,所以端口不能是4...
# Copyright 2015 The TensorFlow Authors. 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 applica...
from .test import TestCase __all__ = [ 'TestCase', ]
import tensorflow as tf class BahdanauAttention(tf.keras.layers.Layer): def __init__(self, units): super(BahdanauAttention, self).__init__() self.W1 = tf.keras.layers.Dense(units) self.W2 = tf.keras.layers.Dense(units) self.V = tf.keras.layers.Dense(1) def call(self, query, va...
"""empty message Revision ID: 5f86e3e2b044 Revises: 4a40191fc890 Create Date: 2019-06-22 20:10:26.664893 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5f86e3e2b044' down_revision = '4a40191fc890' branch_labels = None depends_on = None def upgrade(): # ...
# pylint:disable=unused-variable # pylint:disable=unused-argument # pylint:disable=redefined-outer-name from typing import AsyncIterator import pytest from aioresponses import aioresponses from faker import Faker from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st from models_...
import datetime import shutil import sqlite3 import urllib.parse from pathlib import Path import subprocess as sp from yaspin import yaspin from building import build_packages from utils import parse_package_names, read_config, find_package_deps from snapshots import prepare_snapshot, commit_snapshot, current_snapsho...
""" 交易机器人 """ import time import datetime import numpy as np import pandas as pd import pandas_datareader as pdr import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib as mpl import flynnBot.indicators as mindicators mpl.rcParams['grid.color'] = 'gray' mpl.rcParams['grid.linestyle'] = '...
import pandas as pd from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.pipeline import make_pipeline from blocktorch.pipelines.components.transformers.preprocessing import ( TextTransformer ) class LSA(TextTransformer): """Transformer to ca...
from nltk import word_tokenize from nltk.stem import WordNetLemmatizer import spacy nlp = spacy.load("en_core_web_sm") # Don't put this inside the function- loading it in every CV iteration would tremendously slow down the pipeline. class LemmaTokenizer: """ Class for custom lemmatization in `sklearn.feature_...
import logging import subprocess import time import os import sys import datetime os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") sys.path.append(os.getcwd()) import django # noqa: E402 django.setup() from django.conf import settings from apscheduler.schedulers.background import BackgroundSchedul...
from aurora.settings.base import * import os # Override base.py settings DEBUG = True ALLOWED_HOSTS = [] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.c...
# Copyright 2020 Tensorforce Team. 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 applicable la...
from random import randint class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type numsSize: int """ self.nums = nums def pick(self, target): """ :type target: int :rtype: int """ r = self.nums.index(ta...
#Desafio 8 Escreva um programa que leia um valor em metros e o exiba convertido em centimos e milimetros. medida = float(input('Uma distância em metros: ')) cm = medida * 100 mm = medida * 1000 print('A medida de {}m corresponde a {}cm e {}mm'.format(medida, cm, mm))
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A Python implementation of the method described in [#a]_ and [#b]_ for calculating Fourier coefficients for characterizing closed contours. References ---------- .. [#a] F. P. Kuhl and C. R. Giardina, “Elliptic Fourier Features of a Closed Contour," Computer Visio...
from carton import Carton f = open('input','r') entry = [int(s) for s in f.readline().split(",")] lines = f.readlines() t = len(lines) i = 1 cards = [] while (i < t): data = [] for j in range(5): data.append([int(v) for v in lines[i].split()]) i += 1 d = Carton(data) cards.append(d) ...
import socket #create an INET, raw socket s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP) # receive a packet while True: raw_output = s.recvfrom(65565) bytes_raw_output = raw_output[0] bytes_output = str(bytes_raw_output).encode("utf-8").strip() adress_raw_output = raw_output[1]...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'D:\PyCharmProjects\rp_air\ui\rp_air_main_ui.ui' # # Created: Wed Apr 15 14:21:40 2015 # by: PyQt4 UI code generator 4.11.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = Q...
#!/usr/bin/env python def issquare(n): return (int(round(n**.5)))**2 == n total=m=0 while total < 10**6: m += 1 for ipj in xrange(2*m+1): if not issquare(ipj**2+m**2): continue if ipj > m+1: total += (2*m+2-ipj)/2 else: total += ipj/2 print m
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'demoProgressBar.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): ...
#!/usr/bin/env python2.7 # Amazon FPGA Hardware Development Kit # # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Amazon Software License (the "License"). You may not use # this file except in compliance with the License. A copy of the License is # located at # # htt...
GOOD = 0 # value is perfectly A-okay INSUF_HIST = 1 # value best-guess was made due to insufficient history (ex, acceleration set to zero due to one timestamp) MISSING = 2 # value is missing (no car in front, etc.) CENSORED_HI = 3 # value is past an operating threshold CENSORED_LO = 4 # value is below an operating...
import math import torch from tqdm import tqdm def train_eval(model, criterion, eval_iter, rnn_out=False): model.eval() acc = 0.0 n_total = 0 n_correct = 0 test_loss = 0.0 for x, y in eval_iter: with torch.no_grad(): if torch.cuda.is_available(): x = x.cuda...
# # Plasma # Copyright (c) 2020 Homedeck, LLC. # from cv2 import cornerHarris, findTransformECC, MOTION_TRANSLATION, TERM_CRITERIA_COUNT, TERM_CRITERIA_EPS from numpy import array, argpartition, asarray, column_stack, concatenate, eye, float32, ndarray, ones, split, stack as stack_array, unravel_index from numpy....
#!/usr/bin/env python # # This library is for Grove - Time of Flight Distance Sensor VL53L0X # (https://www.seeedstudio.com/Grove-Time-of-Flight-Distance-Sensor-VL53L0-p-3086.html) # which is a high speed, high accuracy and long range distance sensor based on VL53L0X. # # This is the library for Grove Base Hat which us...
"""Tests for the text reuse module.""" import logging from unittest import TestCase, skip import spacy from dphon.reuse import MatchGraph from spacy.tokens import Doc from dphon.extend import LevenshteinExtender from dphon.match import Match # disconnect logging for testing logging.captureWarnings(True) logging.disa...
import cs.utils as utils import gzip import json import logging import os import shutil import uuid import cs_cmdline import cs_dhcp import cs_firewallrules import cs_forwardingrules import cs_loadbalancer import cs_network_acl import cs_public_ip_acl import cs_staticroutes import cs_virtualrouter class DataBag: ...
#!/usr/bin/python import os, sys from jinja2 import Template if len(sys.argv) != 4: print("Allowed paremeters are 3, the source, destination and environment variable prefix parameters and you are passing %d args" % (len(sys.argv) - 1)) sys.exit(1) template_file = sys.argv[1] config_file = sys.argv[2] env_pre...
import pytest from lib.two_sum import two_sum def test_example_one(): nums = [2, 7, 11, 15] target = 9 assert two_sum(nums, target) == [0, 1] def test_example_two(): nums = [2, 3, 4] target = 6 assert two_sum(nums, target) == [0, 2] def test_example_three(): nums = [-1, 0] target...
#!/usr/bin/env python3 # Cordwood Puzzle (second edition) by Boldport # Boldport Club project #3, May 2016 # This program controls the Boldport Cordwood Puzzle (v2) using the 2N7000 n-channel FETs on the board. # Made by Dries Renmans, 20160516 (mailto:dries.renmans@telenet.be) # Dependencies: python3, RPi.GPIO impor...
import numpy as np from cost_functions import trajectory_cost_fn import time import logging def dd(s): logging.getLogger("hw4").debug(s) def di(s): logging.getLogger("hw4").info(s) class Controller(): def __init__(self): pass # Get the appropriate action(s) for this state(s) def get_act...
import os import mmcv import pytest import torch from mmgen.apis import (init_model, sample_img2img_model, sample_uncoditional_model) class TestSampleUnconditionalModel: @classmethod def setup_class(cls): project_dir = os.path.abspath(os.path.join(__file__, '../../..')) ...
# -*- coding: utf-8 -*- """ Created on Fri Jul 20 09:45:33 2018 @author: lenovo """ # created by cui 20180720 Friday 09:45 # finished by cui 20180720 Friday 09:56 def CountSort(A, k): B = [] for i in range(len(A)): B.append(0) C = [] for j in range(k + 1): C.append(...
from . import rpn, rrpn # noqa F401 isort:skip def build_proposal_generator(cfg, input_shape): """ Build a proposal generator from `cfg.MODEL.PROPOSAL_GENERATOR.NAME`. The name can be "PrecomputedProposals" to use no proposal generator. """ name = cfg.MODEL.PROPOSAL_GENERATOR.NAME if name == ...
#!/usr/bin/env python3 for value in range(1, 15): print("insert " + str(value) + " user" + str(value) + " user" + str(value) + "@codinglab.fr") # insert 15 user15 user15codinglab.fr
""" feature map input : (batch_size, num_channels, fm_size[0], fm_size[1]) feature map output size : (input_size, num_filters, fm_size[0], fm_size[1]) filter_size : (, fm_size[0], fm_size[1]) """ import numpy as np; import theano; import theano.tensor as T; from scae_destin.convnet import ConvNetBase class CKMLayer...
import random as rand from yachalk import chalk import emoji def welcome_en(): print("") name = str(input("What's your name ? ")) if name == '': name = 'Jakob' else: pass print("Welcome, " + chalk.red(chalk.bg_white("{} ")).format(name) + emoji.emojize(":red_exclamati...
# FIND FIRST AND LAST POSITION OF ELEMENT IN SORTED ARRAY LEETCODE SOLUTION: # creating a class. class Solution(object): # creating a function to solve the problem. def searchRange(self, nums, target): # creating a list. l = [] # creating an if-statement to check if the ta...
from .load_backend import *
# -*- coding: utf-8 -*- # # Copyright (C) 2016-2018 by Ihor E. Novikov # # This program 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 Foundation, either version 3 # of the License, or (at your option) any la...
import networkx as nx import pandas as pd #from community import community_louvain from random import choice from multiprocessing import Pool import itertools import os def import_graph(path): """ Import and read a networkx graph to do some calculations Args: path (string): path of the networkx g...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.db.models import Q def leave_only_last_security_scan(apps, schema_editor): SecurityScan = apps.get_model("security", "SecurityScan") total_scans = SecurityScan.objects.count() base_objec...
from a10sdk.common.A10BaseClass import A10BaseClass class SessionList(A10BaseClass): """This class does not support CRUD Operations please use parent. :param protocol: {"type": "string", "format": "string"} :param inside_v6_address: {"type": "string", "format": "ipv6-address"} :param inbound: {"...
#-*- coding: utf-8 -*- #For Flask-Alchemy #使用SqlAutocode,根据数据库已有表,产生符合Flask-SqlAlchemy要求的models的定义 import os.path from sqlautocode.declarative import name2label from flask.ext.sqlalchemy import SQLAlchemy from .flask_factory import FlaskModelFactory def no_prefix_wrapper(f, prefix=None): def _name2label(name, sc...
import asyncio import functools import threading import time def ttl_lru_cache(seconds: int, maxsize: int = 128, typed: bool = False): def wrapper_cache(func): wrapped_cache_func = functools.lru_cache(maxsize=maxsize, typed=typed)(func) wrapped_cache_func.delta = seconds * 10 ** 9 wrapped_...
"""Utilities related to logging.""" import os import sys import logging import datetime import pathlib import appdirs logger = logging.getLogger(__name__) class WarningLoggedError(Exception): """Special exception to raise when a warning message is logged. Satpy has the tendency to log warnings when things ...
from typing import Optional from interface.iapp import IApp from interface.igossipmanager import IGossipManager class GossipManager(IGossipManager): def __init__(self): self.app: Optional[IApp] = None def set_app(self, app: IApp): self.app = app def start(self): """Starts the ru...
from typing import List from boa3.builtin import public @public def Main(operation: str, args: List[int]) -> int: if len(args) < 2: return 0 a: int = args[0] b: int = args[1] c: int if a < b: c = Add(a, b) elif a <= 0 and b <= 0: c = Sub(a, b) else: c = 0 ...
''' The Robot Model package. A set of classes designed to represent the main aspects of the rigid-body-dynamics model of an articulated robot, such as connectivity, numbering scheme of the links, attached frames, geometrical measurements. '''
class Solution: def numMagicSquaresInside(self, grid: List[List[int]]) -> int: def all_vals_valid(row, col): numbers = set() for i in range(row, row + 3): for j in range(col, col + 3): if 1 > grid[i][j] or grid[i][j] > 9 or grid[i][j] in number...
# coding: utf-8 from Crypto.Cipher import AES import base64 import requests import json headers = { 'Cookie': 'appver=1.5.0.75771;', 'Referer': 'http://music.163.com/', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' } # ...
import math import multiprocessing import os import queue import time from collections import defaultdict from copy import copy from multiprocessing import shared_memory import copy import numpy as np from scipy.signal import fftconvolve from Implementations.helpers.Helper import toNumbers, ListToPolynomial from Impl...
# # Copyright (c) 2021, NVIDIA CORPORATION. # # 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 ...
# python example 2 # http://www.steves-internet-guide.com/python-mqtt-publish-subscribe/ import paho.mqtt.client as paho broker="broker.hivemq.com" broker="iot.eclipse.org" #define callback def on_message(client, userdata, message): time.sleep(1) print("received message =",str(message.payload.decode("utf-8"))) clien...
'''OpenGL extension APPLE.texture_max_level This module customises the behaviour of the OpenGL.raw.GLES2.APPLE.texture_max_level to provide a more Python-friendly API Overview (from the spec) This extension allows an application to specify the maximum (coarsest) mipmap level that may be selected for the specif...
# coding: utf-8 # flake8: noqa from __future__ import absolute_import # import models into model package from openapi_server.models.create_docker_submission_request import CreateDockerSubmissionRequest from openapi_server.models.create_file_submission_request import CreateFileSubmissionRequest from openapi_server.mode...
""" Obtains data for a side pairing. """ from click import * from logging import * import pandas as pd @command() @option("--input", required=True, help="the Feather file to read input data from") @option("--output", required=True, help="the Feather file to write output to") @option( "--sides", type=Choice(...