text
stringlengths
8
6.05M
""" PRACTICE Test 2, practice_problem 4. Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder, their colleagues and Muqing Zheng. October 2015. """ # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE. import simple_testing as st import math def main(): """ Calls the TEST functions in this ...
#!/usr/bin/env /proj/sot/ska/bin/python ############################################################################################# # # # ccd_comb_plot.py: read data and create SIB plots ...
import io import os.path import string import sys from textwrap import dedent from hypothesis import given, example, note, assume from hypothesis.strategies import text from py2_compat import unittest, mock from django_develop import utils TEST_ROOT = os.path.dirname(__file__) class TestVirtualEnvDetection(unitt...
from matplotlib import pyplot as plt from skimage import data from skimage.feature import blob_dog, blob_log, blob_doh from math import sqrt from skimage.color import rgb2gray ''' Laplacian of Gaussian (LoG): 这是速度最慢,可是最准确的一种算法。简单来说,就是对一幅图先进行一系列不同尺度的高斯滤波,然后对滤波后的图像做Laplacian运算。将全部的图像进行叠加。局部最大值就是所要检測的blob,这个算法对于大...
STATIC_VERSION = "cad1f4d9"
import errno import numpy as np import pandas as pd import json import os import time from itertools import product from openpyxl import load_workbook def create_sections(number_of_sections: int, bound: tuple): """ Generate lat lon coordinates for the boundaries of sections :param number_of_sections: inte...
# -*- coding: utf-8 -*- """ Created on Thu Jun 6 11:17:51 2019 @author: Administrator """ import numpy as np from scipy import signal import matplotlib.pyplot as plt sig_freq = 470 noise_freq = 360 target_freq = 470 sample_freq= 4000 N = 4000 k = (N*target_freq)/sample_freq def windows(name='Hanning', N=20): # R...
# -*- coding: utf-8 -*- from ctypes import * class ADSB_Data_Struct(Structure): _pack_ = 1 _fields_ = [("ICAO", c_char*16), ("Flight_ID", c_char*16), ("Flight_24bit_addr",c_int32), ("Aircraft_Category", c_uint8), ("Altitude", c_int16), ...
"""Support for bunq account balance."""
from helper import helper import random as rm ''' Strict Donkey Hillclimber algorithm ''' def simulatedAnnealing(mel, mir, failValue, scoreFunction): ''' A probabilistic algorithm for approximating the global optimum of a given function, the global optimum being the final mutation (swap) that changes t...
import random print(random.randint(5, 20)) # line 1 print(random.randrange(3, 10, 2)) # line 2 print(random.uniform(2.5, 5.5)) # line 3 # line one 5 was the smallest i got and 20 was the largest # line two 3 was the smallest and 9 was the largest # line three was 3.6711 and largest was 4.952 print() print(random.r...
valor = int(input('Digite o valor a ser sacado: ')) cinquenta = vinte = dez = um = 0 ced = 50 '''código do professor: total = 0 while True: if valor >= ced: valor -= ced total += 1 else: if total > 0: print(f'Total de {total} cédulas de {ced}') if ced == 50: ...
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('administration', '0004_auto_20191019_0158'), ] operations = [ migrations.AlterField( model_name='clients', name='id_country', ...
import pandas as pd friend_list = [ ["John", 25, "student"], ["Nate", 30, "teacher"], ["Jenny", 30, None] ] column_name = ["name", "age", "job"] df = pd.DataFrame(friend_list,columns=column_name) #조건에 맞는 행 보여주기 print(df[1:3]) #슬라이싱 가능 print() print(df.loc[[0,2]]) #0행과 2행 보여줌 print() print(...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('FBData', '0004_auto_20150614_1552'), ] operations = [ migrations.AlterField( model_name='fbdata'...
#!/proj/sot/ska3/flight/bin/python ##################################################################################### # # # update_sim_flex.py: update sim_flex difference data sets # # ...
#!/usr/bin/env python # Copyright 2009-2014 Eucalyptus Systems, 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 ...
import os import json def extract_route(req): return req.split()[1][1:] def read_file(path): nome1,nome2 = os.path.splitext(path) lista_arq = [".txt", ".html", ".css",".js"] if nome2 in lista_arq: f = open(path, "rt") return f.read().encode(encoding="utf-8") else: f = op...
from neo4j.v1 import GraphDatabase uri = "bolt://localhost:7687" driver = GraphDatabase.driver(uri, auth=("neo4j", "Password")) def get_skills_by_attribute(attr): with driver.session() as session: with session.begin_transaction() as tx: Skills = tx.run("Match (:Attribute{Name:$name})-[:UNLOCK...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ПОРЯДОК ИСПОЛЬЗОВАНИЯ: apache_log_parser_split.py some_log_file Анализирует содержимое лог-файла и генерирует отчет, содержащий перечень удаленных хостов, кол-во переданных байт и код состояния """ import sys def dictify_logline(line): """ Parse logline and ...
import subprocess import torch subprocess.call( "pip install git+https://github.com/facebookresearch/fvcore.git", shell=True ) net = torch.hub.load("zhanghang1989/ResNeSt", "resnest50", pretrained=True)
import boto3 region = 'us-east-1' # db_instance = 'db-instance-identifier' rds = boto3.client('rds', region_name=region) dbs = rds.describe_db_instances() for output in dbs['DBInstances']: print('Master Username: ' + output['MasterUsername'] + '\nBackup Window: ' + output['PreferredBackupWindow']) # print ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from player import * from smart_contract import * from blockchain import * accounts = [] new_game_flag=1 while new_game_flag: print() blockchain = BlockChain() players = [] """ 三人游戏,创建游戏账户 """ while len(players) < 3: str_1 = input('You want to c...
# -*- coding: utf-8 -*- import requests class neteasemusic(): def __init__(self, cookie): self.s = requests.Session() self.url = 'http://music.163.com/api/point/dailyTask?type=1&csrf_token=123' self.header = { 'Pragma':'no-cache', 'DNT':'1', 'Accept-Enco...
t = int(input()) mod = 10**9 + 7 while (t): t -= 1 num, k = [int(x) for x in input().split()] ans = k-1 l = k-num a = l%(num-1) d = num-1 n = (l-a)//d + 1 ans += (n*(a+l))//2 if (n >= k): ans = k-1 print(ans%mod)
import json from allauth import utils from core.forms import ProfileForm, TeamForm, InviteUserForm from core.models import Event, Team, TeamMember from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required from django.core.exceptions imp...
# #!/bin/python3 # # import math # import os # import random # import re # import sys # # # # Complete the arrayManipulation function below. # def arrayManipulation(n, queries): # lista_final = [0 for _ in range(n)] # for i in range(len(queries)): # for j in range(queries[i][0], queries[i][1]+1): # ...
#------------------------------------------------------------------------------- # Name: NLTK-Entity-Extraction # Author: Pratap Vardhan # Created: 17-10-2013 #------------------------------------------------------------------------------- import nltk # Read the file f = open('file.txt') # Each sente...
#!python # encoding: utf-8 # Created by djg-m at 07.01.2021 from handling_db import SqlHandling class ManageDB: """ Creates a database and relations for messenger application. """ def __init__(self, db): self.database = db self.db = None def create_db(self): """ ...
import pygame class Screen: screen = None background = None # Constructor for the screen object that uses the above screen size declarations # background should be an SDL_rect def __init__(self, w, h): # Screen settings self.screen = pygame.display.set_mode((w, h)) ...
# -*- coding: utf-8 -*- # Copyright 2017 IBM RESEARCH. 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 requ...
import sys from node import * #input params, where we make two lists, and make them intersect input_list_1 = list([1, 9, 3, 6, 5, 11, 3, 2]); input_list_2 = list([11, -1, 2, 4, 3, 7, 8, 9]); intersect_index = 3; linked_list_1 = node(); linked_list_1.make_list(input_list_1); linked_list_2 = node(); linked_list_2.make_...
import socket import threading import tkinter import tkinter.messagebox # 服务器 Ip = '127.0.0.1' Port = 50007 ServerAddr = (Ip, Port) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(ServerAddr) Channel = '0' # 表示不在任何一个聊天室 UserId = '0' # 表示还未进入聊天室,没有username UserName = 'server' Rooms = [] # 聊天室 [...
# -*- coding: utf-8 -*- """ Created on Sat Jun 24 10:03:22 2017 @author: Jonathan Morgan """ from subprocess import call import sys import re from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtWidgets import QWidget, QStackedWidget, QApplication,\ QLineEdit, QCheckBox, QLabel, QAction, QMainWindow, QF...
# Libraries import time import allFunctionFiles # all function required imported # serial setup port = "/dev/ttyUSB1" baud = 9600 ser = serial.Serial(port, baud, timeout=None) # Initializing Variables obstacle_list = [] # List storing locations(node numbers) of obstacles turn_cost_90 = 510 # Turn cost used for a...
import sys,re,os.path def RemoveAtAt(Line): AtAtFinder = re.search('(.*?)(@.*?@)(.*)',Line) if AtAtFinder: OneDown = AtAtFinder.group(1)+AtAtFinder.group(3) return RemoveAtAt(OneDown) else: return Line def FormatSplit(Line): return Line.replace('==','@') def AddNewline(Line): if Line[-1] == '\n': return...
# -*- coding: utf-8 -*- """ Created on Thu Apr 30 12:17:09 2020 @author: anusk """ import numpy as np from scipy.stats import entropy from math import log, e import pandas as pd import copy import cv2 def entropy2(labels): """ Computes entropy of label distribution. """ n_labels = labels.size if...
import pde from matplotlib import pyplot as plt import sys import logging logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) f,ap = plt.subplots(3) f,ae = plt.subplots(3) prob = pde.problems.instpoisson1d.quad prob.plot(ap) n=100 solver = pde.solvers.classic.poisson_pwlinear_1d_solver(prob) solver.solve(n=10...
# Faça um Programa que converta metros para centímetros. # entrada de dados metros = float(input('Digite uma distância em metros: ')) # processamento centimetros = int(metros * 100) mensagem = '{} metros equivalem a {} centímetros'.format(metros, centimetros) # saída de dados print(mensagem)
class ResultadoDFS: def __init__(self, tiempo_visitado, tiempo_finalizado, bosque): self.bosque = bosque self.tiempo_finalizado = tiempo_finalizado self.tiempo_visitado = tiempo_visitado def get_tiempo_visitado(self): return self.tiempo_visitado def get_tiempo_finalizado(s...
# Generated by Django 2.1.2 on 2019-01-28 07:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0037_auto_20190128_0919'), ] operations = [ migrations.AlterField( model_name='product', name='product_d...
# Generated by Django 2.1 on 2018-08-12 20:58 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name=...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jul 28 11:46:46 2017 @author: ian """ import pandas as pd import matplotlib.pyplot as plt from scipy.stats import linregress import datetime as dt import numpy as np import DataIO as io path='/home/ian/OzFlux/Sites/GatumPasture/Data/Processed/All/Ga...
import random, string with open('./9.txt', 'w') as f: for i in range(100): len = random.randint(11, 14) f.write(''.join(random.choices(string.ascii_lowercase + string.ascii_uppercase + string.digits, k = len)) + "\n") f.close()
#!/usr/bin/env python3 import csv class csvToDB: playerlist = [] def csvImporter(self, csv): with open('/home/tyrell/app/files/player_data.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) return reader def csvExportToPostgre(self, reader): for row i...
# coding: utf-8 ''' Created on 2017-05-16 @author:Alex Wang 执行shell命令 ''' import os import subprocess import threading import time def run(cmd, timeout=None, timeit=False): if timeit: start_time = time.time() # print('[+] start({}) {}'.format(timeout, ' '.join(cmd))) d = subprocess.run(cm...
# -*- coding: utf-8 -*- """ Created on Wed Jan 17 19:11:07 2018 功能:获取头条新闻、体育资讯等资料 接口:聚合数据api接口,可以根据 type_参数来调整获取的新闻类型 @author: mynumber """ from urllib.request import urlopen from urllib.error import HTTPError,URLError import json class News(object): """浏览信息,可以读取新闻的标题,文本等内容""" def __init__(self)...
{ 'target_defaults': { 'msvs_settings': { 'VCCLCompilerTool': { 'WarningLevel': '4', 'WarnAsError': 'true', }, }, 'msvs_system_include_dirs': [ '$(ProjectName)', # Different for each target 'common', # Same for all targets ], }, 'targets': [ { 't...
__author__ = 'VHLAND002' import sys import parse_ula # array that will hold all variables that have been defined definedVars = [] semantic_errors = [] # traverses the tuples to create the AST recursively # @param: tree- this is the tuple list we get # @param: value- this is the indentation value for the tab chars ...
""" Taylor-Green Vortex """ from phi.flow import * def taylor_green_pressure(x): return math.sum(math.cos(2 * x * VORTEX_COUNT), 'vector') / 4 * math.exp(-4 * VORTEX_COUNT ** 2 * t / RE) def taylor_green_velocity(x): sin = math.sin(VORTEX_COUNT * x) cos = math.cos(VORTEX_COUNT * x) return math.exp(-...
import torch import torch.nn as nn class DetectNet(nn.Module): def __init__(self, vis_sys, num_classes, vis_sys_n_out, embedding_n_out=512): super(DetectNet, self).__init__() self.vis_sys = vis_sys self.embedding = nn.Sequ...
# -*- coding: utf-8 -*- """ Created on Fri Aug 23 23:30:14 2019 @author: HP """ #dividing array into two arrays of equal sums #can be done by using DP s1=[] s2=[] def two_sum(arr,i,sum1): if i==0: if (arr[i]==sum1): s1.append(arr[i]) return 1 elif sum1==0: s2.app...
from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponse from project import settings # Create your views here. # @login_required def index(request): lang = request.META.get('LANGUAGE', request.META.get('LANG')) if lang is None: ...
#Write a Python program that accepts a string and calculate the number of digits and letters Sample Data : Python 3.2, Expected Output : Letters 6, Digits 2: data=str(input("Enter your data here: ")) digits=0 letters=0 for i in data: if i=='0' or i=='1' or i=='2' or i=='3' or i=='4' or i=='5' or i=='6' or i=='...
#Qwerty@123 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import Keys MY_ADDRESS = Keys.getEmailID() PASSWORD = Keys.getEmailPassword() TO_ADDRESS = "kamarajk@tcd.ie" def sendEmail(): s = smtplib.SMTP(host = 'smtp.gmail.com', port = 587) s.starttls() ...
def diff(A, B): l = len(A) n = 0 for i in range(l): if A[i] != B[i]: n += 1 return n AB = input() A, B = AB.split()[0], AB.split()[1] d = len(A) for i in range(len(B) - len(A) + 1): d2 = diff(A, B[i:i + len(A)]) if d2 < d: d = d2 print(d) # Done
# -*- coding: utf-8 -*- from flask import request, Blueprint from flask import g import json import hashlib import logging from libs.util import make_response from libs.util import create_access_token from libs.response_meta import ResponseMeta from .authorization import require_application_auth from models.user import...
'''Database models News API''' from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class DataTimeMixin: ''' Mixin for initializing relevant sqlalchemy columns datetime columns containing current datetime ''' create_at = db.Column(db.DateTime, default=db.func.now()) class NewsArticle(Dat...
import time import queue import random import threading from tkinter import * from tkinter.dialog import * from collections import deque class GUI(Tk): def __init__(self, queue): Tk.__init__(self) self.queue = queue self.is_game_over = False self.canvas = Canvas(self, width = 495, h...
from django.shortcuts import render, redirect from .form import ProduitForm,FactureForm from django.contrib.auth.decorators import login_required from django.http import HttpResponse from .models import Produit, Facture # Create your views here. @login_required(login_url='/register/login/') def AjouterProduit(requ...
import numpy as np import torch from tqdm import trange from .inception import InceptionV3 def get_inception_score(images, device, splits=10, batch_size=32, verbose=False): block_idx = InceptionV3.BLOCK_INDEX_BY_DIM['prob'] model = InceptionV3([block_idx]).to(device) model.eval() ...
# @see https://adventofcode.com/2015/day/17 from itertools import combinations with open('day17_input.txt', 'r') as f: containers = [int(l) for l in f] def calc_num_of_ways(c: list): min_ways, max_ways = 0, 0 l = len(c) # Generate all combinations of containers # Use [combinations of] the index of the li...
import wave from scipy import fromstring, int16 import numpy as np from scipy import signal import matplotlib.pyplot as plt #wavfile = 'hirakegoma.wav' wavfile = 'ohayo.wav' wr = wave.open(wavfile, "rb") ch = wr.getnchannels() width = wr.getsampwidth() fr = wr.getframerate() fn = wr.getnframes() nperseg = 256 #4096 #...
# Generated by Django 2.0.5 on 2018-06-04 08:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('calculation', '0011_map_unit'), ] operations = [ migrations.CreateModel( name='Calculation', ...
"""Utility functions for AUACM package""" import requests from auacm.common import BASE_URL def log(message): """Log a message""" print(message) callbacks = dict() def subcommand(command): """Decorator to register a function as a subcommand""" def wrapped(function): """Add the function to th...
from selenium.webdriver.common.by import By from pageObjects.checkOutPage import checkOutPage class HomePage: # define constructor def __init__(self, driver): self.driver = driver shop = (By.LINK_TEXT, "Shop") def shopItems(self): # return self.driver.find_element(*HomePage.shop) ...
# -*- coding: utf-8 -*- from django import forms from ckeditor.widgets import CKEditorWidget class PostAdminForm(forms.ModelForm): desc = forms.CharField(widget=forms.Textarea, label='摘要', required=False) content = forms.CharField(widget=CKEditorWidget(), label='正文', required=True)
# imports import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error import numpy as np # read in the data drinks = pd.read_csv('https://raw.githubusercontent.com/sinanuozdemir/python-data-science-workshop/master/drinks.csv', na_filter=False) # features X = dr...
#!/usr/bin/env python3 """Filter SNPS from the output of 03_saf_maf_gl_depth_all.sh Usage: <program> angsd_output_folder filtered_folder window_size min_maf max_maf_other_snps max_surrounding_snps Where: window_size is the number of base pairs on each side where surrounding SNPs are searched min_maf is th...
def int_to_bin(n): return format(n, 'b')
import random as r import time as t import os num1 = r.randint(2, 9) num2 = r.randint(1, 9) start = t.time() calc = int(input("%d * %d = "%(num1,num2))) end = t.time() t.sleep(2) #뜸들이기 if calc == num1 * num2: if end - start < 2: print("천재") else: print("보통") else: print("실망이...
def nested_lists(): allscores = set() allnames = [] for i in range(int(input())): list = [] name = input() score = float(input()) list.append(name) list.append(score) allscores.add(score) allnames.append(list) allnames.sort(key=lambda x: x[1]) ...
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import tensorflow as tf sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, shape=[None, 784], name="x") batch_size = tf.placeholder(tf.int32, None, name="batch_size") def weight_variab...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 识别人脸鉴定是哪个人 # 导入face_recogntion模块,可用命令安装 pip install face_recognition import face_recognition #将jpg文件加载到numpy数组中 liu_image = face_recognition.load_image_file("liu.jpeg") liming_image = face_recognition.load_image_file("liming.jpeg") #要识别的图片 unknown_image = face_recognit...
import pipes class CEProbeScript(object): """A class used to generate job-scripts for CE probes.""" def __init__(self): self._required_files = [] self._generated_files = [] def require_file(self, fname, size = None, sha1sum = None): self._required_files.append((fname, size, sha1sum)) def generate...
#!/usr/bin/env python import sys from matplotlib import pyplot as plt import parmed as pmd orig_lib, new_lib, resname0, resname1 = sys.argv[1:] res0 = pmd.load_file(orig_lib)[resname0] res1 = pmd.load_file(new_lib)[resname1] c0 = [a.charge for a in res0.atoms] c1 = [a.charge for a in res1.atoms] print(c0, sum(c0)) ...
# Exercício 6.17 - Livro estoque = { 'tomate': [50, 2.30], 'alface': [35, 0.45], 'batata': [60, 1.20], 'feijão': [20, 1.50] } while True: print('=-=' * 10) produto = str(input('Informe o produto desejado: ')).lower() if produto == 'sair': print('FIM') break elif produto ...
import os import sys import shutil sys.path.insert(0, 'scripts') sys.path.insert(0, 'tools/families') sys.path.insert(0, 'tools/trees') import experiments as exp import fam from ete3 import SeqGroup def get_genes(input_ali): msa = SeqGroup(input_ali) genes = set() for entry in msa.get_entries(): genes.add(en...
""" In training scheme 1, we don't anneal anything. There is an initial round of training without RL, followed by a fragment wherein the exploration is gradually decreased. There are 3 main hyper-parameters: * area_weight during stage 0 * area_weight during remaining stages * nonzero_weight during remaini...
import xml_path import uuid from numpy import logical_and import pandas as pd from datetime import timedelta import init_data_struct as ids # all eval_ methods def eval_leg_type_error(leg): leg_type = xml_path.get_leg_type(leg) if leg_type == 'OEV': # previously get_leg_route_category(), shoiuld be...
import unittest from katas.beta.what_day_is_it import day class DayTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(day('20151208'), 'Tuesday') def test_equals_2(self): self.assertEqual(day('20140728'), 'Monday') def test_equals_3(self): self.assertEqual(day(...
from os import times_result import composite as cp import filter import get_VIs as vi import harmonize import export_as_geotiff as exp import ee def wrapper_prep(params): ''' This function prepares each Landsat collection for merging by filtering for appropriate parameters and harmonizing collection ...
import sponsorapp.views as sponsorapp from django.urls import path app_name = 'sponsorapp' urlpatterns = [ path('sponsor/', sponsorapp.sponsor, name='sponsor'), ]
import pytube from pytube.cli import on_progress url = input("Input video's url: ") video = pytube.YouTube(url, on_progress_callback=on_progress) stream = video.streams.get_highest_resolution() stream.download('C:\\Users\\Workspace\\Downloads') print('Done!')
import unittest from katas.kyu_6.next_version import next_version class NextVersionTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(next_version('1.2.3'), '1.2.4') def test_equals_2(self): self.assertEqual(next_version('0.9.9'), '1.0.0') def test_equals_3(self): ...
def get_diagonal(arr): index = 0 diagonal = [] for row in arr: number = row[index] diagonal.append(number) index += 1 return diagonal def diagonal_difference(arr): first_diagonal = get_diagonal(arr) arr.reverse() second_diagonal = get_diagonal(arr) return abs...
from Geometry import Point, Rectangle def main(): p1 = Point(2,5) p2 = Point(5,6) r1 = Rectangle(p1,p2) print("Area=" + str(r1.getArea())) print("Perimeter=" + str(r1.getPerimeter())) r1.dilate(3) print("\nDilated by 3") print("Area=" + str(r1.getArea())) print("...
import math import numpy as np def similarity(v1, v2): dot = np.dot(v1, v2) mag1 = np.linalg.norm(v1) mag2 = np.linalg.norm(v2) return dot / (mag1 * mag2) def angle(v1, v2): sim = similarity(v1, v2) return math.degrees(math.acos(sim)) def mbti_similarity(mbti1, mbti2): m1 = np.array(m...
from matplotlib import pyplot as plt def smooth_line(li,size): retract = (size-1)//2 for i in range(retract,len(li)-retract): li[i] = sum(li[i-retract:i+retract])/size return li def draw_loss(losslist,epoch,savepath): plt.rcParams['font.sans-serif'] = ['KaiTi'] plt.rcParams['axes.unicode_min...
#!/usr/bin/env python #-*-coding:utf-8-*- # @File:adaboost_model.py # @Author: Michael.liu # @Date:2020/6/18 17:36 # @Desc: this code is .... import numpy as np import pandas as pd import time import json import matplotlib.pyplot as plt from sklearn.ensemble import AdaBoostClassifier from sklearn.tree import Decision...
from django import forms from .models import Feature class featureForm(forms.ModelForm): class Meta: model = Feature fields = ('featureName','description') labels = { 'featureName': 'Title' }
import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from dsn.util.systems import LowRankRNN from dsn.train_dsn import train_dsn import pandas as pd import scipy.stats import sys, os os.chdir("../") nlayers = int(sys.argv[1]) c_init_order = int(sys.argv[2]) sigma_init = float(sys.argv[3]) random...
import cv2 import numpy as np def hsv_shadow_remove(frame_rgb, background_rgb): #Define variable alpha = 0.4 beta = 0.6 th = 0.1 ts = 0.5 #CHANGE THE INITIALIZATION foreground_without_shadows = [] hsv_frame = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2HSV) hsv_background = cv2.cvtColor(...
import os wpos_x = 100 wpos_y = 100 os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (wpos_x,wpos_y) import pygame from pygame.locals import * import random text_size = 60 bg_col = (0,0,0) text_col = (255,255,255) w_width = 640 w_height = 480 try: pygame.init() w = pygame.display.set_mode((w_width,w_height)) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 打印 print "hello wrold!" print "hello Again" print "I like typing this." print "this is fun" print "Yay,printing." print "I'd much rather you 'not'" print 'I "sad " do not touch this' print "this is another line"
# -*- coding: utf-8 -*- class Solution: def arrayNesting(self, nums): result = 0 for num in nums: if num is None: continue current, length = num, 0 while nums[current] is not None: previous = current current = num...
print('Faça um programa que leia tres numeros e mostre qual é o maior e qual é o menor') n1 = int(input('Escreva um número: ')) n2 = int(input('Escreva um número: ')) n3 = int(input('Escreva um número: ')) print('O maior número desses é o {}'.format(max(n1, n2, n3))) print('O menor número desses é o {}'.format(min(n1...
name = input("Enter Name: ") age = input("Enter Age: ") print('Name: ', name) print('Age after 2 years: ', int(age) + 2)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import List, Optional, Tuple import numpy as np from gym import spaces from gym.core import Env from mtenv.utils import seeding from mtenv.utils.types import ActionType, DoneType, EnvObsType, InfoType, RewardType StepReturnType = Tupl...
import turtle import math # class circle class Circle: def __init__(self,snow,radius,x,y): snow.snowmani.up() #set the initial absolute direction of turtle snow.snowmani.sety(y) #set the x and y coordinates of the turtle.These will act as initial points.Could have used goto too here. snow.snowmani.setx(x) arc...