text
stringlengths
38
1.54M
seq = 'ACTGTC' T = {'Y':{'Y':0.7, 'N':0.2, 'End':0.1},\ 'N':{'Y':0.1, 'N':0.8, 'End':0.1},\ 'Begin':{'Y':0.2, 'N': 0.8}} E = {'Y':{'A':0.1, 'G':0.4, 'C':0.4, 'T':0.1},\ 'N':{'A':0.25, 'G':0.25, 'C':0.25, 'T':0.1}} states = ['Y', 'N'] def viterbi(seq, T, E, states): traceback = [] matrix = [[0 for i in range(len(s...
import math Matrix=[] # likelyhood matrix Freq=[] laplace=1 #laplace V=3 _lines=28 # #returns array of frequencies of the numbers # def frequencies(values): ret_val= [0]*10 for value in values: ret_val[int(value)]+=1 return ret_val # #reads the files with the images of text #returns a list will all the image...
# 7月老師的思路是先佔位,然後在其他地方使用這個類 #最後再回過頭來實現這個類 # 下面就是先應用的過程 #1.首先實例化兩個redprint(自定義對象) class Redprint: # 編寫一個類的時候,首先要思考它的構造函數(如何實例化) 還要在紅圖中取實現裝飾器的功能 # (裝飾器不是憑空來的)(還是要借鑑藍圖)1.實例化構造函數 2. 實現裝飾器功能 3.實現url_prefix參數 # 另外在應用這個紅圖的時候,用到了url_prefix的參數設置 def __init__(self,name): self.name = name self.mo...
import subprocess """ To run a process and read all of its output, set the stdout value to PIPE and call communicate(). the PIPE is just the common one-way IPC that we've been using: | """ print('read: ') # below is a subprocess that run a command: proc = subprocess.Popen( ['echo', '"to stdout"'], ...
import time from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from page.base_page import BasePage class Contact(BasePage): _base_url = 'https://work.weixin.qq.com/wework_admin/frame#contacts' def ...
icor = int(input('Wat is uw ICOR cijfer? ')) prog = int(input('Wat is uw PROG cijfer? ')) csn = int(input('Wat is uw CSN cijfer? ')) gemiddelde = (csn+icor+prog)/3 beloning = (int((300/10))*csn)+(int((300/10))*icor+int(((300/10))*prog)) overzicht = 'Uw gemiddelde is {} en uw beloning daarvoor is {} euro.'.format(gemid...
#!/usr/bin/env python3 import sqlite3 #connect to database file dbconnect = sqlite3.connect("mydb.db"); #If we want to access columns by name we need to set #row_factory to sqlite3.Row class dbconnect.row_factory = sqlite3.Row; #now we create a cursor to work with db cursor = dbconnect.cursor(); #execute insetr stateme...
from omtools.comps.vectorized_pnorm_comp import VectorizedPnormComp from omtools.comps.vectorized_axiswise_pnorm_comp import VectorizedAxisWisePnormComp from omtools.core.variable import Variable from typing import List import numpy as np def pnorm(expr, pnorm_type=2, axis=None): ''' This function computes th...
# cook your dish here # cook your dish here t=int(input()) for x in range(t): a,b,c=input().split() a=int(a) b=int(b) c=int(c) d=180 if(a+b+c==d): print("YES") else: print("NO")
""" Data: different labels must be in folders starting with 0, then 1 """ config = { "data_path":"../data", # don't include a "slash" on the end "batch_size":40, "num_epoch":30, "learning_rate":0.0001, # Resize input images "image_width":224, "image_height":224 }
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipaySecurityRiskVerifyidentityApplyModel(object): def __init__(self): self._account_id = None self._account_name = None self._account_type = None self._biz_id = ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-12-14 14:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chica_agenda', '0005_auto_20181214_1139'), ] operations = [ migrations.Alt...
import re from os import path import csv from string import punctuation import pandas as pd import pymorphy2 from nltk.corpus import stopwords CURRENT_DIR = path.dirname(path.abspath(__file__)) CITIES = set() with open(path.join(CURRENT_DIR, 'regions.csv'), 'r', encoding='UTF-8') as csvfile: rows = list(csv.read...
class Attrs: def __init__(self, start): self.wrapped = start def __getattr__(self, attr): return getattr(self.wrapped, attr) def __setattr__(self, attr, value): print("set", attr, value) self.__dict__[attr] = value
import re def parse_to_tuple(s): partten = re.compile(r'\((\d+)\)(\d+)+@(.+)') if partten.search(s) is None: return '正确格式为 (023)68001111@office ' else: return partten.search(s).groups() def parse_to_dict(s): partten = re.compile(r'\(([\d]+)\)(\d+)@(.+)') result = partten.search(s...
import redis import json import h5py import pickle import numpy as np import random import jieba import multiprocessing word2idx, idx2word ,allwords, corpus = None, None,{},[] DUMP_FILE = 'data/basic_data_700k_v2.pkl' check_sample_size = 10 TF_THRES = 5 DF_THRES = 2 r0 = redis.StrictRedis(host='localhost', port=63...
from tkinter import * from tkinter.filedialog import * import os es ="" # 편집을 위한 전역변수 선언 def newFile(): top.title("제목없음-메모장") file = None ta.delete(1.0,END) def openFile(): file = askopenfilename(title="파일 선택",filetypes=(("텍스트 파일","*.txt"),("모든 파일","*.*"))) top.title(os.path.basename(file)+"- 메모장"...
# id=5150 # The following code should print out to the screen the number 1232 in its binary, octal and hexadecimal representations. You should complete the missing code. # number=1232 # print(number) # number_bin = _____ # number_hex = _____ # number_oct = _____ # print(number_bin) # print(number_hex) # print(number_o...
print("What is the first number?") value1 = input() number1 = int(value1) print("What is the second number?") number2 = int(input()) if number1 == number2: print("THEY ARE THE SAME!!!!") else: if number1 > number2: print("The biggest is " + str(number1)) else: print("The biggest is " + str(...
""" Some functions to make testing slightly easier. """ from typing import List def assert_all_equal(left: List, right: List): """ Assert that each element of left is == each element of right in order. """ assert len(left) == len(right) assert all(x == y for x, y in zip(left, right))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 12 13:34:49 2018 @author: orlando """ import pandas as pd import numpy as np import collections import csv from sklearn import linear_model from sklearn import metrics #carrega os datasets train=pd.read_csv('dataset.csv', sep=';') # contem a base ...
# Generated by Django 3.1.5 on 2021-02-13 10:24 from django.db import migrations import easy_thumbnails.fields import users.models class Migration(migrations.Migration): dependencies = [ ('courses', '0010_auto_20210213_1302'), ] operations = [ migrations.AlterField( model_na...
""" Author -------- Best regards, Sungjin (James) Kim, PhD Postdoc, CCB in Harvard sungjinkim@fas.harvard.edu [Web] http://aspuru.chem.harvard.edu/james-sungjin-kim/ [Linkedin] https://www.linkedin.com/in/jamessungjinkim [Facebook] https://www.facebook.com/jamessungjin.kim [alternative email] jamessungjin.kim@gmai...
import webapp2 import os import jinja2 import cgi import re import random import string import hashlib #various hashing algorithms import hmac #hash-based message authentication code - for generating secret keys from google.appengine.ext import db template_dir = os.path.join(os.path.dirname(__file__), 'templates') ji...
from unittest import mock from testbase import * from live_client.events import raw DEFAULT_EVENT = {} A_TIMESTAMP = 1582927835001 DEFAULT_TIMESTAMP = 0 class TestCreateEvent: @mock.patch("live_client.connection.autodetect.build_sender_function", lambda _: no_action) @mock.patch("live_client.utils.logging...
import unittest import numpy as np from OptimalSpline import OptimalSpline class SplineTest(unittest.TestCase): def test_at_waypoints(self): c = np.array([[-1, 3, 0, 2], [-1, 0, 3, 4], [-1, -3, 0, 6]]).transpose() ts = [0, 1, 2, 3] s = OptimalSpline(c, ts) self.assertEqual(s.val(0,...
"""Crie um programa onde o user possa digitar 5 valores numéricos e cadastre-os em uma lista_geral. já na posição correta de inserção (sem usar o sort()). No final, mostre a lista_geral ordenada na tela.""" lista = [] for c in range(0, 5): print('-' * 30) num = int(input(f'Digite o {c+1}° valor: ')) ...
from django.db import models from django.contrib.auth.models import AbstractUser import django.utils.timezone as timezone from DjangoUeditor.models import UEditorField from rest_framework.authtoken.models import Token from django.dispatch import receiver from django.db.models.signals import post_save from django.conf ...
#!/usr/bin/env python3 # ######################################################################### # Copyright 2017 René Frieß rene.friess(a)gmail.com ######################################################################### # # This file is part of SmartHomeNG. # # SmartHomeNG is free software:...
def execute_instructions(instructions): # Returns True if execution reaches end of instructions (index > len(instructions)), otherwise returns False if loop acc = 0 index = 0 indices_used = [] max_index = 0 while index not in indices_used: if index >= len(instructions): prin...
# 使用类模块对鸢尾花进行训练 import numpy as np import tensorflow as tf from sklearn import datasets from tensorflow.keras import Model from tensorflow.keras.layers import Dense x_train = datasets.load_iris().data y_train = datasets.load_iris().target np.random.seed(116) np.random.shuffle(x_train) np.random.seed(116) np.random.sh...
from pyfcm import FCMNotification ''' # Send a message to devices subscribed to a topic. result = push_service.notify_topic_subscribers(topic_name="news", message_body=message) # Conditional topic messaging topic_condition = "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)" result = push_service.not...
# !/usr/bin/env python # -- coding: utf-8 -- # @Author zengxiaohui # Datatime:8/2/2021 12:48 PM # @File:demo2 # 以图片为圆心,根据像素点与圆心的距离来进行不同程度的光照增强。 # coding:utf-8 import cv2 import math import numpy as np import matplotlib.pyplot as plt def stronglight(img,rows,cols,strength = 200): # rows h,cols w # strength设置光照强...
import argparse import logging from src.data.arpa.make_arpa import make_arpa_dataset from src.data.make_dataset import make_dataset from src.data.weather.make_weather import make_weather_dataset from src.models.normalize_weather import predict_normalized_pollutant def parse_args(): parser = argparse.ArgumentPars...
"""Interactive Programming Mini-Project 4: Live Wallpaper Authors: Hwei-Shin Harriman and Jessie Potter References: http://programarcadegames.com/python_examples/en/sprite_sheets/""" import pygame import constants import random import math class SpriteSheet(object): """Class used to grab images out of a sprite sh...
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'search.views.index', name='home'), url(r'^direct_targets', 'search.views.direct_search', name='direct_sea...
# Day_03_04_sigmoid.py import math import matplotlib.pyplot as plt def show_sigmoid(): def sigmoid(z): return 1 / (1 + math.e ** -z) print(math.e) print(sigmoid(-10)) print(sigmoid(-1)) print(sigmoid(0)) print(sigmoid(1)) print(sigmoid(10)) for i in range(-10, 10): ...
#!usr/bin/env python # -*- coding: utf-8 -*- import xgboost as xgb from datetime import datetime # import judge_result import io_operation import sys def read_file_for_local_test():#本地测试的程序读写 f1 = open(sys.argv[4]) test_id_list = [] test_data_y = [] for eachline in f1 : if eachline.__contains__...
# Work with Python 3.6 import discord from discord.ext import commands from xml.dom import minidom import random import os import asyncio import globals try: mydoc = minidom.parse("CoOpBotParameters.xml") except: print("Unable to open file CoOpBotParameters.xml") raise # Unique Bot Token token = mydoc.get...
""" Keyword for safety It is a good idea to start using keyword arguments once a function or method has three more parameters. Especially, if there are optional parameters. Let us assume that we have to set the last maintenance date but we don't have an ad reel """ from screen_control import Screen3DControl screen6_...
import pyppeteer import asyncio from pyppeteer import launch width, height = 1366, 768 # # async def main(): # browser = await launch(headless=False) # page = await browser.newPage() # await page.setViewport({'width': width, 'height': height}) # await page.goto('https://www.taobao.com') # ...
import MeCab import os def TestFileOpen(dir, filename): full_path = os.path.join(dir, filename) with open(full_path, 'r') as file: sentence_list = file.readlines() return sentence_list def subtract_subjects(sentence_list): tagger = MeCab.Tagger('-d /usr/lib/x86_64-linux-gnu/mecab/dic/mecab-ipa...
def find_changes(sequence): # Finds changes between values in a list changes = [] for i in range(len(sequence)-1): changes.append(sequence[i+1]-sequence[i]) return changes def identify_sequence(changes): # Identifies the sequence level = 0 ...
from django.shortcuts import render, redirect from django.contrib import messages from .models import Quote from ..login_and_registration_app.models import User # import datetime # Create your views here. def index(request): # User.objects.all().delete() # Quotes.objects.all().delete() return render(request...
## Anthony Dike - Due: Nov. 28, 2017 ## CSCI-UA.0002-012 ## Assignment 8: Part 1 #This program converts the zeros with index values that are prime in the range of 1-1001 to ones. """ # KEY # 1 == NON PRIME # 0 = PRIME CHANGE TOTAL VALUE TO 1000 at end """ # Create a list of 1,000 values ... all of which are set to ...
from django.contrib import admin from gestionPeliculas.models import Pais, Director, Genero, Pelicula # Register your models here. admin.site.register(Pais) admin.site.register(Director) admin.site.register(Genero) admin.site.register(Pelicula)
from django.db import models from django.utils import timezone class Ideas(models.Model): date = models.CharField(max_length=200) costs = models.DecimalField(max_digits=8, decimal_places=2, default=0) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTi...
from komodo_outings import Outing outings = [] while True: print( """ Please choose an option: 1. To enter an outing 2. List all events 3. List the dollar total of all events 4. Subtotal of the dollar amount of event 5. Exit """) choice = input("Which option > ") if choice == "1": print("Adding n...
import pika import sys import json import redis bigHash = redis.Redis(db=14) bigHash.flushall() bigHash.hmset("1010", {'product_name':'Rubik\'s cube', 'quantity':'4', 'cost':'20', 'category':'Puzzle'}) bigHash.hmset("1001", {'product_name':'OnePlus3t', 'quantity':'2', 'cost':'637', 'category':'Phone|Black'}) bigHash...
import numpy as np from probability_model import ProbabilisticModel class MixtureModel(object): def __init__(self, allModels): self.model_list = allModels.copy() self.nModels = len(allModels) self.alpha = (1 / self.nModels) * np.ones(self.nModels) self.probTable = None self...
# import os import random from config_file import Config config = Config() filename_list = config.filename_list data_path = config.dataset_path def filereader(filename, dev_num): list_train = [] list_test = [] file_train = open(data_path + filename + '.task.train', 'r', encoding='gb18030',...
# Django settings for westiseast2 project. import os PROJECT_PATH = os.path.abspath(os.path.split(__file__)[0]) DEBUG = False GA_IS_ON = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Chris West', 'chris@fry-it.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add...
import numpy as np from lib.DQNAgent import DQNAgent from lib.PolicyAnalyzer import PolicyAnalyzer model = input("What is the name of the model file: ") agent = DQNAgent(4,2) agent.load('./saves/'+model+'.h5') def dql_policy(pos, vel, angle, angular_vel): state = np.reshape([pos, vel, angle, angular_vel], [1, 4...
class Powers: def __init__(self, square, cube): self._square = square self._cube = cube def __getattr__(self, item): if item == 'square': return self._square ** 2 elif item == 'cube': return self._cube ** 3 else: raise TypeError('Unkno...
from rest_framework import viewsets, status from rest_framework.decorators import list_route, detail_route from rest_framework.response import Response from .models import Question, Answer, Tournament, TournamentParticipation from .serializers import QuestionSerializer, QASerializer, TournamentSerializer, TournamentPar...
import sys,math,time from pgmpy.models import BayesianModel from pgmpy.factors.discrete import TabularCPD from pgmpy.inference import VariableElimination from GibbsSamplingWithEvidence import GibbsSampling from prettytable import PrettyTable import warnings warnings.simplefilter(action='ignore', category=FutureW...
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # © ОАО «Северное ПКБ», 2014 from setuptools import setup, find_packages setup(name="cluster-tools", version="0.1.6", description="библиотека утилит для кластера высокой готовности", author="Лаборатория 50", author_email="tea...
import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from KalturaClient import * from KalturaMetadataClientPlugin import * import logging import urllib import time import re logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s %(levelname)s ...
'''7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below. You can download the sample data at http://www.pythonlearn.com/code/words.txt''' fname = raw_input("Enter file n...
# -*- coding: utf-8 -*- import itchat import numpy as np import pandas as pd from collections import defaultdict import re import jieba import os import matplotlib.pyplot as plt from wordcloud import WordCloud, ImageColorGenerator import PIL.Image as Image itchat.login() friends = itchat.get_friends(updat...
# Hack Machine Language Assembler written in Python3 import sys import re # read assembly file(.asm) and parse file content into a list and returns the list, also update symbol table def readAssemblyFile(file, updateSymbolTable): assemblyProgramList = [] with open(file, mode='r') as f: lines = f.read(...
import numpy as np from numpy import cos, sin, tan, arctan, radians, degrees, arcsin, arctan2, sqrt, arccos from uncertainties import unumpy from math import log from scipy.linalg import lstsq from datetime import datetime import matplotlib.pyplot as plt from PyGEL3D import gel def dynecm2nm(x): return x * 1e-7 ...
import datetime import json from enum import Enum class TimeHelper: '''Useful module for converting times and shit. ''' @staticmethod def sec_to_str(sec): ''' Convert Seconds to readable text format :param sec: Seconds :return: ''' m = 0 h = 0 ...
# -*- coding: utf-8 -*- # # Copyright © 2012 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or impli...
import os.path import subprocess class SourcesList: def mostrar(self): f = open('/etc/apt/sources.list','r') return (True,f.read()) def guardar(self,linies): f = open('/etc/apt/sources.list','w') f.write(linies) def mostrarPropis(self): f = open('/usr/share/lliurex-apt2/reps','r') return (True,f.read...
from django.urls import path from student import views urlpatterns = [ path('home/', views.homeView, name="Home"), path('register/', views.registerView, name="register"), path('student/show/',views.showView,name="show_student"), path('register_student/', views.register.as_view(), name="Home"), pat...
#!/usr/bin/env python # This script is for getting more information out of the DSS ES instance about links.json files. # Source your environment correctly `source environment && source environment.{stage}` # Make sure to set your DSS_ES_ENDPOINT environment variable, this can be retrieved from running # `dssops lambda ...
from pymongo import MongoClient #client = MongoClient('mongodb://192.168.0.110:27019') client = MongoClient() database = client.chapter_3 collection = database.example_data_2 collection.insert_many([ {"name": "朱小三", "age": 20, "address": "北京"}, {"name": "刘小四", "age": 21, "address": "上海"}, {"name": "马小五", "a...
from ftplib import FTP def writeline(data): fd.write(data + "\n") f = FTP('ftp.kernel.org') f.login() f.cwd('/pub/linux/kernel') fd = open('README','wt') f.retrlines('RETR README',writeline) fd.close() fd = open("patch.gz",'wb') f.retrbinary("RETR README",fd.write) fd.close() f.quit()
# Generated by Django 3.1.6 on 2021-03-05 21:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('flight', '0002_flight_price'), ] operations = [ migrations.RemoveField( model_name='requirement', name='have_visa', ...
# -*- coding: utf-8 -*- """ Created on Mon Nov 28 10:02:21 2022 @author: Pierre Jouannais, Department of Planning, DCEA, Aalborg University pijo@plan.aau.dk """ ''' This script was used to combine different chunks of backrogund MC results to reach certain sizes that better match the computing performances of the ins...
import tensorflow as tf from tensorflow import keras from tensorflow.keras.models import Sequential from tensorflow.keras.preprocessing.image import ImageDataGenerator from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from tensorflow.keras.callbacks import EarlyStopping fr...
from collections import OrderedDict n, m = map(int, input().split()) ips1, ips2 = OrderedDict(), OrderedDict() for i in range(n): name, ip = input().split() ips2[ip] = name for i in range(m): name1, ip1 = input().split() ips1[name1] = ip1 for j in ips1: for i in ips2: if ';' in ips1[j] and ...
import sys, os, time, csv import pandas as pd from datetime import date from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from bs4 import Be...
#!/usr/bin/env python3 """ Takes input JSON output to produce new FAIR JSON """ from sys import argv import json def MakeDict(oldDict): retDict = {} retDict["text"] = oldDict["entity"] retDict["uri"] = oldDict["uri"] return retDict if len(argv) != 5: print("Usage: --input IN --output OUT") exit() else: fn...
from django.shortcuts import render,render_to_response from django.http import HttpResponse,HttpResponseRedirect,HttpRequest from nblik.models import Category,Blog,UserProfile,Comment,Follow,Discussion,Discuss,Tag,NblikInfo from nblik.forms import BlogForm from django.template.defaultfilters import slugify from django....
from pytorchcv.model_provider import get_model as ptcv_get_model import torch from torch.autograd import Variable net = ptcv_get_model("resnet18", pretrained=True) x = Variable(torch.randn(1, 3, 224, 224)) y = net(x) print(y) print(type(net))
import discord import sqlite3 import datetime from datetime import datetime, timedelta from discord import Embed from discord.ext import commands class Logging(commands.Cog): """Guild logging module""" def __init__(self, bot): self.bot = bot @commands.group(invoke_without_command=Tru...
from os.path import join from .dataset import DatasetFromFolder, DatasetFromFolder_simplified, DatasetFromFolder_in_test_mode from torch.utils.data import DataLoader def get_training_set(root_dir, direction): train_dir = join(root_dir, "train") return DatasetFromFolder(train_dir, direction,'train') def get...
class SpaceAge: Time={ "Earth":31558149.76, "Mercury":7600530.24, "Venus":19413907.2 "Mars":59354294.4,s "Jupiter":374335776.0, "Saturn":929596608.0, "Uranus":2661041808.0, "Neptune":5200418592.0 } def ...
from django.db import models from django.contrib.auth.models import User # Model for a website user, contains various fields of information about them class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) First_Name = models.CharField(max_length=20) Last_Name = models.Cha...
class Node: def __init__(self, data, next=None): self.data = data self.next = next def equal(left_node, right_node): left_none, right_none = left_node is None, right_node is None if left_none and right_none: return True elif left_none != right_none: return False else...
from toolz.functoolz import (thread_first, thread_last, memoize, curry, compose, pipe) from operator import add, mul from toolz.utils import raises import itertools def iseven(x): return x % 2 == 0 def isodd(x): return x % 2 == 1 def inc(x): return x + 1 def double(x): return 2 * x de...
#Exemplo de classe com decoração class Pessoa: def __init__(self, nome, idade): self._nome = nome self._idade = idade @propertyidade def idade (self): return self._idade @idade.setter def idade (self, idade): self._idade = idade @propertynome def nome (se...
import json import boto3 from io import BytesIO import os from torch import load as load_model from werkzeug.utils import secure_filename from flask import Flask, render_template, request, jsonify, send_file from flask_bootstrap import Bootstrap from cyclegan import model from PIL import Image UPLOAD_FOLDER = 'tmp' ALL...
#_*_coding:utf-8_*_ # 作者 :Administrator # 创建时间 :2020/4/116:41 # 文件 :test_login.py from case.login_case.login import func_login import allure import pytest @allure.story('测试登录接口') @allure.title('输入正确的账号密码,登录成功') def test_login_01(creat_data): user = 'test_hlp' pwd = '123456' r = func_...
import pymysql db = pymysql.connect(host='127.0.0.1', port=4000,user='zyh',password='zyh',db='test') cursor = db.cursor() cursor.execute('show tables') rsp = cursor.fetchall() cursor.close() db.close()
from django.db import models # Create your models here. # Products app with Product model. # Product : name, weight, price, created_at, updated_at class productModel(models.Model): name = models.CharField(max_length=255, blank=False, null=False) weight = models.IntegerField(blank=False, null=F...
# http://www.lintcode.com/zh-cn/problem/reverse-words-in-a-string/ def reverseWords(s): """ :param s: A string :return: A string """ length = len(s) list_word = [] i = 0 while i < length: if s[i] != " ": for j in range(i + 1, length): if s[j] == " ": ...
# renames duplicate columns by suffixing _1, _2 etc class renamer(): def __init__(self): self.d = dict() def __call__(self, x): if x not in self.d: self.d[x] = 0 return x else: self.d[x] += 1 return "%s_%d" % (x, self.d[x])
""" Package: app Package for the application models and services This module also sets up the logging """ import os import logging from flask import Flask # Create Flask application app = Flask(__name__) # Load Configurations app.config.from_object('config') app.config['SECRET_KEY'] = 'secret-for-dev' app.config['L...
""" Create a polygon class and a rectangle class that inherits from the polygon class and finds the square of rectangle. """ class Polygon: def __init__(self, name: str, no_of_sides): self.name = name self.no_of_sides = no_of_sides self.sides = [0] * no_of_sides def __repr__(self): ...
import sys from tables import * from optparse import OptionParser """Takes two .h5 files, one with correct analog data and the other one with bad analog data and returns a single .h5 file with all good data.""" usage = '%prog [options] analog.h5 stroklitude.h5 output.h5' parser = OptionParser(usage) (options, ...
def add(a,b): sum=a+b print(sum) a=int(input()) b=int(input()) add(a,b) #another code def add(*element): sum=0 for i in range(n): sum=sum+arr[i] print(sum) arr=[] n=int(input()) for i in range(n): data=int(input()) arr.append(data) add(arr,n)
import pytest from nn_models import model """ Run with oython -m pytest""" class TestModel: """Test for the model of a neural network.""" def test_Input_bias_Neuron(this): """Test for the bias/input neuron functionality.""" this.neru = model.Neuron(None) # an input neuron # outp...
import googlemaps as gm from datetime import datetime import matplotlib.pyplot as plt import math def get_matrix(destinations, method='distance'): gmaps = gm.Client("AIzaSyBwMwayIZrYwfwotUim0QOvKVu4YZPEnw8") cleaned = {} for i, d in enumerate(destinations[:-1]): cleaned = {**clean(i, gmaps.distanc...
cCurrencyDataSource = 'data/currency.json' cCurrencyUpdateDataDestination = 'data/currency_latest.json' cCurrencyURL = 'http://api.fixer.io/latest?base=INR' cShowsDataSource = 'data/shows.xml' cShowsUpdateDataDestination = 'data/shows.xml' cShowsURL = "http://showrss.info/rss.php?user_id=207042&hd=0&proper=null&raw=fa...
import RPi.GPIO as GPIO import time # blinking function def blink(pin): GPIO.output(pin, GPIO.HIGH) time.sleep(1) GPIO.output(pin, GPIO.LOW) time.sleep(1) return # to use Raspberry Pi board pin numbers GPIO.setmode(GPIO.BOARD) # set up GPIO output channel GPIO.setup(11, GPIO.OUT)...
""" A script used to evaluate the BalancedBaggingClassifiers trained on several (12) word2vec model outputs and using 50 or 100 decision tree estimators in order to choose the best (word2vec model, n_estimator) configuration. The criteria which will be used for selection is AUC score and the Brier score if necessary. "...
import os import sys import numpy as np sys.path.append(os.getcwd() + '/src') from PyExpUtils.results.results import loadResults, whereParametersEqual, splitOverParameter from experiment.tools import iterateDomains, parseCmdLineArgs from experiment import ExperimentModel def printStats(exp_paths, metric): print(...