text
stringlengths
38
1.54M
from __future__ import annotations from functools import partial from typing import TYPE_CHECKING, Any from loguru import logger from .html import format_attrs, format_attrs_kw if TYPE_CHECKING: from flask import Flask def format_attrs_ctx() -> dict[str, Any]: return {"format_attrs": format_attrs, "forma...
from copy import copy from card import Card from symbols import Direction, Rank, Suit # TODO: This class doesn't seem very useful now. Either find its use in the next step of the work, or delete it. class State(object): """ We store both declarer and dummy card lists here These lists need not be lists of...
# summarize multiple confidence intervals on an ARIMA forecast from pandas import Series from statsmodels.tsa.arima_model import ARIMA # load data series = Series.from_csv('daily-total-female-births.csv', header=0) # split data into train and test setes X = series.values X = X.astype('float32') size = len(X) - 1 train,...
import scrapy from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor from scrapy.spiders import Rule from geoscrap_project.items.Items import * from bs4 import BeautifulSoup import cfscrape import json import jmespath import pendulum from pathlib import Path import random from urllib.parse import urlparse class...
from django.db import models from django.conf import settings from django.urls import reverse from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill from taggit.managers import TaggableManager class Category(models.Model): DEFAULT = "카테고리" CATEGORY_CHOICE = [ ("FOOD...
# -*- coding: utf-8 -*- """Hyperparameter optimization by grid search. """ # Author: Taku Yoshioka, Shohei Shimizu # License: MIT import numpy as np from bmlingam.cache_mc import create_cache_source from bmlingam.bmlingam_np import comp_logP, comp_logP_bmlingam_np from bmlingam.cache_mc_shared import comp_logPs_mp ...
import tweepy import json auth = tweepy.OAuthHandler('pFduB9dBKq5zvEWrAkhfTSnyv', 'cBcMj9z9jIO3HhmeaykDdfaCsByDqQujF4mZ6VO8mTyjDn5SGG') auth.set_access_token('1058601288223514624-piQQ1twMDAwuAg7jTwJzvjHIRGVGNA' , 'nOcTYajRX8RRQDQ5cb4Rpl12GVGM2atSUqpRRg2aCDP8n') api = tweepy.API(auth) trends1 = api.trends_available()...
# -*- coding: utf-8 -*- ######################################################################### # Copyright (C) 2018-2019 by Simone Gaiarin <simgunz@gmail.com> # # # # This program is free software; you can redistribute it and/or modify # ...
from typing import Callable, Union from argparse import ArgumentTypeError as ArgumentError import os class PathType: def __init__( self, exists=True, val_type: Union[Callable[[str], bool], str, None] = "file", dash_ok=True, ): """Represent an argument of type path to a ...
import time, numpy, pylab import flypod, sky_times pylab.ion() #dirName = '/media/weir05/data/rotator/indoor/gray/12trials/fly10' #dirName = '/media/weir05/data/rotator/indoor/12trials/fly17' #dirName = '/media/weir05/data/rotator/indoor/sham12trials/fly09' #dirName = '/media/weir05/data/rotator/12trials/fly92' dirNam...
# /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2018 Houwei and Tuhang # FileName : predict.py # Author : Hou Wei # Version : V1.0 # Date: 2018-01-08 # Description: Train # History: import os import datetime import numpy as np from keras.models import load_model import prepare_data as pd from postpro...
from tf_activation.models.cff import CFF_Model from tf_activation.models.fff import FFF_Model from tf_activation.models.ccff import CCFF_Model import tf_activation.functions.plotnn as pltnn import pandas as pd import numpy as np import matplotlib.pyplot as plt import networkx as nx import tensorflow as tf from tensorf...
x = [2,54,-2,7,12,98] #max value in array print "Max value is : ", max(x) #min value in array print "Min value is : ", min(x) #length of given array print len(x) #index of given array print "Index for -2 : ",x.index(-2) #append the number -77 to an array x.append(-77) print "Updated List : ", x #append the stri...
#!/usr/bin/env python ''' python script to submit atat jobs to the queue usage: In a directory with a str.out file, run this script. To use it on many files, use this command: foreachfile -e -d 3 wait run_atat_vasp.py Execute the specified command in every first-level subdirectory containing the file filename. The -...
""" File name: grid.py Author: ngocviendang Date created: July 13, 2020 This file creat the grid for the images. """ import argparse import sys import os import numpy as np import nibabel as nib from captcha.utils.helper import load_nifti_mat_from_file from captcha.utils.helper import create_and_save_nifti from captch...
from enum import Enum from solutions import helpers import numpy as np import re from dataclasses import dataclass, replace np.set_printoptions(edgeitems=30, linewidth=100000) filename = 'input' # filename = 'test' n_minutes = 32 strings = helpers.read_each_line_as_string(filename) class BuildOption(Enum): N...
#!/usr/bin/python import sys from multiprocessing import Process from primes import primes # python set of prime numbers input_file = sys.argv[1] if len(sys.argv) > 1 else 'c_sample.in' radixes = (2, 3, 4, 5, 6, 7, 8, 9, 10) divisors_dict = {} def is_prime(n): # Modified from http://stackoverflow.com/questions/152...
import re import datetime import numpy as np from pandas import NA import functools from fuzzywuzzy import process from Entires import SourceColumns as SC, ConvertedColumns as CC from Entires.GeoCoordinatesFinder import GeoFinder import Settings def get_converter(column): if column in [CC.Source, CC.Region, ...
from django.contrib import admin from django.urls import path from .views.pictures import PicturesIndexView app_name = 'pictures' urlpatterns = [ path('', PicturesIndexView.as_view(), name='index'), ]
#coding=gbk ''' Created on 2015年12月21日 @author: 大雄 ''' import csv import poplib import email.header import email.utils import base64 import os import logging from zipfile import ZipFile from io import BytesIO,StringIO def parserCSV(string,row_range,col_range): try: strio = StringIO(stri...
from csv_comparison_package import Compare from csv_comparison_package.decorator import call_each @call_each def set_start_end_disjunctive_column(comparable: Compare): if comparable.number_of_disjunctive_columns > 0: comparable.disjunctive_column_start = \ comparable.start_column \ ...
import pylab as pyl dt = 0.05 p = -5.0 sp = 5.0 acc = [p*sp] vel = [0.0] s = [sp] t = [0.0] for i in range (1, 100): acc.append(s[-1]*p) vel.append(vel[-1] + acc[-1]*dt) s.append(s[-1]+vel[-1]*dt) t.append(dt*i) dp = pyl.plot(t, s) pyl.show()
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Author : willi # @Email : willi168@163.com # @Description: import json import re from lxml import etree class Response(object): def __init__(self, url, status_code, headers, body): self.url = url self.status_code = status_code self.headers =...
# settings for app # PAYPAL_ENDPOINT = 'https://svcs.sandbox.paypal.com/AdaptivePayments/' # sandbox PAYPAL_ENDPOINT = 'https://svcs.paypal.com/AdaptivePayments/' # production # PAYPAL_PAYMENT_HOST = 'https://www.sandbox.paypal.com/au/cgi-bin/webscr' # sandbox PAYPAL_PAYMENT_HOST = 'https://www.paypal.com/webscr' # p...
class Stack: def __init__(self): self.items = [] def isEmpty(self): if len(self.items) != 0: return False else: return True def push(self,data): self.items.append(data) def pop(self): self.items.pop() def display(self): prin...
""" A module that binds all of the commands for the terminal CLI app together into one command group. """ import logging import sys import click from ._bot_command import bot from ._caption_command import caption from ._ls_command import ls _LOGGING_FORMAT = "%(asctime)s %(levelname)s %(message)s" @click.group()...
from django.contrib import admin from django.urls import path import post.views urlpatterns = [ path('admin/', admin.site.urls), path('info/', post.views.info, name="info"), path('', post.views.index, name='index'), path('csv/', post.views.csv, name="csv"), path('conner/', post.views.conner, name=...
from unittest import TestCase import os import tempfile import pickle import shutil from easy_word2vec.utils.data_utils import prepare_corpus class TestCasePrepareCorpus(TestCase): def test_prepare_corpus(self): input_data = '''foo bar foo abc def new old abc how yes no no foo sir foo abc foo old...
import hashlib from http import HTTPStatus from secrets import token_hex from flask_restful import Resource, reqparse from app.auth.handlers import auth from app.entities.basic_schema import BasicResponseSchema, BasicSchema from models.token import Token from db.setup import db class AuthController(Resource): d...
# -*- coding: utf-8 -*- """ Created on Mon Jul 22 17:03:59 2019 @author: zhangyanhang """ import unittest from unittest import TestCase from Ball.bd import bd_test, bd from Ball.bcorsis import bcorsis from Ball.bcov import bcov_test, bcov from Ball.wrap_c import bd_test_wrap_c, bcor_test_wrap_c, bcov_test_wrap_c, kbc...
#/usr/bin/env python #coding=utf-8 import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.metrics import precision_score,recall_score,f1_score,accuracy_score from sklearn import preprocessing from joblib import dump, load from result import figures import input_w train_d...
def pollsf(x, y, sigma, M): import numpy as np ''' Function to perform a linear regression Inputs ------ x Independent variable y Dependent variable sigma Estimated error in y M Number of parameters used to fit data Outputs ------- a_fit Fit parameters; a(1) = intercept, a(2) = slope sig_a...
#!env python # vim: set fileencoding=utf8 # Created:20080216 # By Jeff Connelly # # Trinary-related symbols # See http://jeff.tk/wiki/Trinary/Symbols # Note: to print, .encode('utf8') first # # MORE IMPORTANT NOTE: This isn't needed most of the time. # Instead, just use the Unicode symbols directly. You can # do this i...
import jax.numpy as np import jax.numpy as jnp from jax import jit, vmap, random, value_and_grad, grad import haiku as hk import optax from tqdm import tqdm from functools import partial import warnings from typing import Mapping import os from . import utils, metrics, stein, kernels, nets on_cluster = not os.getenv...
from __future__ import absolute_import from celery import shared_task from jobapplications.management.commands.import_crawlresults import Command from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @shared_task def add(x, y): logger.info('Adding {0} + {1}'.format(x, y)) return x +...
import shutil import os import sys try: files = os.listdir("c:/Users/Sachin/.jenkins/workspace/my_jenkins_pytest/allure-report/history") print(files) for f in files: #print(f) shutil.copy("c:/Users/Sachin/.jenkins/workspace/my_jenkins_pytest/allure-report/history/"+f,"c:/Users/Sachin/.jenkins/workspace/my_jenki...
#!/usr/bin/python3 import json import math from distutils import util import multiprocessing from types import FrameType import PIL # from numpy.core.fromnumeric import repeat import pyopencl as cl import numpy as np import os import matplotlib.pyplot as plt # from PIL import Image import matplotlib.animation as animat...
import socket ip = input('[+] Ingresa la IP: ') def scanner(puerto): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, puerto)) return True except: return False for NumeroPuerto in range(1, 1025): print("Escane...
import shelve db = shelve.open('class-shelve') bob = db['bob'] bob.giveRaise(.20) db['bob'] = bob tom = db['tom'] tom.giveRaise(.25) db['tom'] = tom db.close()
''' 【程序23】 题目:打印出如下图案(菱形) * *** ***** ******* ***** *** * 1.程序分析:先把图形分成两部分来看待,前四行一个规律,后三行一个规律,利用双重       for循环,第一层控制行,第二层控制列。 2.程序源代码: ''' #!/usr/bin/env python # -*- coding: UTF-8 -*- from sys import stdout for i in range(4): for j in range(3 - i): stdout.write(' ') for k in range(2 *...
import sys import csv class Todo(): def __init__(self): self.file_name = 'todo_list.csv' def main_menu(self): print(' ') print('===========================') print(' ') print(' TODO APPLICATION ') pri...
# pass statement # when dont want to write anything and just pass to the next x = 18 if x > 18: pass
#!/usr/bin/python2 """ This script makes an input file for [SweepFinder](http://people.binf.ku.dk/rasmus/webpage/sf.html). To make such file information on the outgroup/ancestral sequence is required. Note! Chromosome number in the first column must be separated by _. For example, chr_1 - correct, chr1 - incorrect. ...
import os from collections import OrderedDict import pandas as pd from src.callbacks import ParamStatsStoreCallback, EpochLoggerCallback from src.constraints import LessThanConstraint, MoreThanConstraint, RoomConstraint from src.experiments.utils import SAMPLES_PATH from src.experiments.utils import get_experiment_di...
commands = { 'help': { 'name': '$help', 'help_message': 'Display help about a command.', 'usage': '$help <command>' }, '8ball': { 'name': '$8ball', 'help_message': 'Answer a yes/no question.', 'usage': '$8ball <yes/no question>' }, 'ban': { ...
import re def cleanhtmltags(raw_html): """ Convert raw html code to text by removing all tags. """ cleanr =re.compile('<.*?>') withouttags = re.sub(cleanr,'', raw_html) withouttags.split() without_mult_spaces= ' '.join(withouttags.split()) return without_mult_spaces
from __future__ import unicode_literals from django import forms from DjangoUeditor.forms import UEditorWidget from DjangoUeditor.models import UEditorField from .models import Post class ImageUploadForm(forms.Form): image = forms.ImageField() class TopicUEditorForm(forms.Form): Name = forms.CharField(label...
#!/usr/bin/env python # coding: utf-8 # In[1]: import requests from bs4 import BeautifulSoup import re import pandas as pd import mysql.connector from datetime import datetime from keywordQuery import query # In[2]: mydb = mysql.connector.connect( host="localhost", user="root", password="", datab...
## Richard Salvaty ## 3002 ## 10/15/2018 ## 10 minutes ## Delcare nTemp as string ## Declare Cel as integer ## Declare Fah as float ## Set nTemp = 'y' ## while (nTemp == 'y') ## Print "Enter degrees in Celcius to be converted to Fahrenheit: " ## Get Cel ## Set Fah = (9/5 * Cel) + 32 ## Print "Degre...
from django.contrib import admin from django.contrib.admin import ModelAdmin from viewer.models import Bookcase, Book, BookAuthor, BookcaseSlot admin.site.register(Bookcase, ModelAdmin) admin.site.register(BookcaseSlot, ModelAdmin) admin.site.register(BookAuthor, ModelAdmin) admin.site.register(Book, ModelAdmin)
import subprocess import shutil import os import time from pprint import pprint from collections import namedtuple import glob import datetime import psutil npx_paramstup = namedtuple('npx_paramstup',['backup_location','start_module','end_module']) backup_drive = r'T:' default_start = 'copy_raw_data' default_end = 'c...
from django.http import HttpResponse from django.template.loader import get_template from core.decorators import UserLogguedDecorator from django.template.loader import render_to_string from django.core.mail import EmailMessage from users.models import User as SystemUser from subjects.models import Subject from reques...
import os, requests, uuid, json #if 'e6821924ed6e4a1d9faea4a0d355d0a0' in os.environ: # subscriptionKey = os.environ['e6821924ed6e4a1d9faea4a0d355d0a0'] #else: # print('Environment variable for TRANSLATOR_TEXT_KEY is not set.') # exit() # If you want to set your subscription key as a string, uncomment the nex...
import numpy as np from math import pi, sin, cos, sqrt import tqdm import matplotlib.pyplot as plt l1 = 1 l2 = 1 l3 = 1 l4 = 1 def J(q): """エンドエフェクター状態変数のヤコビ行列""" z = np.array([ [ -l1*sin(q[0,0]) + sqrt(2)*l2*cos(q[0,0] + q[1,0] + pi/4) + l2*cos(q[0,0] + q[0,0] + q[2,0]), l...
import requests from envparse import env from flask import Flask from flask_restplus import Api, Resource, fields env.read_envfile() app = Flask(__name__) api = Api(app) model = api.model('Model', { 'text': fields.String, }) class Text: def __init__(self): self._text = None self._observers ...
from django.contrib import messages from django.core.exceptions import ImproperlyConfigured from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView from django.views.generic import DetailView from django.views.generic import ListView from djang...
# -*- coding: utf-8 -*- import ui from random import randint import sqlite3 as lite import sys i=1 con = lite.connect('./my.sqlite') with con: cur = con.cursor() cur.execute("SELECT * FROM PrePri") rows = cur.fetchall() a=[] b=[] for row in rows: a.append(row[0]) b.append(row[1]) c=randint(0,184) v=[...
#!/usr/bin/env python3 # vim:fileencoding=utf-8 import os import sys import base64 import quopri from mailbox import mbox import email.header from lxml.html import fromstring, tostring from lxml.html import builder as E from termcolor import colored from charset import CJK_align from myutils import filesize mailSty...
from math import sqrt,sin,pi from numpy import empty from pylab import imshow,gray,show wavelength = 5.0 k = (2*pi)/wavelength E0 = 1.0 Separation = 20.0 side = 100.0 points = 500 spacing = side/points x1 = (side/2 - Separation/2) y1 = (side/2) x2 = (side/2 + Separation/2) y2 = (side/2) xi = empty([points,points],...
"""BigGAN Evol Figure Partially inherit from BigGAN_Evol_summary.py but more focused. """ import os import re from time import time from glob import glob from os.path import join from easydict import EasyDict from imageio import imread import numpy as np import pandas as pd import seaborn as sns import matplotlib as m...
from django.contrib import admin from django.contrib.auth import get_user_model admin.site.register(get_user_model())
import math from itertools import islice from typing import Collection import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy import scipy.optimize import skimage import torch from matplotlib import patches, patheffects from matplotlib import pyplot as plt from matplotlib.patches import Pa...
import numpy as np import math import Interpolate if __name__ == '__main__': mass = [[19,1203],[22,1245],[26,1378],[28,1315],[30,1475]] n = 4 x = [0]*n dimensions = (n, n) y = np.zeros(dimensions) for i in range(1,n): x[i] = mass[i][0] y[i][0] = mass[i][1] Interpolate.calcu...
import keras from keras.models import Sequential, load_model from keras.layers import Dense, Conv2D, Flatten import autograd.numpy as np from collections import OrderedDict class TabularValueFun(object): def __init__(self, env): self.num_states = env.num_states self._value_fun = np.zeros(shape=(s...
from flask_debugtoolbar import DebugToolbarExtension from flask_bcrypt import Bcrypt bcrypt = Bcrypt() from flask_login import LoginManager login_manager = LoginManager() debug_toolbar = DebugToolbarExtension()
import requests import time import threading url = 'https://www.lagou.com/gongsi/allCity.html?option=0-0-0' # 测试接口的响应速度 def request(): start = time.time() requests.get("http://10.0.0.2:1024/company/one?name=steve&age=10&sex=true").text print("响应时间: {} ms".format((time.time() - start))) for i in range(1,10...
#Gavin Harris, Lab 3b # How to run: python ChangeMaker.py #ask user for input on how much change for program change = int(input("How much change are you trying to give (in cents)? ")) quarters = 0 dimes = 0 nickels = 0 pennies = 0 #it will loop as long as the change is above 0 cents while change > 0 : #if the chang...
# Turn off (too-many-instance-attributes), (invalid-name) and # (missing-docstring) pylint errors: # pylint: disable=R0902,C0103,C0111 import unittest from week1.proj1 import slide, merge class TestSlide(unittest.TestCase): def test_slide_returns_correct_result(self): self.assertEqual(slide([1, 0, 1, 1]...
import requests import os def downloadModelFromDB(ID, outPath, baseURL='https://files.rcsb.org/download/'): #print('Requesting {my_id} file. Please wait.\n'.format(my_id=ID)) reqURL = os.path.join(baseURL, ID.lower() + '.pdb') response = requests.get(reqURL) if not response.ok: #print('ID {my_i...
import floppyforms as forms from kitchencrashers.main.models import RsvpOptions from kitchencrashers.main.models import CategoryOptions class EventForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'name your event'})) date = forms.DateTimeField(widget=forms.SplitDateTimeWi...
############################################################################### # Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # # and others # # # ...
from django.core.management import BaseCommand #The class must be named Command, and subclass BaseCommand import matplotlib.pyplot as plt from reports.models import ostPerfHistory import datetime from pytz import timezone import numpy as np class Command(BaseCommand): # Show this when the user types help help = "...
import argparse import asyncio import logging import os from datetime import datetime import reuters_parsing.app as app from .db_postgres import PostgresBackend from .parser_reuters import ReutersParser parser = argparse.ArgumentParser(description='Reuters web scrapper.', prog="python3.8 -m reuters_parsing") parser.a...
# Generated by Django 3.1.1 on 2020-12-01 10:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mainpage', '0002_auto_20201129_1424'), ] operations = [ migrations.AddField( model_name='regionlarge', name='prev_no...
from __future__ import print_function import sys import ctypes import textwrap from nose.tools import assert_equal from parameterized import parameterized, param sys.path.append("pp/") import pp import pprintpp as p from pprintpp import Counter, defaultdict, OrderedDict class PPrintppTestBase(object): def asser...
from yacs.config import CfgNode as CN _C = CN() _C.NAME = "" _C.TRAIN = CN() _C.TRAIN.EPOCH_TOTAL = 50 _C.TRAIN.BATCH_SIZE = 8 _C.TRAIN.DATA = "" _C.TRAIN.OPTIMIZER = "sgd" _C.TRAIN.TEST_FREQ = 5 #epoch _C.TRAIN.OUTPUT_FOLDER = "" _C.TRAIN.INPUT_SIZE = [0,0] #Height Width _C.SGD = CN() _C.SGD.LR_START = 0.001 _C.SG...
import keras.backend as K import numpy as np from keras.layers import merge, Dense from keras.models import Input, Model, Sequential def get_multi_inputs_model(): a = Input(shape=(10,)) b = Input(shape=(10,)) c = merge([a, b], mode='mul') c = Dense(1, activation='sigmoid', name='only_this_layer')(c) ...
import sys, os, re, math import functools sys.path.insert(0, os.path.abspath('..')) from common.DayBase import DayBase class Substrate: def __init__(self, name="", amount=0): self.name = name self.amount = amount class Reaction: def __init__(self, result, substrates): self.substrat...
from __future__ import print_function from setuptools import setup # from setuptools.command.test import test as TestCommand import io # import sys import wikigrouth def read(*filenames, **kwargs): encoding = kwargs.get('encoding', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filename in filen...
import sys # generates the reverse complement of a codon def generate_reverse_complement(codon): new_codon = "" for l in reversed(codon): new_codon += "T" if l == "A" else "A" if l == "T" else "C" if l == "G" else "G" return new_codon # `replacement_codon` will replace `bad_codon` (for normal genes) # `rev_comp_...
from tkinter import * def drawCell(canvas, x, y, size, text): canvas.create_rectangle(x, y, x + size, y + size) canvas.create_text(x + size / 2, y + size / 2 - 1, text = str(text)) def drawCellLine(canvas, x, y, cellSize, elements, xBitCount): for column in range(0, 1 << xBitCount): drawCell...
import pygame import Components import MainPage from Pages import Page class DriveTrainPage(Page.Page): def __init__(self): Page.Page.__init__(self) self.backgroundColor = pygame.Color("dark red") self.components = [ Components.Label.Label([150, 150], 150, "Drive", ["red", "bla...
import cv2 import copy cap = cv2.VideoCapture(0) name=input("Please Enter Your First Name : ") while(True): ret,frame = cap.read() frame1=copy.deepcopy(frame) frame1 = cv2.putText(frame1, 'Press \'k\' to click photo', (200,200), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,255), 3, cv2.LINE_AA) cv2.imshow('im...
__author__ = 'Louis-Pan' import pytest """ 使用场景:有的用例需要登录执行,有些用例不需要登录执行 用例在执行时需要登录的用例,都需要执行login函数,相当于unittest中setUp()函数,每条用例运行前都需要执行 步骤: 1. 导⼊pytest 2. 在登陆的函数上⾯加@pytest.fixture() 3. 在要使⽤的测试⽅法中传⼊(登陆函数名称),就先登陆 4. 不传⼊的就不登陆直接执⾏测试⽅法。 """ @pytest.fixture(scope="function") def login(): print("\n登录成功") def test_update_pe...
from django.contrib import admin from django.urls import path from multiply_app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.calculator, name='calculator'), path('CalculateResult/', views.CalculateResult, name='CalculateResult'), ]
import falcon from ldframe.utils.logs import app_logger from ldframe.api.healthcheck import HealthCheck api_version = "0.2" # TO DO: Figure out a better way to do versioning def init_api(): """Create the API endpoint.""" ldframe = falcon.API() ldframe.add_route('/health', HealthCheck()) app_logger...
''' Created on 28/05/2015 @author: mangeli ''' import GameQualityAssessment.code_pac.dataBaseAdapter as db import os,sys sys.path.insert(1, os.path.abspath(os.pardir)) print (sys.path) db.setValues("desafio_simples", "mangeli", "localhost", "agoravai", 5432) conn = db.getConnection() c = db.getCursor(conn) db.cursorE...
from store import RedisClient import aiohttp import asyncio import time VALID_STATUS_CODES=[200] TEST_URL='http://baidu.com' BATCH_TEST_SIZE=100 class TEST: def __init__(self): self.redis=RedisClient() async def test_single_proxy(self,proxy): """ 测试单个代理 :param proxy: :...
#!/usr/bin/env python import rospy import math from robot_messages.msg import LandmarkDistance from std_msgs.msg import String from kobuki_msgs.msg import DockInfraRed from kobuki_msgs.msg import SensorState from tf.transformations import euler_from_quaternion class RobotController(object): def __init__(self,...
# Your key for the Google Speech API which is used to transcribe your speech to text. See this for more info: https://developers.google.com/api-client-library/python/guide/aaa_apikeys GOOGLE_SPEECH_API_KEY = "" # Your key for the Trello API: https://trello.com/app-key TRELLO_API_KEY = "" # You also need a Trello API ...
from software_v2 import Ui_MainWindow # importing our generated file from PyQt5 import QtCore,QtGui,QtWidgets,uic, QtTest from PyQt5.QtWidgets import QApplication,QMainWindow,QLabel,QDesktopWidget,QFileDialog from PyQt5.QtGui import QPixmap,QImage from PyQt5.QtCore import QThread ,pyqtSlot,pyqtSignal,Qt import thread ...
from qelos.train import lossarray, train, TensorDataset from qelos.rnn import GRUCell, LSTMCell, SRUCell, RNU, RecStack, RNNLayer, BiRNNLayer, GRULayer, LSTMLayer, RecurrentStack, BidirGRULayer, BidirLSTMLayer, Recurrent, Reccable, PositionwiseForward from qelos.loss import SeqNLLLoss, SeqAccuracy, SeqElemAccuracy from...
from backend import db class User(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) public_id = db.Column(db.Integer, unique=True) name = db.Column(db.String(30), nullable=False) surname = db.Column(db.String(30), nullable=False) role = db.Column(db.String(30), nullable=Fa...
import turtle import random draw = turtle.Turtle() lines = random.randint(10) for i in range(lines): length = random.randint(10, 100) angle = random.randint(1, 365) draw.forward(length) draw.right(angle)
from time import time, sleep from math import sqrt t0 = time() ############################# ### Instructions Begin ### ############################# ''' HOW TO USE This is a tool for automatically running multiple treatments and treatment sets and generating graphs to summarize their results. To create a set of...
# Need this modules for the dates. import datetime as dt # Create a list of strings. names = ["Zara", "Lupe", "Alberto", "Jake", "Tyler"] # Create a list of numbers numbers = [14, 0, 56, -4, 99, 56, 11.26] # Sort the names list names.sort() # Sort the numbers list numbers.sort() # Show the results print("Sorting in ...
from django.contrib.postgres.fields import ArrayField from django.db import models from django.db.models import F, Q from django.utils import timezone from enum import Enum import logging logger = logging.getLogger("django") def __defaultList__(): return [] GRADE = [ { 'name': { 'en': 'pri...
hrs = input("Enter Hours:") h = float(hrs) rate = input ("Enter rate") r = float(rate) ot = 1.5 * r pay = 40 * r if h > 40: bonus = (h - 40) * ot print (pay + bonus)
import pandas as pd import numpy as np import requests from io import StringIO from sklearn.preprocessing import MinMaxScaler class ErrorAPI(Exception): def __init__(self, code, message): super().__init__() self.code = code self.message = message def detail(self): ...
""" Runtime: 684 ms Memory: 18.9 MB """ from typing import List class Solution: """ Problem #15: Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Notice that the solution set must not con...