blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30
values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2
values | text stringlengths 12 5.47M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
5f37f8ed4fa60ac826cc302595fcbdd401f0da9e | Python | akash9579/python_snippets | /py8_functions.py | UTF-8 | 1,853 | 4.0625 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 11:08:45 2020
@author: akash
"""
#############################################################
def hello ():
pass #this function doing nothing
print(hello) # gives us the location
# for running that function u have to give()
hello()
def hello1 (): # we are excuting basic function
print("hi bro")
hello1()
def hello2 (): # here we are returnig something instead of running something
return "hi bro"
a=hello2()
print(a)
type(a)
def hello3 (variable):
return "{} bro".format(variable)
hello3() # giving error that 1 argument is required
hello3("ssup")
print(hello3("ssup"))
print(hello3("ssup").upper())
def hello4 (name,name1='akash'): # name1 has default value is akash
print("{}+{} this is my name".format(name,name1))
hello4(2)
hello4('akash') # we are just passing just 1 argument but we dont getting anu error
# beacuse 2nd argument have deafult value
hello4('kamerkar','jaggu')
month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # Number of days per month. First value placeholder for indexing purposes.
def is_leap(year):
"""Return True for leap years, False for non-leap years.""" # its always better to give function information
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def days_in_month(year, month):
"""Return number of days in that month in that year."""
if not 1 <= month <= 12:
return 'Invalid Month'
if month == 2 and is_leap(year):
return 29
return month_days[month]
is_leap(2014)
is_leap(2020)
days_in_month(1997, 2)
days_in_month(1997, 3)
days_in_month(1996, 2)
| true |
27486eea98626f78637303b1d0861bc35598854d | Python | lioncruise/alibaba-clusterdata-analysis | /src/server_cpu_usage_in_time_and_space.py | UTF-8 | 1,275 | 2.75 | 3 | [
"MIT"
] | permissive | import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from src.common.column_name import server_usage_column_name
if __name__ == '__main__':
path = '..\dataset\server_usage.csv'
try:
f = open(path, 'r', encoding='utf-8')
data = pd.read_csv(f)
df = pd.DataFrame(data)
df.columns = server_usage_column_name
df = df.pivot(index='machine_id', columns='timestamp', values='cpu')
norm = mpl.colors.Normalize(vmin=0, vmax=100) # 标准化2D图colorbar的范围
im = plt.imshow(df, interpolation='nearest', aspect='auto', norm=norm)
plt.gca().invert_yaxis() # 默认的y轴坐标画出来是反的
# 将x轴的坐标转换成小时为单位
to_hour = lambda x, pos: x / 12
plt.gca().xaxis.set_major_formatter(FuncFormatter(to_hour))
plt.xticks((0, 24, 48, 72, 96, 120, 144))
plt.colorbar(im, fraction=0.015, pad=0.05).ax.set_ylabel('CPU usage (%)')
plt.title('server CPU usage in time and space')
plt.xlabel('time (h)')
plt.ylabel('machine (id)')
plt.show()
except FileNotFoundError:
print('CSV file not found!')
finally:
print('finish')
| true |
5e5c28cdc863e1f27a4317d52ca17395fbed6306 | Python | nimcrash/myfirstparser | /parser.py | UTF-8 | 843 | 2.96875 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import argparse
param_parser = argparse.ArgumentParser()
param_parser.add_argument('count', help = 'количество выводимых книг', type = int, choices = range(0,101))
param_parser.add_argument('path', help = 'путь к файлу', type = argparse.FileType('w'))
args = param_parser.parse_args()
url = 'http://readrate.com/rus/ratings/top100'
r = requests.get(url)
soup = BeautifulSoup(r.text, features = 'html.parser')
books = soup.findAll('div', {'class':'info'})
for i in range(args.count):
book = books[i].find('div', {'class' : 'title'}).find('a').text
author = books[i].find('ul', {'class' : 'contributors-list list'}).find('a').text
string = "%s - %s" % (book, author)
print(string)
args.path.write(string + '\n')
args.path.close()
| true |
e57cb119c7ee482b9375f68accda68918ee4650f | Python | djskl/Study_RabbitMQ | /B_subscribe/emit_logs.py | UTF-8 | 1,205 | 2.90625 | 3 | [] | no_license | '''
Created on Feb 23, 2016
@author: root
'''
import pika
class Logs(object):
def __init__(self, host="localhost"):
self.host = host
def __call__(self, func):
def _wraper(*args, **kwargs):
try:
kwargs["conn"] = pika.BlockingConnection(pika.ConnectionParameters(host=self.host))
func(*args, **kwargs)
finally:
kwargs["conn"].close()
return _wraper
@Logs()
def send(*args, **kwargs):
conn = kwargs["conn"]
channel = conn.channel()
channel.exchange_declare(exchange="logs", exchange_type="fanout")
msg = ",".join(args) or "info: empty log"
channel.basic_publish(exchange="logs", routing_key="", body=msg)
print "[x] sent: %s"%msg
if __name__ == "__main__":
msgs = [
["1","2"],
["2","2","2"],
["3","3","3","3"],
["4","4","4","4","4"],
["5","5","5","5","5","5"],
]
for msg in msgs:
send(*msg)
| true |
95110cccadf7bd653209b5e0b0bbc38a8098e78e | Python | brockryan2/ArcGIS_utils | /SDE_Maintenance_DateTimeHandling.py | UTF-8 | 3,923 | 3.671875 | 4 | [
"Apache-2.0"
] | permissive | import datetime
class CustomDateTime(object):
print("Assigning date/time variables...")
date = None
time = None
def __init__(dateTimeObject_day, dateTimeObject_month, dateTimeObject_year, dateTimeObject_hour, dateTimeObject_minute, dateTimeObject_second, self, *args, **kwargs):
date = str(dateTimeObject_year)
time = ''
def checkMonthLength(self, dateTimeObject_month):
# if the month number is less than 10 -->
if(int(month) < 10):
# then a leading "0" gets assigned to the "monthString" variable
monthString = "0"
# then the month number is appended, useful for making 1 into 01 which is more human-readable in a file name
monthString = monthString + (str(month))
# otherwise, the two-digit month number gets cast from an int to a String, then is assigned to the "monthString" variable
else: monthString = str(month)
date = date + '-' + monthString
def checkDayLength(self, dateTimeObject_day):
if(int(day) < 10):
# then a leading "0" gets assigned to the "dayString" variable
dayString = "0"
# then the day of the month is appended, useful for making 1 into 01 which is more human-readable in a file name
dayString = dayString + (str(day))
# otherwise, the two-digit day gets cast from an int to a String, then is assigned to the "dayString" variable
else: dayString = str(day)
date = date + '-' + dayString
def checkHourLength(self, dateTimeObject_hour):
# if the hour number is less than 10 -->
if(int(hour) < 10):
# then a leading "0" gets assigned to the "hourString" variable
hourString = "0"
# then the hour number is appended, useful for making 1 into 01 which is more human-readable in a file name
hourString = hourString + (str(hour))
# otherwise, the two-digit hour number gets cast from an int to a String, then is assigned to the "hourString" variable
else: hourString = str(hour)
time = hourString
def checkMinuteLength(self, dateTimeObject_minute):
# if the minute number is less than 10 -->
if(int(minute) < 10):
# then a leading "0" gets assigned to the "minuteString" variable
minuteString = "0"
# then the minute number is appended, useful for making 1 into 01 which is more human-readable in a file name
minuteString = minuteString + (str(minute))
# otherwise, the two-digit minute number gets cast from an int to a String, then is assigned to the "minuteString" variable
else: minuteString = str(minute)
time = time + ':' + minuteString
def checkSecondLength(self, dateTimeObject_second):
# if the second number is less than 10 -->
if(int(second) < 10):
# then a leading "0" gets assigned to the "secondString" variable
secondString = "0"
# then the second number is appended, useful for making 1 into 01 which is more human-readable in a file name
secondString = secondString + (str(second))
# otherwise, the two-digit second number gets cast from an int to a String, then is assigned to the "secondString" variable
else: secondString = str(second)
time = time + ':' + secondString
checkDayLength(dateTimeObject_day)
checkMonthLength(dateTimeObject_month)
checkHourLength(dateTimeObject_hour)
checkMinuteLength(dateTimeObject_minute)
checkSecondLength(dateTimeObject_second) | true |
ae1f4362255e27c1abcaee70d43cded00cb50120 | Python | henriquecl/Aprendendo_Python | /Exercícios/Lista 2 - Seção 5 - Condicionais/Lista 2 - Com todas as questões juntas.py | UTF-8 | 5,354 | 4.53125 | 5 | [] | no_license | """
# Exercício 1 - Faça um programa que receba dois números e mostre qual o maior
# NOTE: Se não colocar o float(input..) ele não vai interpretar o numeral, e sim a string.
num1 = float(input('Digite um numero\n'))
num2 = float(input('Digite outro numero\n'))
if num1 > num2:
print(f'{num1} é maior que {num2}')
elif num2 > num1:
print(f'{num2} é maior que {num1}')
else:
print('Os numeros são iguais')
# Exercício 2 - Leia um número fornecido pelo usúario. Se for positivo
# calcular a raiz quadrada. Se for negativo diz q nao pode
num = float(input('Digite um valor\n'))
if num < 0:
print("Não existe raiz quadrada do valor nos reais")
else:
print(f"O valor da raiz é igual a {num**(1/2)}")
Exercício 3 - Leia um numero real. Se for >0 imprima a raiz, se nao eleve ao quadrado
numero = float(input("Digite um valor\n"))
if numero >= 0:
print(f"A raiz desse numero é {numero**(1/2)}")
else:
print(f"O valor desse número ao quadrado é {numero**2}")
# Exercício 4 - Faça um programa que leia um numero e caso seja positivo, mostre o numero ao quadrado e a raiz dele
num = float(input('Digite um valor\n'))
if num >= 0:
print(f"O valor desse valor ao quadrado é: {num**2} \n e a raiz dele é {num**(1/2)}")
# Exercício 5 - Faça um programa que receba um inteiro e diga se é par ou impar
num_inteiro = int(input('Digite um número inteiro \n'))
if num_inteiro % 2 == 0:
print("O número é par")
else:
print("O número é impar")
# Exercício 6 - Escreva um programa que, dado dois números inteiros
# mostre o maior, assim como a diferença entre ambos
num1 = float(input('Digite um numero\n'))
num2 = float(input('Digite outro numero\n'))
if num1 > num2:
print(f" O maior número é:{num1} \n A diferença entre eles é: {num1-num2}")
else:
print(f" O maior número é:{num2} \n A diferença entre eles é: {num2-num1}")
#Exercício 7 - Já fiz no exercício 1 kkkkk
# Exercício 8 - Ler 2 notas, verifica se as notas são válidas e
# exibir na tela a média. A nota deve ser entre 0 e 10, onde caso
# nao seja válida o fato deve ser informado e prog termina
nota1 = float(input('Digite a nota do seu 1º EE\n'))
nota2 = float(input('Digite a nota do seu 2º EE\n'))
if 10 < nota1 or nota1 < 0:
print("Você inseriu um valor incorreto")
elif 10 < nota2 or nota2 < 0:
print("Você inseriu um valor incorreto")
else:
print(f"A média das suas notas foi: {(nota1+nota2)/2}")
# Exercício 9 - Ler o salário e o valor da prestação de um emprestimo
# Se a prestação for maior que 20% do salário: emprestimo nao concedido
# Se nao, empréstimo
salario = float(input('Digite seu salário\n'))
parcela = float(input('Digite a parcela do emprestimo\n'))
if parcela > 0.2*salario:
print("Empréstimo não concedido")
else:
print("Empréstimo concedido")
# Exercício 10 - programa de calcular imc se for homem uma formula
# se for mule outra formula
altura = float(input('Digite sua altura em metros\n'))
sexo = input('Digite seu sexo\n')
if sexo == 'masculino':
print(f"Seu imc é: {((72.7*altura)-58)}")
elif sexo == 'feminino':
print(f"Seu imc é: {((62.1*altura)-44.7)}")
else:
print('Houve algum erro de digitação')
# Exercício 11 - Dizer a soma dos algarismos de um número***
# Exercício 12/13 é agua
# Exercício 14 - Ponderar notas e dizer se passou ou nao
import sys
trab_lab = float(input('Digite a sua nota do trab de lab\n'))
if 10 < trab_lab or trab_lab < 0:
print("Você inseriu a nota errada.")
sys.exit()
av_semestral = float(input('Digite a sua nota da av semestral\n'))
if 10 < av_semestral or av_semestral < 0:
print("Você inseriu a nota errada.")
sys.exit()
ex_final = float(input('Digite a sua nota do ex final\n'))
if 10 < ex_final or ex_final < 0:
print("Você inseriu a nota errada.")
sys.exit()
media = ((trab_lab*2 + av_semestral*3 + ex_final*5)/10)
if 0 < media < 2.999:
print(f"Você foi reprovado pois sua média foi: {media}")
elif 3 <= media < 4.999:
print(f"Você está de recuperaçao pois sua média foi: {media}")
else:
print(f"Você foi aprovado pois sua média foi: {media}")
# Questão 15,16 usando switch, ele não deu.
# Questão 17 agua
# Questão 18 - Calculadora
operacao = input("Digite qual operação você quer fazer entre "
"soma,diferença,divisão ou multiplicação\n")
num1 = float(input("Digite um número\n"))
num2 = float(input("Digite outro número\n"))
if operacao == 'soma':
print(f"O resultado da soma é: {num1+num2}")
elif operacao == 'diferença':
print(f"O resultado da diferença é: {num1-num2}")
elif operacao == 'divisão':
print(f"O resultado da divisão é: {num1/num2}")
elif operacao == 'multiplicação':
print(f"O resultado da multiplicação é: {num1*num2}")
else:
print("Operação inválida.")
# Questão 19 - Verificar se um inteiro é divisivel por 3 ou por 5
# mas nao pelos dois simultaneamente
num1 = int(input('Digite um número\n'))
div_por3 = num1 % 3
div_por5 = num1 % 5
if div_por3 == 0 and div_por5 == 0:
print('O valor é divísivel por 5 e 3 simultaneamente')
elif div_por3 == 0:
print('O número é divisível por 3')
elif div_por5 ==0:
print('O valor é divísivel por 5')
"""
# Só exemplo reptitivo que nao agrega muito | true |
6b251ff319e3375c6495cb11fd496395702e2398 | Python | JanelleTang/COMP90024_Assignment_2 | /backend/generate_instances.py | UTF-8 | 3,571 | 2.625 | 3 | [
"Apache-2.0"
] | permissive |
from numpy.lib.function_base import average
import requests
import pandas as pd
import django
from django.contrib.gis.geos import GEOSGeometry
import json
from django.core.exceptions import ObjectDoesNotExist
import django
import os
## ========================== Region Polygons ========================== #
class CouchToInstances:
def __init__(self,path,geo_dict):
self.URL = 'http://127.0.0.1:8000/api/location/'
self.region_data = requests.get(self.URL+path).json()['obj']
if path == 'city':
update_model_data(self.region_data,geo_dict,True)
else:
update_model_data(self.region_data,geo_dict,False)
# def dict_to_df(data):
# results = []
# for row in data:
# for k,v in row.items():
# results.append(v)
# df = pd.DataFrame(results)
# return df
def update_model_data(data,geom_dict,is_city=True):
for row in data:
for k,v in row.items():
try:
update_instance(v,geom_dict,is_city)
except:
print('Something wrong with uploading: ',v)
## create model instances here
def update_instance(data,geom_dict,is_city):
pk = data['name']
if is_city:
model=City
else:
model=LGA
try:
obj = model.objects.get(name=pk)
obj.sentiment_rank = get_sentiment_rank(data['total_sentiment'],data['total_tweets'])
obj.sentiment_value = round(data['total_sentiment'],4)
obj.n_tweets = data['total_tweets']
except ObjectDoesNotExist:
try:
geom = convert_to_geom(geom_dict[pk])
except KeyError:
print(pk+" does not exist in geojson")
return None
sent_rank = get_sentiment_rank(data['total_sentiment'],data['total_tweets'])
if is_city:
obj = model(name = pk,
state = data['state'],
polygon = geom,
sentiment_value = round(data['total_sentiment'],4),
sentiment_rank = sent_rank,
n_tweets = data['total_tweets'])
else:
obj = model(name = pk,
state = data['state'],
city = data['city'],
polygon = geom,
sentiment_value = round(data['total_sentiment'],4),
sentiment_rank = sent_rank,
n_tweets = data['total_tweets'])
obj.save()
def convert_to_geom(obj):
if type(obj) == str:
return GEOSGeometry(obj)
coordinates = obj['geometry']
return GEOSGeometry(json.dumps(coordinates))
def get_sentiment_rank(sentiment,count):
average_sent = sentiment/count
if average_sent <-0.66:
return -3
elif average_sent <-0.33:
return -2
elif average_sent <0:
return -1
elif average_sent == 0:
return 0
elif average_sent <=0.33:
return 1
elif average_sent <=0.66:
return 2
elif average_sent <=1:
return 3
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
django.setup()
from locations.models import LGA,City
with open('locations/data/shapefiles/combined_lga_data.json') as f:
lga_dict = json.load(f)
city_dict = {
'melbourne':'POINT(144.9631 -37.8136)',
'sydney':'POINT(151.2093 -33.8688)',
'brisbane city':'POINT(153.0260 -27.4705)',
'adelaide':'POINT(138.6007 -34.9285)',
'perth': 'POINT(115.8613 -31.9523)',
'hobart': 'POINT(147.3257 -42.8826)',
}
CouchToInstances("city",city_dict)
CouchToInstances("lga",lga_dict)
| true |
51a06d2e0a7bd5681274cf6e599078dba9f3458f | Python | Sravaniram/pythonprogramming | /strings contain atleast k vowel strings.py | UTF-8 | 254 | 2.984375 | 3 | [] | no_license | n,m=map(int,input().split())
a=[]
c=0
k=['a','e','i','o','u','A','E','I','O','U']
for x in range(0,n):
a.append(str(input()))
for y in a[x]:
if(y in k):
c=c+1
break
if(c>=m):
print("yes")
else:
print("no")
| true |
1d0c950054109ec7cd11db14e1ddb95242a14db0 | Python | NivedaVelumani/thresholding_opencv | /number_plate_otsu_thresholding/otsu_thres.py | UTF-8 | 543 | 2.75 | 3 | [] | no_license | import cv2
img=cv2.imread("number_plate.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
grayshow=cv2.imshow("GrayImage", gray)
cv2.waitKey(0)
cv2.imwrite("gray_image.png", gray)
gaussian_blur=cv2.GaussianBlur(gray,(7,7),20)
cv2.imshow("GAUSSIAN BLUR",gaussian_blur)
cv2.waitKey(0)
value,otsu_thres=cv2.threshold (gaussian_blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print("The Threshold value = {}".format(value))
cv2.imshow("OTSU THRESHOLD",otsu_thres)
cv2.waitKey(0)
cv2.imwrite("otsu_number_plate_with gaussian.jpg",otsu_thres)
| true |
911b06c8f9d3cfa03baa45556f1fc88b532d4ef2 | Python | gammasoft71/Examples_Python | /tkinter/Panel/Panel.py | UTF-8 | 675 | 2.875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# -*-coding:utf-8 -*
import tkinter
import tkinter.messagebox
import tkinter.ttk
class Form1(tkinter.Tk):
def __init__(self):
super().__init__()
self.panel = tkinter.ttk.Frame(self)
self.panel.pack(fill = tkinter.BOTH, expand=1)
self.panel1 = tkinter.LabelFrame(self.panel, height=460, width=305)
self.panel1.place(x=10, y=10)
self.panel2 = tkinter.LabelFrame(self.panel, borderwidth=1, height=460, width=305)
self.panel2.place(x=325, y=10)
self.geometry("640x480+200+100")
self.title("Panel example")
def main(self=None):
form = Form1()
form.mainloop()
if __name__ == '__main__':
Form1.main()
| true |
38316dc93a923ab81de299829bbd978ae8f08aae | Python | Damianpopisany/ucze_sie | /rzeczy.py | UTF-8 | 479 | 3.875 | 4 | [] | no_license |
class Dupa1(object):
def jeden(self):
selector = int(input("Wpisz 1 lub 2\n"))
print(selector)
print(type(selector))
if selector == 1:
print("wpisales 1")
else:
print("wpisales 2")
return selector
def dwa(self, numer):
print("To jest func dwa, w poprzedniej funkcji wpisales: {}".format(numer))
if __name__ == '__main__':
# print(Dupa1().jeden())
Dupa1().dwa(Dupa1().jeden())
| true |
bf38aeaefb70b2a602b090fcb28e72a5f75425f0 | Python | rajneeshshukla1608/GUI_python | /Label,Geometry,Max&Min.py | UTF-8 | 414 | 3.5 | 4 | [] | no_license | from tkinter import *
me_root = Tk()
# width x height -> argument
me_root.geometry("500x434")
# this concept is used because some times we want som minimum size and not to go below this theta is why we use it
# width , height -> argument
me_root.minsize(200, 100)
# width , height
me_root.maxsize(1200, 1000)
me = Label(text="I am a good boy god GUIr")
me.pack()
me_root.mainloop()
| true |
b01964ea88d90e37472424827c2a938ad240491e | Python | joelmacey/accelerated-data-pipelines | /CurationEngine/src/startCurationProcessing.py | UTF-8 | 4,976 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | import json
import os
import random
import re
import string
import time
import traceback
import urllib
from datetime import datetime
import boto3
class StartCurationProcessingException(Exception):
pass
def lambda_handler(event, context):
'''
lambda_handler Top level lambda handler ensuring all exceptions
are caught and logged.
:param event: AWS Lambda uses this to pass in event data.
:type event: Python type - Dict / list / int / string / float / None
:param context: AWS Lambda uses this to pass in runtime information.
:type context: LambdaContext
:return: The event object passed into the method
:rtype: Python type - Dict / list / int / string / float / None
:raises StartCurationProcessingException: On any error or exception
'''
try:
return start_curation_processing(event, context)
except StartCurationProcessingException:
raise
except Exception as e:
traceback.print_exc()
raise StartCurationProcessingException(e)
def start_curation_processing(event, context):
'''
start_curation_processing Passes the event and additional
details defined to start off the curation engine.
:param event: AWS Lambda uses this to pass in event data.
:type event: Python type - Dict / list / int / string / float / None
:param context: AWS Lambda uses this to pass in runtime information.
:type context: LambdaContext
:return: The event object passed into the method
:rtype: Python type - Dict / list / int / string / float / None
'''
start_step_function_for_event(event['curationType'])
return event
def start_step_function_for_event(curationType):
'''
start_step_function_for_file Starts the accelerated
data pipelines curation engine step function for this curationType.
:param curationType: The unique Id of the curation defined in the curaiton details dynamodb table
:type curationType: Python String
'''
try:
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
keystring = re.sub('\W+', '_', curationType) # Remove special chars
step_function_name = timestamp + id_generator() + '_' + keystring
sfn = boto3.client('stepfunctions')
state_machine_arn = os.environ['STEP_FUNCTION']
step_function_name = step_function_name[:80]
sfn_Input = {
'curationDetails': {
'curationType': curationType,
'curationExecutionName': step_function_name,
'curationTimestamp': timestamp
},
'settings': {
'curationDetailsTableName':
os.environ['CURATION_DETAILS_TABLE_NAME'],
'curationHistoryTableName':
os.environ['CURATION_HISTORY_TABLE_NAME'],
'scriptsRepo':
os.environ['SCRIPTS_REPO_NAME']
}
}
step_function_input = json.dumps(sfn_Input)
sfn.start_execution(
stateMachineArn=state_machine_arn,
name=step_function_name, input=step_function_input)
print(f'Started step function with input:{step_function_input}')
except Exception as e:
record_failure_to_start_step_function(
curationType, e)
raise
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
'''
id_generator Creates a random id to add to the step function
name - duplicate names will cause errors.
:param size: The required length of the id, defaults to 6
:param size: Python Integer, optional
:param chars: Chars used to generate id, defaults to uppercase alpha+digits
:param chars: Python String
:return: The generated id
:rtype: Python String
'''
return ''.join(random.choice(chars) for _ in range(size))
def record_failure_to_start_step_function(curationType, exception):
'''
record_failure_to_start_step_function Record failure to start the
curation engine step function in the curation history. Any exceptions
raised by this method are caught.
:param curationType: The curation Type that is being ran
:type curationType: Python String
:param exception: The exception raised by the failure
:type exception: Python Exception
'''
try:
dynamodb = boto3.resource('dynamodb')
curation_history_table = os.environ['CURATION_HISTORY_TABLE_NAME']
dynamodb_item = {
'curationType': curationType,
'timestamp': int(time.time() * 1000),
'error': "Failed to start processing",
'errorCause': {
'errorType': type(exception).__name__,
'errorMessage': str(exception)
}
}
dynamodb_table = dynamodb.Table(curation_history_table)
dynamodb_table.put_item(Item=dynamodb_item)
except Exception:
traceback.print_exc() | true |
7b1fe2c73139f0bb4ff7b9ceb798ab43e41d177f | Python | shantanudwvd/PythonHackerrank | /checksubset.py | UTF-8 | 533 | 3.28125 | 3 | [] | no_license | queries = int(input())
for i in range(0, queries):
count = 0
SetA = []
sizeofA = int(input())
SetA = list(map(int, input().split(" ")))
SetB = []
sizeofB = int(input())
SetB = list(map(int, input().split(" ")))
j = 0
while j < sizeofA:
k = 0
while k < sizeofB:
if SetA[j] == SetB[k]:
count += 1
break
k += 1
j += 1
if count == sizeofA:
print("True")
else:
print("False")
| true |
5cb3677eb5880be1f9859d224f47f9de987ef1e3 | Python | jakubhorvath/Kojima_et_al_2021_PNAS | /scripts/pseudogene_parental_gene_similarity/calc_p_val.py | UTF-8 | 513 | 2.671875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
"""
# usage: python %prog
# python3
scipy 1.1.0
"""
import os,sys,re,shutil
from statistics import mean,stdev
import scipy.stats as st
f_path='pseudogene_perc_ident.txt'
idents=[]
with open(f_path) as infile:
for line in infile:
ls=line.split()
idents.append(float(ls[1]))
pass
mean=mean(idents)
sd=stdev(idents)
value=float('76.92') # PVI
zscore= (value - mean) / sd
print(zscore)
pvalues=st.norm.sf(abs(zscore)) * 2 # two-sided
print(pvalues)
| true |
2d2e7d354b77bc8a70f985e56aca6ca31f096873 | Python | Jasolicon/Maha_Siamese_FSN | /metric.py | UTF-8 | 4,642 | 2.953125 | 3 | [] | no_license | """ Metric Learning related
"""
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.optim as optim
class MNet(nn.Module):
def __init__(self, dim):
super(MNet, self).__init__()
self.dimension = dim
self.w_matrix = nn.Parameter(torch.zeros(dim, dim)) # dimension of features
self.reset_parameters() # initialize parameters
def reset_parameters(self): # Identity matrix
nn.init.zeros_(self.w_matrix)
with torch.no_grad():
for i in range(self.dimension):
self.w_matrix[i][i] = 1
def forward(self, features1, features2):
diff = features1 - features2 # (x - y)
weighted_diff = diff.mm(self.w_matrix) # W^T(x - y)
out = torch.tanh(torch.norm(weighted_diff, 2, dim=1))
return out
def my_knn(distances, train_labels, query_labels, same_set, k, class_num):
""" My KNN Algorithm
:param distances: [q * t] train-query distances
:param train_labels: [t]
:param query_labels: [q]
:param same_set: True if training set and query set are the same.
:param k:
:param class_num:
:param log_path:
:param write_log:
:return:
"""
ct_t = train_labels.shape[0]
ct_q = query_labels.shape[0]
train_labels = train_labels.float()
query_labels = query_labels.float()
result = torch.zeros([ct_q])
with torch.no_grad():
# KNN
# if write_log:
# with open(logpath, mode='a', encoding='utf-8') as f:
# print('Distances:', file=f)
for i in range(ct_q):
distances_cur = {}
for j in range(ct_t):
distances_cur[j] = distances[i][j]
if same_set and (i == j):
distances_cur[j] = 10
# sort
distances_cur = sorted(distances_cur.items(), key=lambda x: x[1])
# count neighbors
neighbors = torch.zeros([class_num], dtype=torch.int)
for j in range(k):
neighbors[train_labels[distances_cur[j][0]].long().item()] += 1
# find the nearest neighbor
nearest_ct = 0
nearest = 0
for j in range(class_num):
if neighbors[j] > nearest_ct:
nearest_ct = neighbors[j]
nearest = j
result[i] = nearest
acc_record = torch.eq(result.long(), query_labels.long())
acc = float(acc_record.sum()) / ct_q
# if write_log:
# with open(logpath, mode='a', encoding='utf-8') as f:
# print('Prediction result:\n', result, '\n', file=f)
return acc
class MyCriterion(nn.Module):
def __init__(self, m=0.8, t=0.05):
"""
:param m: margin
:param t: threshold
"""
super(MyCriterion, self).__init__()
self.m = m
self.t = t
def forward(self, distances, labels1, labels2):
""" Loss = y * max(d, t) + (1 - y) * max(0, m - d)
y = 1 if same labels; y = 0 if different labels
:param distances: shape: [b]
:param labels1: shape: [b * 1]
:param labels2: shape: [b * 1]
:return: loss
"""
distances = distances.reshape(-1)
labels1 = labels1.reshape(-1)
labels2 = labels2.reshape(-1)
size = distances.shape[0]
y = torch.eq(labels1, labels2).long()
a = distances.clamp_min(self.t)
b = (-distances + self.m).clamp_min(0)
loss = y * a + (-y + 1) * b
loss = loss.sum() / size
return loss
if __name__ == '__main__':
dim = 5
batch_size = 4
m_net = MNet(dim)
m_net.train()
feature1 = torch.randn((batch_size, dim))
feature2 = torch.zeros((batch_size, dim))
label1 = torch.randint(0, 3, [batch_size])
label2 = torch.randint(0, 3, [batch_size])
optimizer = optim.Adam(m_net.parameters(), lr=0.0001)
# for p in m_net.parameters():
# if p.requires_grad:
# print(p.name, p.data)
out = m_net(feature1, feature2)
# out = torch.tensor([0.7, 0.03, 0.07, 0.9], dtype=torch.float)
criterion = MyCriterion()
loss = criterion(out, label1, label2)
loss.backward()
optimizer.step()
# for p in m_net.parameters():
# if p.requires_grad:
# print(p.name, p.data)
| true |
9a54b4e867dca924ce23c5f247ca96de270378a8 | Python | strands-project/strands_morse | /src/strand_morse/scene_generator.py | UTF-8 | 34,201 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python3
"""
Simple API for placing objects on tables according to directional spatial
relations.
"""
import pymorse
import sys
import random
import json
import math
import numpy
import errno
import getopt
from operator import itemgetter
import qsr
from contextlib import contextmanager
@contextmanager
def ignored(*exceptions):
try:
yield
except exceptions:
pass
# Constants
# Offset for placing an object above a table
Z_DIST = 0.005
# Offset for placing an object at the edge of the table
XY_DIST = 0.01
# Sigma allows for some variance for directional relations
DIRECTION_SIGMA = math.pi/16
# Scale the bounding box of the object in order to prevent the object to be
# spawned close to the table edge
OBJECT_SCALE = 1.00
# Number of samples used to place an object
# If more samples would be needed for one object the overall scene is discarded
MAX_NUM_OF_SAMPLES = 100
# Distance of the camera with respect to the center of the table
CAMERA_DISTANCE = 2.5
# epsilon for testing whether a number is close to zero
_EPS = numpy.finfo(float).eps * 4.0
def vector_norm(data, axis=None, out=None):
"""Return length, i.e. Euclidean norm, of ndarray along axis.
>>> v = numpy.random.random(3)
>>> n = vector_norm(v)
>>> numpy.allclose(n, numpy.linalg.norm(v))
True
>>> v = numpy.random.rand(6, 5, 3)
>>> n = vector_norm(v, axis=-1)
>>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=2)))
True
>>> n = vector_norm(v, axis=1)
>>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1)))
True
>>> v = numpy.random.rand(5, 4, 3)
>>> n = numpy.empty((5, 3))
>>> vector_norm(v, axis=1, out=n)
>>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1)))
True
>>> vector_norm([])
0.0
>>> vector_norm([1])
1.0
"""
data = numpy.array(data, dtype=numpy.float64, copy=True)
if out is None:
if data.ndim == 1:
return math.sqrt(numpy.dot(data, data))
data *= data
out = numpy.atleast_1d(numpy.sum(data, axis=axis))
numpy.sqrt(out, out)
return out
else:
data *= data
numpy.sum(data, axis=axis, out=out)
numpy.sqrt(out, out)
def quaternion_about_axis(angle, axis):
"""Return quaternion for rotation about axis.
>>> q = quaternion_about_axis(0.123, [1, 0, 0])
"""
q = numpy.array([0.0, axis[0], axis[1], axis[2]])
qlen = vector_norm(q)
if qlen > _EPS:
q *= math.sin(angle/2.0) / qlen
q[0] = math.cos(angle/2.0)
return q
class BBox():
""" Bounding box of an object with getter functions.
"""
def __init__(self, bbox):
# Calc x_min and x_max for obj1
x_sorted = sorted(bbox, key=itemgetter(0))
self.x_min = x_sorted[0][0]
self.x_max = x_sorted[7][0]
# Calc y_min and y_max for obj
y_sorted = sorted(bbox, key=itemgetter(1))
self.y_min = y_sorted[0][1]
self.y_max = y_sorted[7][1]
# Calc z_min and z_max for obj
z_sorted = sorted(bbox, key=itemgetter(2))
self.z_min = z_sorted[0][2]
self.z_max = z_sorted[7][2]
def get_x_min(self):
return self.x_min
def get_x_max(self):
return self.x_max
def get_y_min(self):
return self.y_min
def get_y_max(self):
return self.y_max
def get_z_min(self):
return self.z_min
def get_z_max(self):
return self.z_max
class AbstractNode():
""" An abstract node. Captures the common aspects of RootNode and ObjectNode
"""
def __init__(self, object):
self.name = object
self.local_bbox = BBox(self.get_local_bbox())
self.calc_anchors()
def get_local_bbox(self):
""" Get the bounding box from the object.
"""
return json.loads(morse.rpc('simulation','get_object_bbox',self.name))
def calc_anchors(self):
""" Calculate anchors on the supporting plane. Default is a 3x3 grid.
"""
x = (self.local_bbox.get_x_max() - self.local_bbox.get_x_min()) / 6
y = (self.local_bbox.get_y_max() - self.local_bbox.get_y_min()) / 6
self.x_sigma = (x) * (x)
self.y_sigma = (y) * (y)
self.north = [self.local_bbox.get_x_min() + 1*x, self.local_bbox.get_y_min() + 3*y]
self.north_east = [self.local_bbox.get_x_min() + 1*x, self.local_bbox.get_y_min() + 5*y]
self.east = [self.local_bbox.get_x_min() + 3*x, self.local_bbox.get_y_min() + 5*y]
self.south_east = [self.local_bbox.get_x_min() + 5*x, self.local_bbox.get_y_min() + 5*y]
self.south = [self.local_bbox.get_x_min() + 5*x, self.local_bbox.get_y_min() + 3*y]
self.south_west = [self.local_bbox.get_x_min() + 5*x, self.local_bbox.get_y_min() + 1*y]
self.west = [self.local_bbox.get_x_min() + 3*x, self.local_bbox.get_y_min() + 1*y]
self.north_west = [self.local_bbox.get_x_min() + 1*x, self.local_bbox.get_y_min() + 1*y]
self.center = [self.local_bbox.get_x_min() + 3*x, self.local_bbox.get_y_min() + 3*y]
def get_anchor(self, anchor):
if anchor == 'north':
return self.north
elif anchor == 'north_east':
return self.north_east
elif anchor == 'east':
return self.east
elif anchor == 'south_east':
return self.south_east
elif anchor == 'south':
return self.south
elif anchor == 'south_west':
return self.south_west
elif anchor == 'west':
return self.west
elif anchor == 'north_west':
return self.north_west
else: # anchor == 'center':
return self.center
class RootNode(AbstractNode):
""" A root node must be a supporting plane, e.g. an office desk. All
objects that are associated with the suppporting plane will be placed on
it.
"""
def __init__(self, object):
super(RootNode, self).__init__(object)
self.children = []
self.anchors = dict()
self.objects = list()
self.types = dict()
self.positions = dict()
self.orientations = dict()
self.global_bboxes = dict()
self.global_bboxes_json = dict()
def add(self,node, anchor):
""" Appends an object sub-tree to the current node
"""
self.children.append(node)
self.anchors[node] = anchor
def within_root_bbox(self,object,x,y):
min_xy_dim = \
min(object.local_bbox.get_x_max() - object.local_bbox.get_x_min(), \
object.local_bbox.get_y_max() - object.local_bbox.get_y_min()) \
* OBJECT_SCALE
if (self.local_bbox.get_x_min() + min_xy_dim < x and \
x < self.local_bbox.get_x_max() - min_xy_dim and \
self.local_bbox.get_y_min() + min_xy_dim < y and \
y < self.local_bbox.get_y_max()- min_xy_dim ):
return True
return False
def in_collision(self,bbox):
x_min = bbox.get_x_min()
x_max = bbox.get_x_max()
y_min = bbox.get_y_min()
y_max = bbox.get_y_max()
for obj in self.global_bboxes.keys():
bbox2 = self.global_bboxes[obj]
if (x_max >= bbox2.get_x_min() and
x_min <= bbox2.get_x_max() and
y_max >= bbox2.get_y_min() and
y_min <= bbox2.get_y_max()):
return True
return False
def place_objects(self, no):
""" Places objects in the scene according to their specified
relations.
"""
for c in self.children:
c.set_root(self)
[x_mu, y_mu] = self.get_anchor(self.anchors[c])
# sample as long as a valid position is found
i = 0
while i < MAX_NUM_OF_SAMPLES:
x = random.gauss(x_mu, self.x_sigma)
y = random.gauss(y_mu, self.y_sigma)
z = self.local_bbox.get_z_max() + \
(c.local_bbox.get_z_max() - c.local_bbox.get_z_min()) / 2 + Z_DIST
if self.within_root_bbox(c,x,y):
# calc pose
pos = morse.rpc('simulation','transform_to_obj_frame', self.name, str([x,y,z]))
orientation = list(quaternion_about_axis(c.get_yaw(), [0,0,1]))
# set pose
morse.rpc('simulation','set_object_pose',
c.name, str(pos), str(orientation))
# get global bounding box
json_bbox = json.loads(morse.rpc('simulation','get_object_global_bbox',c.name))
global_bbox = BBox(json_bbox)
# Second test: is object in collision with other objects?
if not self.in_collision(global_bbox):
# Hooray! Object could be placed
self.objects.append(c.name)
obj_type = json.loads(morse.rpc('simulation','get_object_type', c.name))
self.types[c.name] = obj_type
self.positions[c.name] = pos
self.orientations[c.name] = orientation
self.global_bboxes[c.name] = global_bbox
self.global_bboxes_json[c.name] = json_bbox
break
i = i + 1
if i >= MAX_NUM_OF_SAMPLES:
raise PlacementException(c.name)
# place children
c.place_children()
# Add root object (table) to data structures
obj_type = json.loads(morse.rpc('simulation','get_object_type', self.name))
self.types[self.name] = obj_type
root_pose = json.loads(morse.rpc('simulation','get_object_pose',
self.name))
self.positions[self.name] = root_pose[0]
self.orientations[self.name] = root_pose[1]
json_bbox = json.loads(morse.rpc('simulation','get_object_global_bbox',self.name))
self.global_bboxes_json[self.name] = json_bbox
# TODO: replace the anlges 0 by the actual angle of the table!
x_rel = math.sin(math.pi / 2) * CAMERA_DISTANCE
y_rel = math.cos(math.pi / 2) * CAMERA_DISTANCE
x = root_pose[0][0] + x_rel
y = root_pose[0][1] + y_rel
z = 1.698 # height of the xtion on the scitos robot
camera_position = [x, y, z]
scene = ['scene' + str(no), {'supporting_object' : self.name,
'camera_position' : camera_position,
'objects' : self.objects,
'type' : self.types,
'position' : self.positions,
'orientation' : self.orientations,
'bbox': self.global_bboxes_json}]
return scene
class ObjectNode(AbstractNode):
""" An object node is an element in an object tree; a hierarchical
specification of the relations between objects with repect to its root
element.
"""
def __init__(self, object):
super(ObjectNode, self).__init__(object)
self.root = None
self.children = []
self.directions = dict()
self.distances = dict()
self.init_directions()
self.set_yaw_range([0,2*math.pi])
def set_root(self, root):
self.root = root
def get_root(self):
return self.root
def add(self, node, direction, distance='any'):
""" Appends a node to the current node
"""
self.children.append(node)
self.directions[node] = direction
self.distances[node] = distance
def init_directions(self):
self.right = 0
self.right_front = math.pi / 4
self.front = math.pi / 2
self.left_front = 3 * math.pi / 4
self.left = math.pi;
self.left_back = 5 * math.pi / 4
self.back = 3 * math.pi / 2
self.right_back = 7 * math.pi / 4
def get_direction(self,direction):
if direction == 'center_back':
return self.back
elif direction == 'right_back':
return self.right_back
elif direction == 'right_center':
return self.right
elif direction == 'right_front':
return self.right_front
elif direction == 'left_front':
return self.left_front
elif direction == 'left_center':
return self.left
elif direction == 'left_back':
return self.left_back
else: #elif direction == 'center_front':
return self.front
def calc_distance_range(self, obj):
[x,y,z] = self.get_root().positions[self.name]
obj_bbox = self.get_root().global_bboxes[self.name]
root_bbox = BBox(json.loads(morse.rpc('simulation',
'get_object_global_bbox',
self.get_root().name)))
direction = self.directions[obj]
min_xy_dim = \
(min(obj.local_bbox.get_x_max() - obj.local_bbox.get_x_min(), \
obj.local_bbox.get_y_max() - obj.local_bbox.get_y_min()) \
* OBJECT_SCALE ) / 2
if direction == 'center_back':
min_dist = x - obj_bbox.get_x_min() + min_xy_dim
max_dist = x - root_bbox.get_x_min() - min_xy_dim
elif direction == 'right_back':
min_dist = math.sqrt(2* min(x - obj_bbox.get_x_min(),
obj_bbox.get_y_max() - y)**2) + min_xy_dim
max_dist = math.sqrt(2*min(x - root_bbox.get_x_min(),
root_bbox.get_y_max() - y)**2) - min_xy_dim
elif direction == 'right_center':
min_dist = obj_bbox.get_y_max() - y + min_xy_dim
max_dist = root_bbox.get_y_max() - y - min_xy_dim
elif direction == 'right_front':
min_dist = math.sqrt(2*min( obj_bbox.get_x_max() - x,
obj_bbox.get_y_max() - y)**2) + min_xy_dim
max_dist = math.sqrt(2*min(root_bbox.get_x_max() - x,
root_bbox.get_y_max() - y)**2) - min_xy_dim
elif direction == 'left_front':
min_dist = math.sqrt(2*min( obj_bbox.get_x_max() - x,
y - obj_bbox.get_y_min())**2) + min_xy_dim
max_dist = math.sqrt(2*min(root_bbox.get_x_max() - x,
y - root_bbox.get_y_min())**2) - min_xy_dim
elif direction == 'left_center':
min_dist = y - obj_bbox.get_y_min() + min_xy_dim
max_dist = y - root_bbox.get_y_min() - min_xy_dim
elif direction == 'left_back':
min_dist = math.sqrt(2* min(x - obj_bbox.get_x_min(),
y - obj_bbox.get_y_min() )**2) + min_xy_dim
max_dist = math.sqrt(2*min(x - root_bbox.get_x_min(),
y - root_bbox.get_y_min())**2) - min_xy_dim
else: #elif direction == 'center_front':
min_dist = obj_bbox.get_x_max() - x + min_xy_dim
max_dist = root_bbox.get_x_max() - x - min_xy_dim
if self.distances[obj] == 'close':
max_dist = (max_dist + min_dist) / 2
else:
min_dist = (max_dist + min_dist) / 2
return [min_dist,max_dist]
def set_yaw_range(self,yaw_range):
self.yaw_range = yaw_range
def set_yaw(self,yaw):
self.yaw = yaw
def get_yaw(self):
return random.uniform(self.yaw_range[0],self.yaw_range[1])
def place_children(self):
for c in self.children:
c.set_root(self.get_root())
[self_x,self_y,self_z] = self.get_root().positions[self.name]
phi_mu = self.get_direction(self.directions[c])
root_pose = json.loads(morse.rpc('simulation','get_object_pose',
self.get_root().name))
[root_x, root_y, root_z] = root_pose[0]
[min_dist, max_dist] = self.calc_distance_range(c)
i = 0
while i < MAX_NUM_OF_SAMPLES:
i = i + 1
phi = random.gauss(phi_mu, DIRECTION_SIGMA)
if phi < 0:
phi = phi + 2 * math.pi
if phi > (2 * math.pi):
phi = phi - (2 * math.pi)
dist = random.uniform(min_dist, max_dist)
x_rel = math.sin(phi) * dist
y_rel = math.cos(phi) * dist
x = self_x - root_x + x_rel
y = self_y - root_y + y_rel
z = self.get_root().local_bbox.get_z_max() + \
(c.local_bbox.get_z_max() - c.local_bbox.get_z_min()) / 2 + Z_DIST
# First sanity check: is object position on table?
if self.get_root().within_root_bbox(c,x,y):
pos = morse.rpc('simulation','transform_to_obj_frame',
self.get_root().name, str([x,y,z]))
orientation = list(quaternion_about_axis(c.get_yaw(), [0,0,1]))
# set pose
morse.rpc('simulation','set_object_pose', c.name,
str(pos),str(orientation))
json_bbox = json.loads(morse.rpc('simulation','get_object_global_bbox',c.name))
global_bbox = BBox(json_bbox)
# Second test: is object in collision with other objects?
if not self.get_root().in_collision(global_bbox):
# Hooray! Object could be placed
self.get_root().objects.append(c.name)
obj_type = json.loads(morse.rpc('simulation','get_object_type', c.name))
self.get_root().types[c.name] = obj_type
self.get_root().positions[c.name] = pos
self.get_root().orientations[c.name] = orientation
self.get_root().global_bboxes[c.name] = global_bbox
self.get_root().global_bboxes_json[c.name] = json_bbox
break
#else:
#print('not on table: ', c.name, min_dist, max_dist)
if i >= MAX_NUM_OF_SAMPLES:
raise PlacementException(c.name)
c.place_children()
def remove_objects(objs):
for o in objs:
morse.rpc('simulation','set_object_pose', o, str([0,0,0]),str([1,0,0,0]))
# Main
class PlacementException(Exception):
def __init__(self, msg):
self.msg = msg
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def help_msg():
return """
Usage: scene_generator.py [-h] <qsrmodel> <outfile> <num_of_scenes>
qsrmodel file including the QSR model for generationg the scenes
outfile name of the output file
num_of_scenes number of scenes to be generated
-h, --help for seeing this msg
"""
morse = None
def anchor_name(i):
anchor_name = ['north_west','north','north_east',
'west','center','east',
'south_west','south','south_east']
return anchor_name[i]
if __name__ == "__main__":
#sys.exit(main())
#def main(argv=None):
argv = None
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "h", ["help"])
except getopt.error as msg:
raise Usage(msg)
if ('-h','') in opts or ('--help', '') in opts or len(args) != 3:
raise Usage(help_msg())
#print('Parsing QSR model')
presence_total = dict()
presence_pop= dict()
anchor_pop = dict()
lrc_pop = dict()
fbc_pop = dict()
cd_pop = dict()
with open(args[0]) as qsr_file:
qsr_model = json.load(qsr_file)
print('PRESENCE')
for t in qsr_model['types']:
# total number of seen type instaces
presence_total[t] = sum(qsr_model['presence'][t][1:])
#print(t, presence_total[t])
# generate the population for each type
presence_pop[t] = list()
for i in range(len(qsr_model['presence'][t])):
for j in range(qsr_model['presence'][t][i]):
presence_pop[t].append(i)
print(t,presence_pop[t])
print('ANCHORS')
for t in qsr_model['landmarks']:
anchor_pop[t] = list()
for i in range(len(qsr_model['anchors'][t])):
for j in range(qsr_model['anchors'][t][i]):
anchor_pop[t].append(anchor_name(i))
print(t, anchor_pop[t])
print('QSR')
landmarks = list()
for t1 in qsr_model['landmarks']:
lrc_pop[t1] = dict()
fbc_pop[t1] = dict()
cd_pop[t1] = dict()
landmarks.append(t1)
for t2 in qsr_model['types']:
qsr_val = qsr_model['qsr'][t1][t2]
lr_center = max((qsr_val[4] + qsr_val [5]) - (qsr_val[0] + qsr_val[1]),0)
lrc_pop[t1][t2] = list()
lrc_pop[t1][t2] += ['left' for i in range(qsr_val[0])]
lrc_pop[t1][t2] += ['right' for i in range(qsr_val[1])]
lrc_pop[t1][t2] += ['center' for i in range(lr_center)]
fb_center = max((qsr_val[4] + qsr_val [5]) - (qsr_val[2] + qsr_val[3]),0)
fbc_pop[t1][t2] = list()
fbc_pop[t1][t2] += ['front' for i in range(qsr_val[2])]
fbc_pop[t1][t2] += ['back' for i in range(qsr_val[3])]
fbc_pop[t1][t2] += ['center' for i in range(fb_center)]
cd_pop[t1][t2] = list()
cd_pop[t1][t2] += ['close' for i in range(qsr_val[4])]
cd_pop[t1][t2] += ['distant' for i in range(qsr_val[5])]
print(t1,lrc_pop[t1])
print("----------------------------")
print(t1,fbc_pop[t1])
print("----------------------------")
print(t1,cd_pop[t1])
print("============================")
#print('Starting scene generation')
#sys.exit()
scenes = list()
num_of_scenes = int(args[2])
num_of_trials_per_scene = 20
if num_of_scenes < 0:
num_of_scenes = 0
i = 0
while i < num_of_scenes:
objs_of_type = dict()
for t in presence_pop:
objs_of_type[t] = random.sample(presence_pop[t],1)[0]
print(t,objs_of_type[t])
objs = dict()
for t in objs_of_type:
for j in range(objs_of_type[t]):
if j == 0:
objs[t.lower()] = t
else:
objs[t.lower() + ".00" + str(j)] = t
print(objs)
ii = 0
while ii < num_of_trials_per_scene:
with ignored(IOError):
with pymorse.Morse() as morse:
# Please note: all objects need to exist in the simulation beforehand!
# Create a root note
table = RootNode('table')
node = dict()
for o in objs:
# Create an object node
node[o] = ObjectNode(o)
# Background knowledge: some objects do only vary very little in orientation
if objs[o] in ['Monitor']:
node[o].set_yaw_range([0.0,math.pi/32])
elif objs[o] in ['Telephone','Mouse','Keyboard','PC','Laptop']:
node[o].set_yaw_range([0,math.pi/16])
else:
node[o].set_yaw_range([0,2*math.pi])
landmark_added = False
landmark = None
for o in objs:
if objs[o] == 'Monitor':
table.add(node[o],random.sample(anchor_pop[objs[o]],1)[0])
landmark_added = True
landmark = o
break
if not landmark_added:
for o in objs:
if objs[o] == 'Laptop':
table.add(node[o],random.sample(anchor_pop[objs[o]],1)[0])
landmark_added = True
landmark = o
break
try:
if not landmark_added:
ii = num_of_trials_per_scene
raise PlacementException('No landmark -> Discard scene')
print("Landmark:", landmark)
for o in objs:
if objs[o] in ['Monitor'] and o != landmark:
direction = "center_center"
while direction == "center_center":
lrc = random.sample(lrc_pop[objs[landmark]][objs[o]],1)[0]
fbc = random.sample(fbc_pop[objs[landmark]][objs[o]],1)[0]
direction = lrc + "_" + fbc
cd = random.sample(cd_pop[objs[landmark]][objs[o]],1)[0]
node[landmark].add(node[o],direction,cd)
print("QSR:",o,landmark,direction,cd)
for o in objs:
if objs[o] in ['PC'] and o != landmark:
direction = "center_center"
while direction == "center_center":
lrc = random.sample(lrc_pop[objs[landmark]][objs[o]],1)[0]
fbc = random.sample(fbc_pop[objs[landmark]][objs[o]],1)[0]
direction = lrc + "_" + fbc
cd = random.sample(cd_pop[objs[landmark]][objs[o]],1)[0]
node[landmark].add(node[o],direction,cd)
print("QSR:",o,landmark,direction,cd)
for o in objs:
if objs[o] in ['Laptop'] and o != landmark:
direction = "center_center"
while direction == "center_center":
lrc = random.sample(lrc_pop[objs[landmark]][objs[o]],1)[0]
fbc = random.sample(fbc_pop[objs[landmark]][objs[o]],1)[0]
direction = lrc + "_" + fbc
cd = random.sample(cd_pop[objs[landmark]][objs[o]],1)[0]
node[landmark].add(node[o],direction,cd)
print("QSR:",o,landmark,direction,cd)
for o in objs:
if objs[o] in ['Lamp'] and o != landmark:
direction = "center_center"
while direction == "center_center":
lrc = random.sample(lrc_pop[objs[landmark]][objs[o]],1)[0]
fbc = random.sample(fbc_pop[objs[landmark]][objs[o]],1)[0]
direction = lrc + "_" + fbc
cd = random.sample(cd_pop[objs[landmark]][objs[o]],1)[0]
node[landmark].add(node[o],direction,cd)
print("QSR:",o,landmark,direction,cd)
keyboard_added = False
keyboard_landmark = None
for o in objs:
if objs[o] in ['Keyboard']:
if objs[o] == 'Keyboard':
keyboard_landmark = o
keyboard_added = True
direction = "center_center"
while direction == "center_center":
lrc = random.sample(lrc_pop[objs[landmark]][objs[o]],1)[0]
fbc = random.sample(fbc_pop[objs[landmark]][objs[o]],1)[0]
direction = lrc + "_" + fbc
cd = random.sample(cd_pop[objs[landmark]][objs[o]],1)[0]
node[landmark].add(node[o],direction,cd)
print("QSR:",o,landmark,direction,cd)
break
for o in objs:
if objs[o] in ['Keyboard'] and o != keyboard_landmark and o != landmark:
l = landmark
if keyboard_added == True:
l = keyboard_landmark
direction = "center_center"
while direction == "center_center":
lrc = random.sample(lrc_pop[objs[l]][objs[o]],1)[0]
fbc = random.sample(fbc_pop[objs[l]][objs[o]],1)[0]
direction = lrc + "_" + fbc
cd = random.sample(cd_pop[objs[l]][objs[o]],1)[0]
node[l].add(node[o],direction,cd)
print("QSR:",o,l,direction,cd)
for o in objs:
if o != landmark and objs[o] not in ['Lamp','Laptop','Monitor','Keyboard','PC']:
l = landmark
if keyboard_added:
l = keyboard_landmark
direction = "center_center"
while direction == "center_center":
lrc = random.sample(lrc_pop[objs[l]][objs[o]],1)[0]
fbc = random.sample(fbc_pop[objs[l]][objs[o]],1)[0]
direction = lrc + "_" + fbc
cd = random.sample(cd_pop[objs[l]][objs[o]],1)[0]
node[l].add(node[o],direction,cd)
print("QSR:",o,l,direction,cd)
ii = ii + 1
scene = table.place_objects(i+1)
scenes.append(scene)
i = i + 1
ii = num_of_trials_per_scene
print("=========================================")
print(i," scene generated")
print("=========================================")
print("Press 'Enter' to continue")
input()
remove_objects(objs)
except PlacementException as e:
remove_objects(objs)
print('Warning:',e.msg,'could not be placed -> retry generation')
pass
except:
print("Unexpected error:", sys.exc_info()[0])
raise
# Generate QSR labelszzzzzz
for s in scenes:
scn = s[1]
cam_pos = scn['camera_position']
scn_qsr = dict()
for o1 in scn['objects']:
obj_qsr = dict()
for o2 in scn['objects']:
if o1 != o2:
pos1 = scn['position'][o1]
pos2 = scn['position'][o2]
#print(o1,o2)
obj_qsr[o2] = qsr.calc_QSR(cam_pos,pos1,pos2)
scn_qsr[o1] = obj_qsr
scn['qsr'] = scn_qsr
with open(args[1], "w") as outfile:
outfile.write(json.dumps(scenes, outfile, indent=2))
except Usage as err:
print(err.msg)
print("for help use --help")
#return 2
| true |
2abb96d76c28b5fc4c970ea24a82d10cbf12764e | Python | scrambleegg7/ATARI | /DQN/dqnMain00.py | UTF-8 | 6,005 | 2.84375 | 3 | [] | no_license | #import
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import gym
from MemoryClass import Memory
from tfQnetClass import QNetwork
from time import time
import matplotlib.pyplot as plt
# Network parameters
hidden_size = 64 # number of units in each Q-network hidden layer
learning_rate = 0.0001 # Q-network learning rate
# Memory parameters
memory_size = 10000 # memory capacity
batch_size = 20 # experience mini-batch size
pretrain_length = batch_size # number experiences to pretrain the memory
def process(render=False):
print("CartPole main start..")
env = gym.make('CartPole-v0')
# Initialize the simulation
env.reset()
# Take one random step to get the pole and cart moving
state, reward, done, _ = env.step(env.action_space.sample())
memory = Memory(max_size=memory_size)
# Make a bunch of random actions and store the experiences
for ii in range(pretrain_length):
# Uncomment the line below to watch the simulation
if render:
env.render()
# Make a random action
action = env.action_space.sample()
next_state, reward, done, _ = env.step(action)
if done:
# The simulation fails so no next state
next_state = np.zeros(state.shape)
# Add experience to memory
memory.add((state, action, reward, next_state))
# Start new episode
env.reset()
# Take one random step to get the pole and cart moving
state, reward, done, _ = env.step(env.action_space.sample())
else:
# Add experience to memory
memory.add((state, action, reward, next_state))
state = next_state
#memory.checkBuffer()
return memory, state, env
def training(render = False):
tf.reset_default_graph()
mainQN = QNetwork(name='main', hidden_size=hidden_size, learning_rate=learning_rate)
memory , state, env = process()
#print(state[:,np.newaxis].transpose().shape)
#return
#
train_episodes = 1000 # max number of episodes to learn from
max_steps = 200 # max steps in an episode
gamma = 0.99 # future reward discount
# Exploration parameters
explore_start = 1.0 # exploration probability at start
explore_stop = 0.01 # minimum exploration probability
decay_rate = 0.0001 # exponential decay rate for exploration prob
saver = tf.train.Saver()
rewards_list = []
with tf.Session() as sess:
# Initialize variables
sess.run(tf.global_variables_initializer())
step = 0
for ep in range(1, train_episodes):
total_reward = 0
t = 0
while t < max_steps:
step += 1
# Uncomment this next line to watch the training
if render:
env.render()
# Explore or Exploit
explore_p = explore_stop + (explore_start - explore_stop)*np.exp(-decay_rate*step)
if explore_p > np.random.rand():
# Make a random action
action = env.action_space.sample()
else:
# Get action from Q-network
#feed = {mainQN.inputs_: state.reshape((1, *state.shape))}
feed = {mainQN.inputs_: state.reshape((1, state.shape[0] ))}
Qs = sess.run(mainQN.output, feed_dict=feed)
action = np.argmax(Qs)
# Take action, get new state and reward
next_state, reward, done, _ = env.step(action)
total_reward += reward
if done:
# the episode ends so no next state
next_state = np.zeros(state.shape)
t = max_steps
print('Episode: {}'.format(ep),
'Total reward: {}'.format(total_reward),
'Training loss: {:.4f}'.format(loss),
'Explore P: {:.4f}'.format(explore_p))
rewards_list.append((ep, total_reward))
# Add experience to memory
memory.add((state, action, reward, next_state))
# Start new episode
env.reset()
# Take one random step to get the pole and cart moving
state, reward, done, _ = env.step(env.action_space.sample())
else:
# Add experience to memory
memory.add((state, action, reward, next_state))
state = next_state
t += 1
# Sample mini-batch from memory
batch = memory.sample(batch_size)
states = np.array([each[0] for each in batch])
actions = np.array([each[1] for each in batch])
rewards = np.array([each[2] for each in batch])
next_states = np.array([each[3] for each in batch])
# Train network
target_Qs = sess.run(mainQN.output, feed_dict={mainQN.inputs_: next_states})
# Set target_Qs to 0 for states where episode ends
episode_ends = (next_states == np.zeros(states[0].shape)).all(axis=1)
target_Qs[episode_ends] = (0, 0)
targets = rewards + gamma * np.max(target_Qs, axis=1)
loss, _ = sess.run([mainQN.loss, mainQN.opt],
feed_dict={mainQN.inputs_: states,
mainQN.targetQs_: targets,
mainQN.actions_: actions})
saver.save(sess, "checkpoints/cartpole.ckpt")
def main():
training()
if __name__ == "__main__":
main()
| true |
5743407895bcd9c2ee6e06b9e7f9af25fc420e83 | Python | ahmedatef1610/scikit-learn-library-for-machine-learning | /2.12 NB/5-MultinomialNB.py | UTF-8 | 4,301 | 3.46875 | 3 | [] | no_license | #Import Libraries
from sklearn.naive_bayes import MultinomialNB
from sklearn.datasets import make_classification
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix , classification_report
# ----------------------------------------------------
# Naive Bayes classifier for multinomial models (MultinomialNB)
'''
class sklearn.naive_bayes.MultinomialNB(alpha=1.0, fit_prior=True, class_prior=None)
===
- alpha float, default=1.0
Additive (Laplace/Lidstone) smoothing parameter (0 for no smoothing).
- fit_prior bool, default=True
Whether to learn class prior probabilities or not. If false, a uniform prior will be used.
- class_prior array-like of shape (n_classes,), default=None
Prior probabilities of the classes. If specified the priors are not adjusted according to the data.
===
'''
# ----------------------------------------------------
X, y = make_classification(n_samples=1000, n_features = 2, n_informative = 2, n_redundant = 0, n_repeated = 0,
n_classes = 2, n_clusters_per_class = 1, class_sep = 1.0, flip_y = 0.10, weights = [0.5,0.5],
shuffle = True, random_state = 17)
print(X.shape,y.shape)
print("0 : ", len(y[y==0]))
print("1 : ",len(y[y==1]))
print("="*10)
# ---------------
scaler = MinMaxScaler(copy=True, feature_range=(0, 1))
X = scaler.fit_transform(X)
# ---------------
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=44, shuffle=True)
print(X_train.shape,X_test.shape)
print(y_train.shape,y_test.shape)
print("="*25)
# ----------------------------------------------------
# Applying MultinomialNB Model
MultinomialNBModel = MultinomialNB(alpha=1.0, fit_prior=True, class_prior=None)
MultinomialNBModel.fit(X_train, y_train)
# ----------------------------------------------------
#Calculating Details
print('MultinomialNBModel Train Score is : ' , MultinomialNBModel.score(X_train, y_train))
print('MultinomialNBModel Test Score is : ' , MultinomialNBModel.score(X_test, y_test))
print("="*10)
# ---------------
print('number of training samples observed in each class is : ' , MultinomialNBModel.class_count_)
print('class labels known to the classifier is : ' , MultinomialNBModel.classes_)
print('Smoothed empirical log probability for each class is : ' , MultinomialNBModel.class_log_prior_)
print("="*5)
print('Number of features of each sample is : ' , MultinomialNBModel.n_features_)
print('Number of samples encountered for each (class, feature) during fitting is : ' , MultinomialNBModel.feature_count_)
print('Empirical log probability of features given a class, P(x_i|y). is : ' , MultinomialNBModel.feature_log_prob_)
# print("="*5)
# print('Mirrors feature_log_prob_ for interpreting MultinomialNB as a linear model is : ' , MultinomialNBModel.coef_)
# print('Mirrors class_log_prior_ for interpreting MultinomialNB as a linear model is : ' , MultinomialNBModel.intercept_)
print("="*25)
# ----------------------------------------------------
# Calculating Prediction
y_pred = MultinomialNBModel.predict(X_test)
y_pred_prob = MultinomialNBModel.predict_proba(X_test)
print('Prediction Probabilities Value for MultinomialNBModel is : \n', y_pred_prob[:5])
print('Pred Value for MultinomialNBModel is : ', y_pred[:5])
print('True Value for MultinomialNBModel is : ' , y_test[:5])
print("="*25)
# ----------------------------------------------------
ClassificationReport = classification_report(y_test, y_pred)
print(ClassificationReport)
print("="*10)
# ---------------
CM = confusion_matrix(y_test, y_pred)
print(CM)
print("="*10)
# ---------------
# plt.figure()
# sns.heatmap(CM, center = True, annot=True, fmt="d")
# plt.show(block=False)
# ---------------
print("="*25)
# ----------------------------------------------------
x_axis = np.arange(0-0.1, 1+0.1, 0.001)
xx0, xx1 = np.meshgrid(x_axis,x_axis)
Z = MultinomialNBModel.predict(np.c_[xx0.ravel(), xx1.ravel()]).reshape(xx0.shape)
plt.figure()
sns.scatterplot(x=X[:,0], y=X[:,1], hue=y, alpha=1);
plt.contourf(xx0, xx1, Z, alpha=0.2, cmap=plt.cm.Paired)
plt.show(block=False)
plt.show(block=True) | true |
8d990d7dba30f20d4103499698293d33df3a0b16 | Python | lnls-fac/tools | /scripts_elegant/visualize.py | UTF-8 | 1,811 | 2.75 | 3 | [] | no_license | #!/usr/bin/env python3
import subprocess as sub
def usage():
print('Prints the main results of the optimization and plot the twiss parameters:'
'\n\n Usage: visualize [rootName]')
def visualize(lattice_name):
if lattice_name in ('-h', '--help'):
usage()
return
sub.call(['plotTwiss','-fileRoot',lattice_name])
p = sub.getoutput('sdds2stream -par=ex0 ' + lattice_name + '.twi')
print('\nEmittance [pm.rad] = {0:8.4f}'.format(float(p) * 1e12))
p = sub.getoutput('sdds2stream -par=nux ' + lattice_name + '.twi')
print('Tunex = {0:8.4f}'.format(float(p)))
p = sub.getoutput('sdds2stream -par=nuy ' + lattice_name + '.twi')
print('Tuney = {0:8.4f}'.format(float(p)))
p = sub.getoutput('sdds2stream -par=betaxMax ' + lattice_name + '.twi')
print('Maximo Betax = {0:8.4f}'.format(float(p)))
p = sub.getoutput('sdds2stream -par=betayMax ' + lattice_name + '.twi')
print('Maximo Betay = {0:8.4f}'.format(float(p)))
p = sub.getoutput('sdds2stream -col=ElementName,betax,betay,etax ' + lattice_name + '.twi')
indmi = p.index('MIB')
indend = p.index('\n',indmi)
miLine = p[indmi:indend].split()
print('Betax @ MIB = {0:8.4f}'.format(float(miLine[1])))
print('Betay @ MIB = {0:8.4f}'.format(float(miLine[2])))
print('Etax @ MIB = {0:8.4f}'.format(float(miLine[3])))
indmi = p.index('MIA')
indend = p.index('\n',indmi)
miLine = p[indmi:indend].split()
print('Betax @ MIA = {0:8.4f}'.format(float(miLine[1])))
print('Betay @ MIA = {0:8.4f}'.format(float(miLine[2])))
print('Etax @ MIA = {0:8.4f}'.format(float(miLine[3])))
try:
visualize(lattice_name=sub.sys.argv[1])
except IndexError:
usage()
| true |
5ae255529d3ba8fd7cadb9cee1b8f1fe51a20fe3 | Python | DiptoChakrabarty/Python | /Recursion/recursivedigitsumpro.py | UTF-8 | 333 | 3.03125 | 3 | [
"MIT"
] | permissive | def superDigit(n, k):
l=list(n)
s=0
for i in l:
s=s+int(i)
t=s*k
if((t//10)>0):
p=sum0(t)
return sum0(p)
def sum0(t):
k=0
if(t//10==0):
return t
else:
return (t%10+sum0(t//10))
w=int(input())
a=int(input())
k=superDigit(w,a)
print(k)
| true |
133ce2bea96bdd06a595e2afad54091ff1652008 | Python | beCharlatan/gu_ai | /pyalgs/lesson1/task08.py | UTF-8 | 583 | 4.53125 | 5 | [] | no_license | # 8. Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого).
a = int(input('Введите первое число: '))
b = int(input('Введите второе число: '))
c = int(input('Введите третье число: '))
if a == b or b == c or a == c:
print('Нет среднего числа')
else:
if (a > b and a < c) or (a < b and a > c):
print(a)
elif (b > a and b < c) or (b < a and b > c):
print(b)
else:
print(c) | true |
640b65b9baeedf09d636f26ae0607f7066eac140 | Python | Pavlo-Olshansky/Python_learns_3-Data-Analysis | /1_2_Intro_Basics/1_2_main.py | UTF-8 | 1,231 | 2.96875 | 3 | [] | no_license | import pandas as pd
import datetime
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
# style.use('ggplot')
# import pandas.io.data as wed
#
# start = datetime.datetime(2010, 1, 1)
# end = datetime.datetime(2015, 1, 1)
#
# df = wed.DataReader('XOM', 'yahoo', start, end)
# print(df.head()) # TOP 5
# df['Adj Close'].plot()
# plt.show()
web_stats = {'Day': [1, 2, 3, 4, 5, 6],
'Visitors': [43, 53, 34, 53, 43, 34],
'Bounce_Rate': [65, 43, 43, 23, 54, 65]}
stats = pd.DataFrame(web_stats)
# print(stats)
# print(stats.head(2)) # First 2
# print(stats.tail(2)) # Last_ 2
# print(stats.set_index('Day'))
stats.set_index('Day', inplace=True)
print(stats)
print(stats['Visitors'])
print(stats.Visitors)
print(stats[['Bounce_Rate', 'Visitors']])
print('tolist : ------', stats.Visitors.tolist())
print(stats['Visitors'].tolist())
print('array : ------', np.array(stats[['Bounce_Rate', 'Visitors']]))
stats_2 = pd.DataFrame(np.array(stats[['Bounce_Rate', 'Visitors']]))
print('Stats_2: ', stats_2)
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
x = int(input("Please enter a number: "))
| true |
6b7164647f8158c7f920bd1b9b3edf6d0be1a3e9 | Python | awrenn/StochasticKnapsack | /greedy_algorithm.py | UTF-8 | 1,394 | 3.5 | 4 | [] | no_license | import random
class item:
def __init__(self,min_v,max_v,min_w,max_w):
self.max_v = max(max_v,min_v)
self.min_v = min(max_v,min_v)
self.max_w = max(max_w,min_w)
self.min_w = min(max_w,min_w)
self.exp_v = (max_v + min_v)/2.0
self.exp_w = (max_w + min_w)/2.0
def expected_return(self,remaining):
range_w = self.max_w - self.min_w + 1
allowed_w = remaining - self.min_w + 1
possible_percent = float(allowed_w)/float(range_w)
if possible_percent < 0:
return 0
else:
return min(self.exp_v * possible_percent, self.exp_v)
def make_items(n,min_v,max_v,min_w,max_w):
items = []
for i in range(n):
v = random.randint(min_v,max_v)
V = random.randint(min_v,max_v)
w = random.randint(min_w,max_w)
W = random.randint(min_w,max_w)
items += [item(v,V,w,W)]
return items
def stoch_knapsack(items,weight):
if not items:
return 0
items = sorted(items, key= lambda item: item.expected_return(weight)/item.exp_w)
selected = items.pop(0)
value = selected.exp_v
used_cost = random.randint(selected.min_w,selected.max_w)
if used_cost > weight:
return 0
else:
return (value + stoch_knapsack(items,weight-used_cost))
items = make_items(100,1,1000,1,1000)
print(stoch_knapsack(items,10000))
| true |
f2693b008809c58e4c4ceae3395659c3c2d03f22 | Python | kartikeya649/Tecko-Data-Base | /frontend.py | UTF-8 | 2,927 | 3 | 3 | [
"MIT"
] | permissive | from tkinter import *
import backend
def get_selected_row(event):
global selected_row
index = list.curselection()[0]
selected_row = list.get(index) #Creating Labels for seeing new files
e1.delete(0,END)
e1.insert(END,selected_row[1])
e2.delete(0,END)
e2.insert(END,selected_row[2])
e3.delete(0,END)
e3.insert(END,selected_row[3])
e4.delete(0,END)
e4.insert(END,selected_row[4])
e5.delete(0,END)
e5.insert(END,selected_row[5])
e6.delete(0,END)
e6.insert(END,selected_row[6])
def delete_command():
backend.delete(selected_row[0])
def view_command():
list.delete(0,END)
for row in backend.view():
list.insert(END,row)
def search_command():
list.delete(0,END)
for row in backend.search(date_text.get(),earning_text.get(),exercise_text.get(),study_text.get(),diet_text.get(),python_text.get()):
list.insert(END,row)
def add_command():
backend.insert(date_text.get(),earning_text.get(),exercise_text.get(),study_text.get(),diet_text.get(),python_text.get())
list.delete(0,END)
list.insert(END,(date_text.get(),earning_text.get(),exercise_text.get(),study_text.get(),diet_text.get(),python_text.get()))
win = Tk()
win.wm_title('TECKO DATABASE')
l1 = Label(win, text='Date')
l1.grid(row=0,column=0)
l2 = Label(win, text='Earnings')
l2.grid(row=0,column=2)
l3 = Label(win, text='Exercise')
l3.grid(row=1,column=0)
l4 = Label(win, text='Study')
l4.grid(row=1,column=2)
l5 = Label(win, text='Diet')
l5.grid(row=2,column=0)
l6 = Label(win, text='Python')
l6.grid(row=2,column=2)
#Creating Entries
date_text = StringVar()
e1 = Entry(win, textvariable=date_text)
e1.grid(row=0,column=1)
earning_text = StringVar()
e2 = Entry(win, textvariable=earning_text)
e2.grid(row=0,column=3)
exercise_text = StringVar()
e3 = Entry(win, textvariable=exercise_text)
e3.grid(row=1,column=1)
study_text = StringVar()
e4 = Entry(win, textvariable=study_text)
e4.grid(row=1,column=3)
diet_text = StringVar()
e5 = Entry(win, textvariable=diet_text)
e5.grid(row=2,column=1)
python_text = StringVar()
e6 = Entry(win, textvariable=python_text)
e6.grid(row=2,column=3)
#Creating ListBox
list = Listbox(win,height=8,width=35)
list.grid(row=3,column=0,rowspan=9,columnspan=2)
#Creating ScrollBar
sb = Scrollbar(win)
sb.grid(row=3,column=2,rowspan=9)
#Binding the List Function
list.bind('<<ListboxSelect>>',get_selected_row)
#Creating Buttons
b1 = Button(win,text='ADD',width=12,pady=5,command=add_command)
b1.grid(row=3,column=3)
b2 = Button(win,text='Search',width=12,pady=5,command=search_command)
b2.grid(row=4,column=3)
b3 = Button(win,text='Delete date',width=12,pady=5,command=delete_command)
b3.grid(row=5,column=3)
b4 = Button(win,text='View all',width=12,pady=5,command=view_command)
b4.grid(row=6,column=3)
b5 = Button(win,text='Close',width=12,pady=5,command = win.destroy)
b5.grid(row=7,column=3)
win.mainloop()
| true |
1d94be507c92f07fdf703c8095e655ad214732ad | Python | TrebledJ/aoc | /2018/d3/d3p1.py | UTF-8 | 493 | 2.96875 | 3 | [] | no_license | ## 120 ms
import time as tm
import numpy as np
with open('input.txt') as f:
data = f.read().splitlines()
start = tm.time()
mx=my=mw=mh=0
sz = 1050
grid = np.matrix(
[[0] * sz] * sz
)
for line in data:
id_, _, coor, dim = line[1:].split()
x, y = coor[:-1].split(',')
w, h = dim.split('x')
x, y, w, h = map(int, [x, y, w, h])
grid[x:x+w, y:y+h] += 1
end = tm.time()
print(len(np.where(grid > 1)[0]))
print('Time Taken:', (end - start) * 1000, 'ms')
| true |
267cb2b64d24a48de55c7c12aecb77cda2c87698 | Python | roba-di-gp/fractals | /julia_in_mandelbrot.py | UTF-8 | 2,478 | 3.0625 | 3 | [] | no_license | import numpy as np
from numba import jit
import matplotlib.pyplot as plt
from time import time
start = time()
nx = 1800 #main figure x resolution
ny = 1200 #main figure y resolution
jx = 1800 #Julia rendering x res
jy = 1800 #Julia rendering y res
#number of iterations of the Mandelbrot set calculation
iters = 100
#number of iterations of the Julia sets calculation
iters_j = 100
colormap = 'hot_r' #chosen colormap
#x and y limits of the main figure
ext = [-2,1,-1.15,1.15]
#x and y limits of the Julia rendering
ext_j = [-2,2,-2,2]
@jit
def iterative(n,z,c):
for i in range(n):
if abs(z) < 2:
z = z*z + c
else: break
return i;
def mandelbrot(x,y,nx,ny):
z = complex(0,0)
escape = np.zeros([nx,ny])
for nx_index, re in enumerate(x):
for ny_index, im in enumerate(y):
c = complex(re,im)
escape[nx_index,ny_index] = iterative(iters,z,c)
if nx_index % 100 == 0:
print('%.2f'%(nx_index/nx))
return escape;
def julia(xx,yy,jx,jy,c):
getaway = np.zeros([jx,jy])
for jx_index, re in enumerate(xx):
for jy_index, im in enumerate(yy):
z = complex(re,im)
getaway[jx_index,jy_index] = iterative(iters,z,c)
if jx_index % 100 == 0:
print('%.2f'%(jx_index/jx))
return getaway;
def render_julia(c):
start = time()
fig1 = plt.figure(1)
plt.clf()
xx = np.linspace(ext_j[0],ext_j[1],jx)
yy = np.linspace(ext_j[2],ext_j[3],jy)
getaway = julia(xx,yy,jx,jy,c)
plt.imshow(getaway.T,cmap=colormap,extent=ext_j,origin='lower')
plt.title(r'$%.2f$ $%.2f$i'%(c.real,c.imag), fontsize = 'medium')
#plt.imsave(fname=r'###path###',arr=getaway.T,cmap=colormap,,extent=ext_j,origin='lower')
print('\n')
print(time() - start)
print('\n')
plt.show()
def onclick(event):
cx = event.xdata
cy = event.ydata
c = complex(cx,cy)
render_julia(c)
x = np.linspace(ext[0],ext[1],nx)
y = np.linspace(ext[2],ext[3],ny)
escape = mandelbrot(x,y,nx,ny)
fig0 = plt.figure(0)
plt.imshow(escape.T,cmap=colormap,extent=ext,origin='lower')
#plt.imsave(fname=r'###path###',arr=escape.T,cmap=colormap,extent=ext,origin='lower')
print('\n')
print(time() - start)
print('\n')
cid0 = fig0.canvas.mpl_connect('button_press_event', onclick)
plt.show()
| true |
a12e9a6bed28be7317e3fe2c26056e86c567a440 | Python | narraccino/AggregationStrategies | /Loft/NewFAaireness.py | UTF-8 | 4,923 | 3.3125 | 3 | [] | no_license | import pandas as pd
import numpy as np
import itertools
class Engine(object):
def __init__(self,num):
self.index=0
def valueReturn(self,lista):
letter= lista[self.index]
self.index= self.index+1
return letter
final_list = list()
ratingsArraylist=list()
ratingsArraylist.append([10,4,3,6,10,9,6,8,10,8])
ratingsArraylist.append([1,9,8,9,7,9,6,9,3,8])
ratingsArraylist.append([10,5,2,7,9,8,5,6,7,6])
ratingsArrayPOI = np.array(ratingsArraylist)
list_POI=list(['A','B','C','D','E','F','G','H','I','J'])
list_Names=list(["Giseppe", "Nava", "Shabnam"])
obj=[]
for i in range(len(list_Names)):
obj.append(Engine(i))
#creo un dataframe a partire dai ratings degli utenti
unsorted_df=pd.DataFrame(ratingsArrayPOI,columns=list_POI)
#aggiungo al dataframe la riga "Total"
somma= unsorted_df.sum()
unsorted_df.loc['Total'] = unsorted_df.sum()
for i in range(0,len(list_Names)):
#ordino le colonne a partire dalla riga 0 mediante ratings. Otterrò la riga i-esima ordinata
row= unsorted_df.sort_values(by=i, ascending=False, axis=1)
#allego alla riga i-esima ordinata la riga somma.
row=row.append(somma, ignore_index=True)
# creo due liste vuote
final_list1= list()
flattened_list=list()
for n in range(10,-1,-1):
#All'interno del dataframe row(compreso di somma), alla riga i-esima ,
#trova tutte le occorrenze nel numero n.
#se viene trovato il numero n allora verrà estratta la riga che conterrà solo quelle occorrenze n
#e per il resto NaN
vari= row.loc[i, :].where(row.loc[i, :]==n)
#converte la riga "vari" trasformando i numeri trovati in TRUE e i NaN in FALSE
bi= vari.notnull()
#nella riga contenente TRUE e FALSE, estrare i nomi delle colonne e le trasforma in una lista
columns= bi.index[bi[0:]== True].tolist()
#se la lista columns non è vuota
if columns != []:
#Creo il dataframe df1 che conterrà SOLO le colonne determinate da columns
df1 = pd.DataFrame(row, columns=columns)
#Ordino le colonne in base ai valori discendenti di somma che si trovano sull'ultima riga, ovvero 3
df1= df1.sort_values(by=len(list_Names), ascending=False, axis=1)
#prendo le colonne ordinate e le converto in lista
columns= df1.columns.tolist()
#aggiungo la lista columns alla lista final
final_list1.append(columns)
#faccio in modo che tutti gli elementi siano separati e perciò resi iterabili
final_list1= list(itertools.chain.from_iterable(final_list1))
#aggiungo per ogni iterazione(0-users_number le proprie liste finali ordinate)
final_list.append(final_list1)
print(final_list)
print("\n")
#creo la lista vuota ultimate che sarà quella definitiva
ultimate= list()
#indico il numero di spostamenti max che si devono verificare nel momento
#in cui nel vettore vi sono già lettere scelte in precedenza
repetition=2
#cicla fin quando la lunghezza di ultimate non raggiunge la lunghezza dei POI
while len(ultimate) != len(list_POI):
for i in range(0, len(list_Names)):
#estraggo la i-esima lista ordinata
lista= final_list[i]
#valueReturn mi tirerà fuori la lettera in base alla lista passata
letter= obj[i].valueReturn(lista)
#se la lettera non è in ultimate allora verrà aggiunta ad ultimate
if(letter not in ultimate):
ultimate.append(letter)
#se i=MAX degli utenti, in questo caso 3 (cioè indice 2) è il max
if(i==len(list_Names)-1):
#arrivato alla fine comincio a fare il conto, perché
#essendo l'ultimo a scegliere, l'algoritmo riparte dall'ultimo utente
#e itera sulla lista di "confine" da 0 fino al numero max di ripetizioni
for k in range(0, repetition-1):
letter= obj[i].valueReturn(lista)
if (letter not in ultimate):
ultimate.append(letter)
#comincio a tornare indietro fino al "confine" inizio
for j in range(len(list_Names) - (len(list_Names)-1), -1, -1):
lista = final_list[j]
letter = obj[j].valueReturn(lista)
if (letter not in ultimate):
ultimate.append(letter)
# arrivato di nuovo al punto di partenza comincio a fare il conto, perché
# essendo l'ultimo a scegliere, l'algoritmo riparte di nuovo dal primo utente
# e itera sulla lista di "confine" da 0 fino al numero max di ripetizioni
if (j == 0):
for k in range(0, repetition - (len(list_Names)-1)):
letter = obj[j].valueReturn(lista)
if (letter not in ultimate):
ultimate.append(letter)
print(ultimate)
| true |
15604d395349e59089905031fc2450d680d6ec33 | Python | lcaron4910/Python | /boucle numerique/multiplication d un nombre.py | UTF-8 | 127 | 3.34375 | 3 | [] | no_license | print("entrer votre nbr ?")
nb=int(input())
somme=1
for i in range (1,nb+1,1):
somme=somme*i
print(somme)
print(somme)
| true |
815bb406de4c327bf05eeb0019f5cca54cc749df | Python | sidshrivastav/Profanity-Checker | /main.py | UTF-8 | 855 | 3.34375 | 3 | [] | no_license | import urllib
### Funtion to read the file
def read_text():
quotes = open('sample.txt')
contents = quotes.read()
### Print orignal content
print(contents)
quotes.close()
check_profanity(contents)
### Function to check profanity
def check_profanity(check):
### Access Purgomalum Api for profanity words
connection = urllib.urlopen("http://www.purgomalum.com/service/containsprofanity?text=" + check)
output = connection.read()
connection.close()
if "true" in output:
print("Profanity Alert!! Check Your Document!")
doted = urllib.urlopen("http://www.purgomalum.com/service/plain?text=" + check)
doted_output = doted.read()
### Print dotted content
print(doted_output)
doted.close()
if "false" in output:
print("Success!! No Profanity!!")
read_text()
| true |
d81392e5431f8db292da4368dccbb0c50a21cc4e | Python | paulocesarcsdev/HappyNumbers | /HappyNumbers.py | UTF-8 | 373 | 3.5625 | 4 | [] | no_license | def sum_of_squares(number):
return sum(int(char) ** 2 for char in str(number))
def happy(number):
next_ = sum(int(char) ** 2 for char in str(number))
return number in (1, 7) if number < 10 else happy(next_)
assert sum_of_squares(130) == 10
assert all([happy(n)for n in (1, 10, 100, 130, 97)])
assert not all(happy(n) for n in (2, 3, 4, 5, 6, 8, 9)) | true |
c8a47c6f8eb82248c4028986eec0db9474645a35 | Python | mtk57/PublicMemo | /Python/mock_test/test/test_child.py | UTF-8 | 4,074 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python3
import pytest
# from unittest import mock
from ..src import base, child
def test_1():
# pytest.set_trace() # pdb kick
# Childのクラスのインスタンス生成
ins_c = child.Child()
# Baseクラスのインスタンスメソッドを呼び出す
assert ins_c.base_func() == base.Base.BASE_MEM
# Baseクラスのクラスメソッドを呼び出す
assert base.Base.base_class_func() == base.Base.BASE_DEF
# Childクラスのインスタンスメソッドを呼び出す
assert ins_c.child_func() == child.Child.CHILD_MEM + '&' + child.Child.DEF_PRM1
# Childクラスのクラスメソッドを呼び出す
assert child.Child.child_class_func() == child.Child.CHILD_DEF
# Childクラスのクラスメソッドを呼び出す2
assert child.Child.child_class_func(prm1=False) is None
# chileモジュールのモジュールメソッドを呼び出す
assert child.Child_module_func() == 1230
def test_2_child_init_mock(monkeypatch):
"""
Childクラスの__init__をモックする
"""
class Child():
""" Childクラスのモック """
def __init__(*args, **kwargs):
raise RuntimeError('init failed!')
def mock_child(*args, **kwargs):
""" Childクラスのインスタンスを生成 """
return Child()
# Childクラスのインスタンス生成をモック
monkeypatch.setattr(child, 'Child', mock_child)
with pytest.raises(RuntimeError):
# Childクラスのインスタンス生成
child.Child()
def test_3_child_instance_method_mock(monkeypatch):
"""
Childクラスのインスタンスメソッドをモックする
"""
# Childのクラスのインスタンス生成
ins_c = child.Child()
def mock_child_func(*args, **kwargs):
""" Childクラスのchild_funcメソッドのモック """
return 'mock return'
# child_funcメソッドのモックを設定
monkeypatch.setattr(ins_c, 'child_func', mock_child_func)
# pytest.set_trace() # pdb kick
# child_funcメソッドを呼び出す
assert ins_c.child_func() == 'mock return'
def test_4_child_class_method_mock(monkeypatch):
"""
Childクラスのクラスメソッドをモックする
"""
def mock_child_class_func(*args, **kwargs):
""" Childクラスのchild_class_funcメソッドのモック """
return 'mock return'
# child_class_funcメソッドのモックを設定
monkeypatch.setattr(child.Child, 'child_class_func', mock_child_class_func)
# pytest.set_trace() # pdb kick
# child_class_funcメソッドを呼び出す
assert child.Child.child_class_func() == 'mock return'
def test_5_child_instance_member_mock(monkeypatch):
"""
Childクラスのインスタンスメンバーをモックする
"""
# Childのクラスのインスタンス生成
ins_c = child.Child()
# _child_memインスタンスメンバの値を設定
monkeypatch.setitem(ins_c.__dict__, '_child_mem', 'mock value')
# pytest.set_trace() # pdb kick
assert ins_c._child_mem == 'mock value'
def test_6_child_class_member_mock(monkeypatch):
"""
Childクラスのクラスメンバーをモックする (無理かも...)
"""
pass
# CHILD_DEFインスタンスメンバの値を設定
# monkeypatch.setitem(child.Child.__dict__, 'CHILD_DEF', 'mock value')
# assert child.Child.CHILD_DEF == 'mock value'
def test_1000_module_method_mock(monkeypatch):
"""
モジュールメソッドをモックする
"""
def mock_Child_module_func(*args, **kwargs):
""" Child_module_funcメソッドのモック """
return 'mock return'
# Child_module_funcメソッドのモックを設定
monkeypatch.setattr(child, 'Child_module_func', mock_Child_module_func)
assert child.Child_module_func() == 'mock return'
def test_1001_module_varialble_mock():
"""
モジュール変数をモックする
"""
pass
| true |
0ed339fc6ec49ea1827fd5c2dc2f9bfe8dece5cc | Python | pto8913/KyoPro | /ABC/ABC109/A.py | UTF-8 | 141 | 2.828125 | 3 | [] | no_license | # URL: https://atcoder.jp/contests/abc109/tasks/abc109_a
A, B = map(int,input().split())
if(A*B%2 == 1):
print("Yes")
else:
print("No")
| true |
cf59295f69ed6ef58b3bdc3e5d4f889bc4a6c586 | Python | tanakn/aws-study-flask | /app.py | UTF-8 | 389 | 3 | 3 | [] | no_license | # import の実行
from flask import Flask,jsonify,request
# インスタンスの作成
app = Flask(__name__)
items =[{'name':'isu','price':None}]
# URL, Methodと関数の紐づけ
@app.route('/item',methods=['POST'])
def make_something():
item = request.get_json()
items.append(item)
return jsonify(items)
# サーバの起動
app.run(host='0.0.0.0', port=80, debug=True) | true |
8958b77e61a80f2ce3f35da0d93b6142d19afe80 | Python | divyanshagrwll-zz/GLAU-Python-Hackerrank-Contest | /03.1.py | UTF-8 | 163 | 3.09375 | 3 | [] | no_license | a=list(input().split(" "))
c=0
m=0
for i in a:
for k in range(1+c,len(a)):
t=int(i)&int(a[k])
if t>m :
m=t
c=c+1
print(m) | true |
3751d93574ac9158e040b2f19098e59459aa10d6 | Python | calciumhs/calciumAAA | /yufang/pythonnn/exam2.py | UTF-8 | 251 | 3.140625 | 3 | [] | no_license | A=[]
while True:
a=input()
if a=='-1':
break
else:
try:
a=eval(a)
A.append(a)
except:
continue
x=sum(A)
z=len(A)
y=x/z
print('%.2f'%x)
print('%.2f'%y)
print(z)
| true |
da0ec626944e886d766862c1c801f2d89aea8ae1 | Python | rohit-kumar6/DailyCode | /Day2/day2_2.py | UTF-8 | 99 | 3.53125 | 4 | [] | no_license | st = input()
rst = st[::-1]
if st==rst:
print("Pallindrome")
else:
print("Not Pallindrome") | true |
40ea56b4ff235598da95c50692296fd39ff9fee5 | Python | malaffoon/euler | /python/problems/problem10.py | UTF-8 | 503 | 3.953125 | 4 | [] | no_license | """Problem 10 - Project Euler
Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
from utils.prime import primes
class Problem10(object):
@staticmethod
def solve(limit=2000000):
return sum(primes(limit))
@staticmethod
def get_tests():
return [(2000000, 142913828922), (10, 17)]
if __name__ == '__main__':
print("The sum of all the primes below two million is", Problem10().solve())
| true |
1a2eef737b6d8e78790da7472a79b085db80cc9c | Python | shinexia/machine-learning | /decision_tree/cart.py | UTF-8 | 1,653 | 2.625 | 3 | [
"MIT"
] | permissive | import logging
import argparse
import numpy as np
from collections import Counter
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, accuracy_score
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(filename)s:%(lineno)s - %(message)s')
def load_data():
iris = load_iris()
xs = iris.data
ys = iris.target
x_train, x_test, y_train, y_test = train_test_split(xs, ys, test_size=0.2)
logging.info('x_train: %s, y_train: %s, x_test: %s, y_test: %s',
x_train.shape, y_train.shape, x_test.shape, y_test.shape)
return x_train, y_train, x_test, y_test
class TreeNode(object):
def __init__(self, col, split_value, left=None, right=None, label=None):
self.col = col
self.split_value = split_value
self.left = left
self.right = right
self.label = label
@property
def is_leaf(self):
return self.left is None and self.right is None
class CARTModel(object):
def __init__(self, tree: TreeNode = None):
self.tree = tree
def gini(y_train):
c = Counter(y_train)
c = np.array(list(c.values()))
c = c / np.sum(c)
return 1 - np.sum(c * c)
class CART(object):
def __init__(self):
pass
def train(self, x_train, y_train):
pass
def _select_best_split(self, x_train, y_train):
pass
def _split(self, x_train, y_train):
pass
def _build_tree(self, x_train, y_train):
pass
def main():
pass
if __name__ == '__main__':
main()
| true |
7301cf5d30b651e5836231d15cc597edb0a9c4d2 | Python | jmardjuki/decode-hack | /project2.py | UTF-8 | 517 | 2.78125 | 3 | [] | no_license | import pandas as pd
import numpy as np
def main():
data = pd.read_csv("./data/1_oneHots.csv").iloc[:, 1:]
counts = data.drop('METER', axis=1).groupby(['lat', 'lon', 'WEEKDAY']).sum().reset_index()
meterCount = data[['lat', 'lon', 'METER']].groupby(['lat', 'lon'])['METER'].nunique().reset_index().rename(columns={'METER': 'meter_count'})
data = counts.join(meterCount.set_index(['lat', 'lon']), ['lat', 'lon'])
print(data)
data.to_csv('./data/2_data.csv')
# print(data)
if __name__=='__main__':
main() | true |
9ce82aa6e8a76be1fd575a59739d8bfba305622e | Python | martinferianc/PatternRecognition-EIE4 | /Coursework 1/eigenfaces.py | UTF-8 | 10,021 | 2.734375 | 3 | [
"MIT"
] | permissive | import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from numpy.linalg import matrix_power
from pre_process import *
from eigenfaces import *
import copy
from pre_process import compute_eigenspace
class EigenFace:
def __init__(self,dataset,eigenvectors,mean):
#store mean
self.mean = mean
# faces from dataset
self.test_faces = dataset[1][0]
self.train_faces = dataset[0][0]
# labels from dataset
self.test_labels = dataset[1][1].T
self.train_labels = dataset[0][1].T
# order and store initial eigenvalues and eigenvectors from training data
self.eigenvectors = eigenvectors
# temporary variable for number of eigenvectors
self.M = 50
# empty set for selected eigenvalues and vectors
self.m_eigenvectors = []
# training faces projected by selected eigenvalues
self.train_facespace = []
# test faces projected by selected eigenvalues
self.projected_train_faces = []
self.projected_test_faces = []
def nn_classifier(self, face):
nn = copy.deepcopy(self.train_facespace[0])
label_index = 0
min_distance = np.linalg.norm(face - nn)
for i in range(1,self.train_facespace.shape[0]):
#get distance between
curr_distance = np.linalg.norm(face - self.train_facespace[i])
if curr_distance < min_distance:
nn = self.train_facespace[i]
min_distance = curr_distance
label_index = i
return self.train_labels[label_index]
def nn_classifier_index(self, face):
nn = copy.deepcopy(self.train_facespace[0])
label_index = 0
min_distance = np.linalg.norm(face - nn)
for i in range(1,self.train_facespace.shape[0]):
#get distance between
curr_distance = np.linalg.norm(face - self.train_facespace[i])
if curr_distance < min_distance:
nn = self.train_facespace[i]
min_distance = curr_distance
label_index = i
return label_index
# Sort and select the M largest eigenvalues and eigenvectors
def select_M_eigenvectors(self, M, plot=False):
if plot:
plt.plot(self.eigenvalues)
plt.show()
self.m_eigenvectors = copy.deepcopy(self.eigenvectors[:,:M])
# Do the projection through the eigenvectors
def project_to_face_space(self, face):
return np.dot(face.T, self.m_eigenvectors)
def project_all_to_face_space(self):
#self.train_facespace = [self.project_to_face_space(copy.deepcopy(face.T)) for face in self.train_faces.T]
self.train_facespace = self.project_to_face_space(self.train_faces)
#self.projected_test_faces = np.array([self.project_to_face_space(copy.deepcopy(face.T)) for face in self.test_faces.T])
self.projected_test_faces = self.project_to_face_space(self.test_faces)
self.projected_train_faces = self.project_to_face_space(self.train_faces)
return
def plot_img(self,img):
plt.figure()
img = img.reshape((46,56))
img = np.rot90(img,3)
plt.imshow(img, cmap="gray")
plt.show()
def identity_error(self, labels, labels_correct):
err = 0
for i in range(len(labels)):
if labels[i] != labels_correct[i]:
err += 1
#normalise by size of labels
return err/len(labels)
def mse_error(self, img, img_correct):
err = 0
for i in range(img.shape[0]):
err += (img[i,0] - img_correct[i,0])**2
#return ((img - img_correct) ** 2).mean()
return err/img.shape[0]
def abs_error(self, img, img_correct):
err = 0
for i in range(img.shape[0]):
err += abs((img[i,0] - img_correct[i,0]))
#return ((img - img_correct) ** 2).mean()
return err/img.shape[0]
def reconstruction(self,projected_face):
reconstructed_face = copy.deepcopy(self.mean)
for i in range(projected_face.shape[1]):
reconstructed_face += copy.deepcopy(projected_face[0,i]) * copy.deepcopy(self.m_eigenvectors[:,[i]])
return copy.deepcopy(reconstructed_face)
def reconstruction_general(self,projected_face,mean,eigenvectors):
reconstructed_face = copy.deepcopy(mean)
for i in range(projected_face.shape[1]):
reconstructed_face += copy.deepcopy(projected_face[0,i]) * copy.deepcopy(eigenvectors[:,[i]])
return copy.deepcopy(reconstructed_face)
def run_reconstruction_general(self,m,faces,mean,eigenvectors_in):
err_results = []
# select M eigenvectors
eigenvectors = copy.deepcopy(eigenvectors_in[:,:m])
facespace = np.dot(faces.T, eigenvectors)
# run nn classifier for every project test face
for i in range(facespace.shape[0]):
reconstructed_face = copy.deepcopy(self.reconstruction_general(facespace[[i],:],mean,eigenvectors))
err_results.append(self.mse_error(faces[:,[i]]+mean,reconstructed_face))
#print('error: ',np.mean(err_results)/facespace.shape[0])
#print(np.mean(err_results)/facespace.shape[0])
return np.mean(err_results)/facespace.shape[0]
def run_reconstruction(self):
err_results = []
# select M eigenvectors
self.select_M_eigenvectors(self.M, plot=False)
# project to facespace
self.project_all_to_face_space()
# run nn classifier for every project test face
for i in tqdm(range(self.projected_train_faces.shape[0])):
reconstructed_face = copy.deepcopy(self.reconstruction(self.projected_train_faces[[i],:]))
err_results.append(self.mse_error(self.train_faces[:,[i]]+self.mean,reconstructed_face))
print('error: ',np.mean(err_results)/self.projected_train_faces.shape[0])
return np.mean(err_results)/self.projected_train_faces.shape[0]
def run_nn_classifier(self):
# empty array to hold label results
label_results = []
# select M eigenvectors
self.select_M_eigenvectors(self.M, plot=False)
# project to facespace
self.project_all_to_face_space()
# run nn classifier for every project test face
for face in tqdm(self.projected_test_faces):
# get label from nn classifier
label_results.append(self.nn_classifier(face))
err = self.identity_error(label_results,self.test_labels)
print('error: ',err)
return err , label_results
def run_reconstruction_classifier(self,err_min=19,FIXED_M=False):
ERR_MIN = err_min
# Add mean back (not used in this classifier)
train_faces = copy.deepcopy(self.train_faces) + copy.deepcopy(self.mean)
test_faces = copy.deepcopy(self.test_faces) + copy.deepcopy(self.mean)
# Seperate classes
class_space = {}
# Seperate into individual classes
for i in range(self.train_labels.shape[0]):
if not self.train_labels[i] in class_space:
class_space[self.train_labels[i]] = {}
class_space[self.train_labels[i]]['data'] = copy.deepcopy(train_faces[:,[i]])
else:
class_space[self.train_labels[i]]['data'] = copy.deepcopy(np.hstack((class_space[self.train_labels[i]]['data'] ,train_faces[:,[i]])))
for a in class_space:
# compute eigenvectors
_,class_space[a]['eigenvectors'] = copy.deepcopy(compute_eigenspace(class_space[a]['data']))
# select M eigenvectors
#class_space[a]['eigenvectors'] = copy.deepcopy(class_space[a]['eigenvectors'][:,:self.M])
# compute mean
class_space[a]['mean'] = class_space[a]['data'].mean(axis=1).reshape(-1, 1)
if not FIXED_M:
# get possible M
tmp_M = np.arange(1,class_space[a]['eigenvectors'].shape[1])
for m in tmp_M:
err = self.run_reconstruction_general(m,class_space[a]['data'],class_space[a]['mean'],class_space[a]['eigenvectors'])
if err < ERR_MIN:
class_space[a]['eigenvectors'] = copy.deepcopy(class_space[a]['eigenvectors'][:,:m])
break
else:
class_space[a]['eigenvectors'] = copy.deepcopy(class_space[a]['eigenvectors'][:,:self.M])
label_results = []
# Perform reconstruction for each class space and evaluate error
for i in tqdm(range(test_faces.shape[1])):
err_min = float('inf')
label = 0
# Project across each class and evaluate error
for a in class_space:
# remove mean for this class
face = copy.deepcopy(test_faces[:,[i]]) - copy.deepcopy(class_space[a]['mean'])
# project to class eigen space
projected_face = copy.deepcopy(np.matmul(face.T, class_space[a]['eigenvectors']))
# perform reconstruction for this class
reconstructed_face = copy.deepcopy(projected_face[0,0]) * copy.deepcopy(class_space[a]['eigenvectors'][:,[0]])
for j in range(1,projected_face.shape[1]):
reconstructed_face += copy.deepcopy(projected_face[0,j]) * copy.deepcopy(class_space[a]['eigenvectors'][:,[j]])
# get error
err = self.abs_error(face,reconstructed_face) # TODO: make sure it only returns single value
# update error to select minmum error
if err < err_min:
label = a
err_min = err
label_results.append(label)
err = self.identity_error(label_results,self.test_labels)
print('error: ',err)
return err , label_results
if __name__ == '__main__':
t = EigenFace()
t.run_nn_classifier()
| true |
0470e4592d58d0c3bf6dbcbb07c648f46cadce5b | Python | Zeno0/Python | /HANDELING_FILE/binary.py | UTF-8 | 933 | 3.296875 | 3 | [] | no_license | # Creating a binary file
# for creating and writing into a binary file 'bw' is used
with open("HANDELING_FILE/binary",'bw') as binary_file:
for i in range(20):
binary_file.write(bytes([i]))
with open("HANDELING_FILE/binary", 'br') as bin_file:
for b in bin_file:
print(b)
# In output x07 is for a <sound - beep>, to listen it, open the terminal in the binary file directory and enter - "cat binary"
a= 65455
b= 98789
c= 12430
d= 12345
with open("HANDELING_FILE/binary2",'bw') as bin2:
bin2.write(a.to_bytes(2,'big'))
bin2.write(b.to_bytes(4,'big'))
bin2.write(c.to_bytes(2,'big'))
bin2.write(d.to_bytes(2,'big'))
with open("HANDELING_FILE/binary2",'br') as bin:
e = int.from_bytes(bin.read(2), 'big')
print(e)
f = int.from_bytes(bin.read(4), 'big')
print(f)
g = int.from_bytes(bin.read(2), 'big')
print(g)
h = int.from_bytes(bin.read(2), 'big')
print(h) | true |
639365086993586e5b653dedb9c09d010caa9f09 | Python | benx45h/advent-2020 | /15/script.py | UTF-8 | 421 | 3.078125 | 3 | [] | no_license | import re
nums = [8,13,1,0,18]
hist = [1,2,3,4,5]
last = 9
timer = 0
goal = 10000
for i in range(7,30000001):
if(timer == goal):
print(timer)
goal = goal + 10000
if(last not in nums):
num = 0
nums.append(last)
hist.append(i-1)
else:
num = i - 1 - hist[nums.index(last)]
hist[nums.index(last)] = i - 1
last = num
timer = timer + 1
print(num)
| true |
cebca247c6a6207ac26386bf414182831b52b562 | Python | coogleall/FileUpload | /FileUpload/django/mysite/common/utils/util_date.py | UTF-8 | 330 | 3.03125 | 3 | [
"MIT"
] | permissive | import time
# 根据文件上传的时间戳, 格式化为 2020-6-30 12:00:00
def time_stamp_to_date(time_stamp):
now = int(round(time_stamp * 1000))
t = time.localtime(now / 1000)
return time.strftime('%Y-%m-%d %H:%M:%S', t)
if __name__ == '__main__':
stamp = time.time()
print(time_stamp_to_date(stamp))
| true |
4dbb5642ac2cde7e2e89dfe6c2ecc42e90d09145 | Python | AndreaMiola/consumption_behaviour_during_retirement | /src/analysis/visualizing_data.py | UTF-8 | 1,455 | 2.609375 | 3 | [
"MIT"
] | permissive | """Plotting graphs for sub_sample data pointing out the interval confidence
of the different year classes for the expected retirment (exret) and for
actual retirment event (dummy variable job_Retired) coefficients.
"""
import pandas as pd
from matplotlib import pyplot as plt
from regression import years_classes
from bld.project_paths import project_paths_join as ppj
# Import each dataFrame of sub_regression_
for i in ["exret", "job_Retired"]:
coefs = []
deviations = []
labels = []
for y in years_classes:
sub_par = pd.read_pickle(
ppj("OUT_DATA", "sub_" + i + "_" + str(y[0]) + "_" + str(y[1]) + "_par.pkl")
)
sub_std = pd.read_pickle(
ppj("OUT_DATA", "sub_" + i + "_" + str(y[0]) + "_" + str(y[1]) + "_std.pkl")
)
coef = sub_par[1]
dev = sub_std[1] * 1.96
labels.append("From " + str(y[0]) + " to " + str(y[1]))
coefs.append(coef)
deviations.append(dev)
df_plot = pd.DataFrame([coefs, deviations, labels])
exp_name = "CI_" + i + ".pdf"
plt.figure()
x = range(1, len(df_plot.index) + 1)
y = df_plot.iloc[0]
yerr = df_plot.iloc[1]
plt.errorbar(x, y, fmt="bo", yerr=yerr, uplims=True, lolims=True)
plt.xticks(range(1, len(df_plot.index) + 1), df_plot.iloc[2], size="small")
plt.title("CI of " + i + " per years", fontsize=10, weight="bold", wrap="True")
plt.savefig(ppj("OUT_FIGURES", exp_name))
| true |
9de8d576bfea4381885cf59f210084f3e4e00466 | Python | znwang25/fuzzychinese | /fuzzychinese/_utils.py | UTF-8 | 735 | 3.203125 | 3 | [
"BSD-3-Clause"
] | permissive | # Credits to this answer https://stackoverflow.com/a/52837006/8673150
# list of cjk codepoint ranges
# tuples indicate the bottom and top of the range, inclusive
cjk_ranges = [(0x4E00, 0x62FF), (0x6300, 0x77FF), (0x7800, 0x8CFF),
(0x8D00, 0x9FCC), (0x3400, 0x4DB5), (0x20000, 0x215FF),
(0x21600, 0x230FF), (0x23100, 0x245FF), (0x24600, 0x260FF),
(0x26100, 0x275FF), (0x27600, 0x290FF), (0x29100, 0x2A6DF),
(0x2A700, 0x2B734), (0x2B740, 0x2B81D), (0x2B820, 0x2CEAF),
(0x2CEB0, 0x2EBEF), (0x2F800, 0x2FA1F)]
def is_cjk(char):
char = ord(char)
for bottom, top in cjk_ranges:
if char >= bottom and char <= top:
return True
return False | true |
ee8865f43befb6f7dfce39438ec8401b09d798ac | Python | anhanhtdh01/timekeeping_server | /facenet_recognition/src/extract_frame_from_cam.py | UTF-8 | 1,158 | 2.59375 | 3 | [] | no_license | from __future__ import division, print_function, absolute_import
import sys
import os
import time
import cv2
import os
import argparse
def parse_arguments(argv):
''' Input parameters. '''
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output", help="path to image output folder",
default="./frames/")
return parser.parse_args(argv)
args = parse_arguments(sys.argv[1:])
name = input("Nhập tên: ")
id = input("Nhập id: ")
name_folder = name + "_" + str(id)
#Create a folder to save frame
frame_folder = os.path.join(args.output, name_folder)
if not os.path.exists(frame_folder):
os.makedirs(frame_folder)
cap = cv2.VideoCapture(0)
frames_index = 0
while(cap.isOpened()):
ret, frame = cap.read()
if ret == False:
break
# Save frame to disk
cv2.imwrite(os.path.join(frame_folder, name_folder + "_" + str(frames_index) + '.jpg'), frame)
frames_index += 1
cv2.imshow('video', frame)
# Press Q to stop!
if cv2.waitKey(100) & 0xFF == ord('q'):
break
elif frames_index == 200:
break
cap.release()
cv2.destroyAllWindows() | true |
ac3fa95c8ac7924d5b92a426bdd9e71699eebab5 | Python | informatorio2020com07/actividades | /jorgecunado/005/act005.py | UTF-8 | 275 | 3.453125 | 3 | [] | no_license | def esprimo(numero):
if numero < 2:
return False
for n in range(2, numero):
if numero % n == 0:
return False
return True
def primos(a = 0, b = 100):
lista=[]
for a in range(a, b + 1):
if esprimo(a):
lista.append(a)
return tuple(lista)
| true |
95d1414147308145f152fdfe18ff48ada4e2e173 | Python | ironmanyu/Laundry_and_Garbage_Collection | /scripts/actserver_go_to_point.py | UTF-8 | 3,844 | 2.6875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# license removed for brevity
import rospy
# Brings in the SimpleActionClient
import actionlib
# Brings in the .action file and messages used by the move base action
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
<<<<<<< HEAD
def get_goal(x,y,z,qx,qy,qz,qw):
goal = MoveBaseGoal()
goal.target_pose.header.frame_id = "map"
goal.target_pose.header.stamp = rospy.Time.now()
# Select position based on the "map" coordinate frame
goal.target_pose.pose.position.x = x
goal.target_pose.pose.position.y = y
goal.target_pose.pose.position.z = z
# Select orientation w.r.t. map frame
goal.target_pose.pose.orientation.x = qx
goal.target_pose.pose.orientation.y = qy
goal.target_pose.pose.orientation.z = qz
goal.target_pose.pose.orientation.w = qw
return goal
# takes a MoveBaseGoal object
def movebase_client(goal):
=======
def movebase_client():
>>>>>>> e221825f4fec1f832483110c8063ca9898a185bb
# Create an action client called "move_base" with action definition file "MoveBaseAction"
client = actionlib.SimpleActionClient('move_base',MoveBaseAction)
# Waits until the action server has started up and started listening for goals.
client.wait_for_server()
<<<<<<< HEAD
=======
# Creates a new goal with the MoveBaseGoal constructor
goal = MoveBaseGoal()
goal.target_pose.header.frame_id = "map"
goal.target_pose.header.stamp = rospy.Time.now()
# Select position based on the "map" coordinate frame
goal.target_pose.pose.position.x = 3.762
goal.target_pose.pose.position.y = 7.756
goal.target_pose.pose.position.z = 0.0
# Select orientation w.r.t. map frame
goal.target_pose.pose.orientation.x = 0.0
goal.target_pose.pose.orientation.y = 0.0
goal.target_pose.pose.orientation.z = 1.0
goal.target_pose.pose.orientation.w = 0.0
>>>>>>> e221825f4fec1f832483110c8063ca9898a185bb
# Sends the goal to the action server.
client.send_goal(goal)
# Waits for the server to finish performing the action.
wait = client.wait_for_result()
# If the result doesn't arrive, assume the Server is not available
if not wait:
rospy.logerr("Action server not available!")
rospy.signal_shutdown("Action server not available!")
else:
# Result of executing the action
return client.get_result()
# If the python node is executed as main process (sourced directly)
if __name__ == '__main__':
try:
# Initializes a rospy node to let the SimpleActionClient publish and subscribe
rospy.init_node('planning_goal')
<<<<<<< HEAD
# Creates a new goal with the MoveBaseGoal constructor
goal_list = []
# # table
# goal_list.append(get_goal(3.469, 3.349, 0.000, -0.0, -0.0, 0.212, 0.977))
# # start pose
# goal_list.append(get_goal(-0.459, -0.880, 0.000, 0.0, 0.0, -0.064, 0.998))
# in door init
goal_list.append(get_goal(-5.554, 1.341, 0.000, 0.0, 0.0, 0.730, 0.684))
# in door final
goal_list.append(get_goal(-5.583, -0.682, 0.000, 0.0, 0.0, -0.736, 0.677))
# out door init
goal_list.append(get_goal(-5.444, -0.462, 0.000, 0.0, 0.0, 0.668, 0.744))
# out door final
goal_list.append(get_goal(-5.356, 1.185, 0.000, 0.0, 0.0, 0.682, 0.731))
# start pose
goal_list.append(get_goal(-0.459, -0.880, 0.000, 0.0, 0.0, -0.064, 0.998))
for goal in goal_list:
result = movebase_client(goal)
if result:
rospy.loginfo("Goal execution done!")
=======
result = movebase_client()
if result:
rospy.loginfo("Goal execution done!")
>>>>>>> e221825f4fec1f832483110c8063ca9898a185bb
except rospy.ROSInterruptException:
rospy.loginfo("Navigation test finished.")
| true |
276f7d821dcc3cee2a1dea8e4a5f441835b6278d | Python | juselius/python-tutorials | /Basics/looptricks.py | UTF-8 | 463 | 4.15625 | 4 | [] | no_license | # Often we need an index, as well as a value:
for i, v in enumerate(['tic', 'tac', 'toe']):
print i, v
# Looping over two sets of values:
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print 'What is your {0}? It is {1}.'.format(q, a)
# Looping backwards:
for i in reversed(range(1,10,2)):
print i
# List comprehensions:
print [ i for i in range(8) if i % 2]
| true |
1b4b136d6b0b68f7d2081eca326cb64ceda84e2e | Python | cognitivexr/sandbox-vision | /cpopservice/utils/common.py | UTF-8 | 4,306 | 2.59375 | 3 | [] | no_license | import os
import time
import uuid
import logging
import tarfile
import threading
import traceback
import subprocess
import psutil
import requests
LOG = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF-8'
class FuncThread(threading.Thread):
""" Helper class to run a Python function in a background (daemon) thread. """
def __init__(self, func, *args, **kwargs):
threading.Thread.__init__(self)
self.daemon = True
self.func = func
self.func_args = args
self.func_kwargs = kwargs
def run(self):
try:
self.func(*self.func_args, **self.func_kwargs)
except Exception as e:
LOG.warning('Thread run method %s failed: %s %s' %
(self.func, e, traceback.format_exc()))
def stop(self):
LOG.warning('Not implemented: FuncThread.stop(..)')
class ShellCommandThread(FuncThread):
""" Helper class to run a shell command in a background thread. """
def __init__(self, cmd, log_result=False):
self.cmd = cmd
self.log_result = log_result
FuncThread.__init__(self, self.run_cmd)
def run_cmd(self):
self.process = run(self.cmd, asynchronous=True)
result = self.process.communicate()
if self.log_result:
LOG.info('Command "%s" produced output: %s' % (self.cmd, result))
def stop(self):
LOG.info('Terminating process: %s' % self.process.pid)
kill_process_tree(self.process.pid)
def run(command, asynchronous=False, quiet=True):
""" Run a shell command and return the output as a string """
if not asynchronous:
return to_str(subprocess.check_output(command, shell=True))
kwargs = {'stdout': subprocess.DEVNULL} if quiet else {}
process = subprocess.Popen(command, stderr=subprocess.STDOUT, shell=True, **kwargs)
return process
def find_command(cmd):
try:
return run('which %s' % cmd).strip()
except Exception:
pass
def get_os_type():
if is_mac_os():
return 'osx'
if is_alpine():
return 'alpine'
if is_linux():
return 'linux'
raise Exception('Unable to determine operating system')
def is_mac_os():
return 'Darwin' in get_uname()
def is_linux():
return 'Linux' in get_uname()
def is_alpine():
try:
if not os.path.exists('/etc/issue'):
return False
issue = to_str(run('cat /etc/issue'))
return 'Alpine' in issue
except subprocess.CalledProcessError:
return False
def short_uid():
return str(uuid.uuid4())[0:8]
def mkdir(folder):
if not os.path.exists(folder):
os.makedirs(folder)
def download(url, target):
response = requests.get(url, allow_redirects=True)
with open(target, 'wb') as f:
f.write(response.content)
def untar(path, target_dir):
mode = 'r:gz' if path.endswith('gz') else 'r'
with tarfile.open(path, mode) as tar:
tar.extractall(path=target_dir)
def get_uname():
try:
return run('uname -a')
except Exception:
return ''
def kill_process_tree(parent_pid):
parent_pid = getattr(parent_pid, 'pid', None) or parent_pid
parent = psutil.Process(parent_pid)
for child in parent.children(recursive=True):
try:
child.kill()
except Exception:
pass
parent.kill()
def sleep_forever():
while True:
time.sleep(1)
def retry(function, retries=3, sleep=1, sleep_before=0, **kwargs):
raise_error = None
if sleep_before > 0:
time.sleep(sleep_before)
for i in range(0, retries + 1):
try:
return function(**kwargs)
except Exception as error:
raise_error = error
time.sleep(sleep)
raise raise_error
def to_str(obj, encoding=DEFAULT_ENCODING, errors='strict'):
""" If ``obj`` is an instance of ``bytes``, return
``obj.decode(encoding, errors)``, otherwise return ``obj`` """
return obj.decode(encoding, errors) if isinstance(obj, bytes) else obj
def to_bytes(obj, encoding=DEFAULT_ENCODING, errors='strict'):
""" If ``obj`` is an instance of ``str``, return
``obj.encode(encoding, errors)``, otherwise return ``obj`` """
return obj.encode(encoding, errors) if isinstance(obj, str) else obj
| true |
89b270537398558792d69c1b6d2ee2e3147e3506 | Python | SmallPuddingComing/Python-learn | /show_me_the_code/Activition_code.py | UTF-8 | 761 | 3.390625 | 3 | [] | no_license | #coding:utf8
'''
creaet a amounts of activition code
1、创建一个文本,进行存贮激活码
2、激活码的组成来源于string模块里面的大小写字母和数字
3、制定序列号的长度,得到序列号后进行字符串化
4、序列号存进文本文件
5、自定义传参可以指定生成数量
'''
import string
import random
def create_activition_code(num, length=7):
fp = open('C:/Users/yuanrong/Desktop/photos/Activition_code.txt', 'wb')
L = [string.letters, string.digits]
for i in xrange(num):
mylist = [random.choice(L[random.randint(0,1)]) for x in xrange(length)]
mylist = ''.join(mylist)
fp.write(mylist + '\n')
fp.close()
if __name__ == '__main__':
create_activition_code(200) | true |
7922944616e13e6a8acbb2344b1d3d8e3ba154da | Python | sveetch/django-palette | /tests/100_forms/002_palette.py | UTF-8 | 9,592 | 2.515625 | 3 | [] | no_license | import pytest
import json
from django.forms import formset_factory
from tests.utils import assert_and_parse_html
from django_palette.forms.palette import (formset_data_helper,
PaletteItemFormSet,
PaletteItemForm)
@pytest.mark.parametrize("data,options,expected", [
# single item with single choice, no fields
(
{
"#f0f0f0": [("gray94", "#f0f0f0")],
},
{"fields": False, "initials": False},
{
"form-TOTAL_FORMS": 1,
"form-INITIAL_FORMS": 1,
"form-MAX_NUM_FORMS": "",
},
),
# single item with single choice, no initials
(
{
"#f0f0f0": [("gray94", "#f0f0f0")],
},
{"fields": True, "initials": False},
{
"form-TOTAL_FORMS": 1,
"form-INITIAL_FORMS": 1,
"form-MAX_NUM_FORMS": "",
"form-0-color": "",
"form-0-name": "",
},
),
# single item with single choice
(
{
"#f0f0f0": [("gray94", "#f0f0f0")],
},
{"fields": True, "initials": True},
{
"form-TOTAL_FORMS": 1,
"form-INITIAL_FORMS": 1,
"form-MAX_NUM_FORMS": "",
"form-0-color": "#f0f0f0",
"form-0-name": "gray94",
},
),
# multiple item with single choice
(
{
"#000000": [("black", "#000000")],
"#f0f0f0": [("gray94", "#f0f0f0")],
"#ff0000": [("red1", "#ff0000")],
},
{"fields": True, "initials": True},
{
"form-TOTAL_FORMS": 3,
"form-INITIAL_FORMS": 3,
"form-MAX_NUM_FORMS": "",
"form-0-color": "#000000",
"form-0-name": "black",
"form-1-color": "#f0f0f0",
"form-1-name": "gray94",
"form-2-color": "#ff0000",
"form-2-name": "red1",
},
),
# multiple item with multiple choice
(
{
"#000000": [("black", "#000000")],
"#f0f0f0": [
("gray94", "#f0f0f0"),
("grey2", "#f0f0f0"),
],
"#ff0000": [
("red1", "#ff0000"),
("firebrick0", "#ff0000"),
],
},
{"fields": True, "initials": True},
{
"form-TOTAL_FORMS": 3,
"form-INITIAL_FORMS": 3,
"form-MAX_NUM_FORMS": "",
"form-0-color": "#000000",
"form-0-name": "black",
"form-1-color": "#f0f0f0",
"form-1-name": "gray94",
"form-2-color": "#ff0000",
"form-2-name": "red1",
},
),
])
def test_formset_data_helper(data, options, expected):
assert formset_data_helper(data, **options) == expected
def test_formset_build():
"""
Build formset with some initial and check returned HTML is ok
"""
# Initial data to add forms
initial = [
{
"color": "#000000",
"name": "black",
},
{
"color": "#ffffff",
"name": "white",
},
]
# Order of expected form HTML must follow the "initial" items order to
# correctly be checked against the right form
# Expected HTML include some indentation to be more human readable but
# are not mandatory
expected_forms = [
(
"""<p>"""
""" <label for="id_form-0-color">Color:</label>"""
""" <input type="text" name="form-0-color" value="#000000" id="id_form-0-color" />"""
"""</p>"""
"""<p>"""
""" <label for="id_form-0-name">Name:</label>"""
""" <input type="text" name="form-0-name" value="black" maxlength="50" id="id_form-0-name" minlength="3" />"""
"""</p>"""
),
(
"""<p>"""
""" <label for="id_form-1-color">Color:</label>"""
""" <input type="text" name="form-1-color" value="#ffffff" id="id_form-1-color" />"""
"""</p>"""
"""<p>"""
""" <label for="id_form-1-name">Name:</label>"""
""" <input type="text" name="form-1-name" value="white" maxlength="50" id="id_form-1-name" minlength="3" />"""
"""</p>"""
),
]
# Create formset factory without extra form
factory = formset_factory(
PaletteItemForm,
extra=0,
)
# Build formset according to given initial data and dynamic choices
formset = factory(initial=initial)
for i, form in enumerate(formset):
expected_html = expected_forms[i]
assert assert_and_parse_html(form.as_p()) == assert_and_parse_html(expected_html)
@pytest.mark.parametrize("data,is_valid,errors", [
# no errors, everything is fine, note we use color name instead of hex
# code, this is fine also
(
{
"form-TOTAL_FORMS": "2",
"form-INITIAL_FORMS": "2",
"form-MAX_NUM_FORMS": "",
"form-0-color": "white",
"form-0-name": "dummy",
"form-1-color": "black",
"form-1-name": "foo",
},
True,
[
{},
{}
],
),
# no errors, everything is fine
(
{
"form-TOTAL_FORMS": "2",
"form-INITIAL_FORMS": "2",
"form-MAX_NUM_FORMS": "",
"form-0-color": "#FFFFFF",
"form-0-name": "white",
"form-1-color": "#000",
"form-1-name": "black",
},
True,
[
{},
{}
],
),
# second form fields are empty
(
{
"form-TOTAL_FORMS": "2",
"form-INITIAL_FORMS": "2",
"form-MAX_NUM_FORMS": "",
"form-0-color": "dummy",
"form-0-name": "fake",
"form-1-color": "",
"form-1-name": "",
},
False,
[
{},
{
"name": ["This field is required."],
"color": ["This field is required."],
}
],
),
# rgb(a) notation is not supported
(
{
"form-TOTAL_FORMS": "2",
"form-INITIAL_FORMS": "2",
"form-MAX_NUM_FORMS": "",
"form-0-color": "#FFFFFF",
"form-0-name": "white",
"form-1-color": "rgb(0, 0, 0)",
"form-1-name": "black",
},
False,
[
{},
{
"color": ["RGB(A) values are not supported"],
}
],
),
# Wrong hex color codes
(
{
"form-TOTAL_FORMS": "3",
"form-INITIAL_FORMS": "3",
"form-MAX_NUM_FORMS": "",
"form-0-color": "#ff",
"form-0-name": "foo",
"form-1-color": "##000000",
"form-1-name": "bar",
"form-2-color": "#f0f0z0",
"form-2-name": "ping",
},
False,
[
{
"color": ["Invalid Hexadecimal code"],
},
{
"color": ["Invalid Hexadecimal code"],
},
{
"color": ["Invalid Hexadecimal code"],
},
],
),
# Both valid and invalid names
(
{
"form-TOTAL_FORMS": "4",
"form-INITIAL_FORMS": "4",
"form-MAX_NUM_FORMS": "",
"form-0-color": "#ffffff",
"form-0-name": "foo bar",
"form-1-color": "#000000",
"form-1-name": "foo-bar",
"form-2-color": "#f0f0f0",
"form-2-name": "-foobar",
"form-3-color": "#f0f0f0",
"form-3-name": "_foobar",
},
False,
[
{
"name": ["Invalid name"],
},
{},
{
"name": ["Invalid name"],
},
{
"name": ["Invalid name"],
},
],
),
])
def test_formset_field_errors(data, is_valid, errors):
"""
Check against various errors on formset form fields
"""
factory = formset_factory(
PaletteItemForm,
extra=0,
formset=PaletteItemFormSet,
)
formset = factory(data)
assert formset.is_valid() == is_valid
assert formset.errors == errors
@pytest.mark.parametrize("data,expected_palette", [
(
{
"form-TOTAL_FORMS": "3",
"form-INITIAL_FORMS": "3",
"form-MAX_NUM_FORMS": "",
"form-0-color": "#FFF",
"form-0-name": "white",
"form-1-color": "Yellow",
"form-1-name": "Yellow",
"form-2-color": "#404040",
"form-2-name": "gray25",
},
[
{
"color": "#fff",
"name": "white"
},
{
"color": "yellow",
"name": "yellow"
},
{
"color": "#404040",
"name": "gray25"
},
],
),
])
def test_results(data, expected_palette):
factory = formset_factory(
PaletteItemForm,
extra=0,
formset=PaletteItemFormSet,
)
formset = factory(data)
assert formset.is_valid() == True
results = formset.save()
assert (len(results["formats"]) > 0) == True
assert expected_palette == results["palette"]
| true |
e4de6d42aea31a75d259b710870bee7183cc639c | Python | mbisbano1/369_Project_1 | /experiment2/TCPClient.py | UTF-8 | 1,495 | 3.34375 | 3 | [] | no_license | import socket
import sys
encoding="UTF-8"
class TCPClient:
def __init__(self):
if (len(sys.argv) != 3):
print("Usage: python3 TCPClient.py server_address server_port")
exit(1)
serverAddress=sys.argv[1]
try:
serverPort=int(sys.argv[2])
except ValueError:
print("Error: input argument invalid.")
exit(1)
if ((serverPort <= 1024) or (serverPort >= 65536)):
print("Error: Server port value must be greater than 1024 and less than 65536.")
exit(1)
self.connect(serverAddress, serverPort)
def connect(self, serverAddress, serverPort):
try:
clientSocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
clientSocket.connect((serverAddress, serverPort))
except ConnectionRefusedError:
print("Error: Connection refused.")
exit(1)
print("Type \"quit\" to exit the client, or \"shutdown\" to turn off server.")
while 1:
message=input("Enter a message: ")
clientSocket.send(message.encode(encoding))
modifiedMessage=clientSocket.recv(1024)
print("Received message: %s" % modifiedMessage.decode(encoding))
if ((message == "quit") or (message == "shutdown")):
break
clientSocket.close()
except KeyboardInterrupt:
print("Keyboard interrupt")
if (clientSocket):
clientSocket.close()
print("Socket closed successfully.")
except Exception as ex:
print("Exception: %s" % ex)
if (clientSocket):
clientSocket.close()
print("Socket closed successfully.")
TCPClient()
| true |
3357374ff9e330b5c7c8683c43f34d09221d3ad4 | Python | ketan-lambat/Tic-Tac-Toe-using-AI | /src/Open Field Tic Tac Toe/AI_algo_custom.py | UTF-8 | 6,117 | 3.09375 | 3 | [
"MIT"
] | permissive | import random
from OpenField_TTT import *
# if AI turn isMax = True
def random_cell(TTT):
rndm_num = random.randint(0, len(empty_cells(TTT))-1)
cells = empty_cells(TTT)
rndm_cell = cells[rndm_num]
return rndm_cell
def minimax(TTT, isMax):
if isMax:
best = [-1, -1, -inf]
else:
best = [-1, -1, inf]
if len(empty_cells(TTT)) == 0 or is_winner(TTT):
score = eval(TTT)
return [-1, -1, score]
for cell in empty_cells(TTT):
x, y = cell[0], cell[1]
if isMax:
TTT[x][y] = 'o'
else:
TTT[x][y] = 'x'
score = minimax(TTT, not isMax)
TTT[x][y] = None
score[0], score[1] = x, y
if isMax:
if score[2] > best[2]:
best = score
else:
if score[2] < best[2]:
best = score
return best
def alpha_beta(TTT, alpha, beta, isMax):
if isMax:
best = [-1, -1, -inf]
else:
best = [-1, -1, inf]
if len(empty_cells(TTT)) == 0 or is_winner(TTT):
score = eval(TTT)
return [-1, -1, score]
for cell in empty_cells(TTT):
x, y = cell[0], cell[1]
if isMax:
TTT[x][y] = 'o'
else:
TTT[x][y] = 'x'
score = alpha_beta(TTT, alpha, beta, not isMax)
TTT[x][y] = None
score[0], score[1] = x, y
if isMax:
if score[2] > best[2]:
best = score
alpha = max(alpha, best[2])
if beta <= alpha:
break
else:
if score[2] < best[2]:
best = score
beta = min(beta, best[2])
if beta <= alpha:
break
return best
def minimax_depth_limit(TTT, depth, isMax):
if isMax:
best = [-1, -1, -inf]
else:
best = [-1, -1, inf]
if len(empty_cells(TTT)) == 0 or is_winner(TTT):
score = eval(TTT)
return [-1, -1, score]
# cutoff at depth of 3 and evaluate TTT state
if depth == 1:
result = eval_heuristic(TTT)
return [-1, -1, result]
for cell in empty_cells(TTT):
x, y = cell[0], cell[1]
if isMax:
TTT[x][y] = 'o'
else:
TTT[x][y] = 'x'
score = minimax_depth_limit(TTT, depth+1, not isMax)
TTT[x][y] = None
score[0], score[1] = x, y
if isMax:
if score[2] > best[2]:
best = score
else:
if score[2] < best[2]:
best = score
return best
def depth_alphabeta(TTT, depth, alpha, beta, isMax):
if isMax:
best = [-1, -1, -inf]
else:
best = [-1, -1, inf]
if len(empty_cells(TTT)) == 0 or is_winner(TTT):
score = eval(TTT)
return [-1, -1, score]
# cutoff at depth of 3 and evaluate TTT state
if depth == 2:
result = eval_heuristic(TTT)
return [-1, -1, result]
for cell in empty_cells(TTT):
x, y = cell[0], cell[1]
if isMax:
TTT[x][y] = 'o'
else:
TTT[x][y] = 'x'
score = depth_alphabeta(TTT, depth+1, alpha, beta, not isMax)
TTT[x][y] = None
score[0], score[1] = x, y
if isMax:
if score[2] > best[2]:
best = score
alpha = max(alpha, best[2])
if beta <= alpha:
break
else:
if score[2] < best[2]:
best = score
beta = min(beta, best[2])
if beta <= alpha:
break
return best
def minimax_exper(TTT, depth, alpha, beta, isMax):
if isMax:
best = [-1, -1, -inf]
else:
best = [-1, -1, inf]
if len(empty_cells(TTT)) == 0 or is_winner(TTT):
score = eval(TTT)
return [-1, -1, score]
# cutoff at depth of 3 and evaluate TTT state
if depth == 1:
result = eval_heuristic(TTT)
return [-1, -1, result]
for cell in empty_cells(TTT):
x, y = cell[0], cell[1]
if isMax:
TTT[x][y] = 'o'
else:
TTT[x][y] = 'x'
score = minimax_exper(TTT, depth+1, alpha, beta, not isMax)
TTT[x][y] = None
score[0], score[1] = x, y
if isMax:
if score[2] > best[2]:
best = score
alpha = max(alpha, best[2])
if beta <= alpha:
break
else:
if score[2] < best[2]:
best = score
beta = min(beta, best[2])
if beta <= alpha:
break
return best
def eval_heuristic(TTT):
# no of possible wins in next 2 moves of AI
score_AI = 0
for cell_i in empty_cells(TTT):
x_i, y_i = cell_i[0], cell_i[1]
TTT[x_i][y_i] = 'o'
for cell_j in empty_cells(TTT):
x_j, y_j = cell_j[0], cell_j[1]
TTT[x_j][y_j] = 'o'
if is_winner(TTT) == 'o':
score_AI = score_AI + 1
TTT[x_j][y_j] = None
TTT[x_i][y_i] = None
# no of possible wins in next 2 moves of User
score_User = 0
for cell_i in empty_cells(TTT):
x_i, y_i = cell_i[0], cell_i[1]
TTT[x_i][y_i] = 'x'
for cell_j in empty_cells(TTT):
x_j, y_j = cell_j[0], cell_j[1]
TTT[x_j][y_j] = 'x'
if is_winner(TTT) == 'x':
score_User = score_User + 1
TTT[x_j][y_j] = None
TTT[x_i][y_i] = None
if score_AI > score_User:
score = 10
elif score_AI < score_User:
score = -10
else:
score = 0
return score
def grid_size_4():
return 4
def grid_size_5():
return 5
def grid_size_6():
return 6
def grid_size_7():
return 7
def grid_size_8():
return 8
def grid_size_9():
return 9
def grid_size_10():
return 10
def get_algo_1():
return 1
def get_algo_2():
return 2
def get_algo_3():
return 3
def get_algo_4():
return 4
def get_algo_5():
return 5
def get_algo_6():
return 6
| true |
24a8158547b80311056e7c7aeb6cfedf06bc62ef | Python | mlalandag/Reacher | /agent_testing.py | UTF-8 | 2,258 | 3.15625 | 3 | [] | no_license |
from unityagents import UnityEnvironment
import numpy as np
import torch
import time
from agent import Agent
num_agents = 1
# please do not modify the line below
env = UnityEnvironment(file_name="Reacher_Windows_x86_64/Reacher.exe")
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
# reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents in the environment
print('Number of agents:', len(env_info.agents))
# number of actions
action_size = brain.vector_action_space_size
print('Number of actions:', action_size)
# examine the state space
state = env_info.vector_observations[0]
print('States look like:', state)
state_size = len(state)
print('States have length:', state_size)
max_num_episodes = 5
agent = Agent(state_size, action_size, 1)
agent.actor_local.load_state_dict(torch.load('actor_weights.pth'))
agent.critic_local.load_state_dict(torch.load('critic_weights.pth'))
for episode in range(1, max_num_episodes+1):
env_info = env.reset(train_mode=True)[brain_name] # reset the environment
state = env_info.vector_observations[0] # get the current state
score = 0 # initialize the score
while True:
action = agent.act(state) # select an action (for each agent)
action = np.clip(action, -1, 1) # all actions between -1 and 1
env_info = env.step(action)[brain_name] # send all actions to tne environment
next_state = env_info.vector_observations[0] # get next state (for each agent)
reward = env_info.rewards[0] # get reward (for each agent)
done = env_info.local_done[0] # see if episode finished
score += reward # update the score
state = next_state # roll over the state to next time step
time.sleep(0.005)
if np.any(done): # exit loop if episode finished
break
print('\rEpisode {}\tScore: {:.2f}'.format(episode, score))
#When finished, you can close the environment.
env.close()
| true |
ae708832a37dcd93bb54fc46b177102a05700409 | Python | Lyppeh/PythonExercises | /Repetition Structure Exercises/ex047.py | UTF-8 | 94 | 3.5625 | 4 | [] | no_license | print('Os números pares entre 1 e 50 são:')
for c in range(2, 51, 2):
print(c, end=' ')
| true |
c3fc8738a769ce7a73b1d7eab8f5a3da0fabd324 | Python | fabiogallotti/adventofcode | /src/year2020/day04/exercises.py | UTF-8 | 416 | 2.828125 | 3 | [] | no_license | from functions.read_input import read_input
from inputs.path import PATH
from .functions import preprocessing, valid_passport, validate_data_passport
data = read_input(f"{PATH}/2020/day04.txt")
passports = preprocessing(data)
print(f"First part: {sum(1 for passport in passports if valid_passport(passport))}")
print(
f"Second part: {sum(1 for passport in passports if validate_data_passport(passport))}"
)
| true |
5cd3d2b7e6fc2fd5946478c0544eeeb34e533f40 | Python | simonenkoav/depth-model | /depth_model/train.py | UTF-8 | 3,921 | 2.5625 | 3 | [] | no_license | import os
from sys import stdout
import shutil
import numpy as np
from random import shuffle
import cv2
from keras.callbacks import ModelCheckpoint
from make_net import get_unet
from image_processing import read_sample, reverse_depth_image, img_rows, img_cols
from save_results_callback import SaveResults
from data import load_test_not_none, load_not_none
model_filename = "model.h5"
def std_print(str):
stdout.write(str + "\n")
stdout.flush()
def image_generator(data, read_sample, shuffle=False):
if shuffle:
np.random.shuffle(data)
for img_filenames in data:
img_real, depth_real = read_sample(img_filenames)
yield img_real, depth_real
def batch_generator(img_generator, batch_size=32):
while True:
cur_batch_x = []
cur_batch_y = []
img_gen = img_generator()
for image, depth in img_gen:
cur_batch_x.append(image)
cur_batch_y.append(depth)
if len(cur_batch_x) == batch_size:
yield (np.array(cur_batch_x), np.array(cur_batch_y))
cur_batch_x = []
cur_batch_y = []
def make_logs_dirs():
results_dir = "epochs_results/"
if os.path.exists(results_dir):
shutil.rmtree(results_dir)
os.makedirs(results_dir)
checkpoint_dir = "snapshot/"
if os.path.exists(checkpoint_dir):
shutil.rmtree(checkpoint_dir)
os.makedirs(checkpoint_dir)
return results_dir, checkpoint_dir
def train():
print('-' * 30)
print('Loading and preprocessing train data...')
print('-' * 30)
train_data = load_not_none()
test_data = load_test_not_none()
shuffle(test_data)
test_data = test_data[:1000]
img_generator = lambda: image_generator(train_data, read_sample, shuffle=True)
train_generator = batch_generator(img_generator, 8)
test_img_gen = lambda: image_generator(test_data, read_sample, shuffle=True)
test_generator = batch_generator(test_img_gen, 8)
print('-' * 30)
print('Creating and compiling model...')
print('-' * 30)
model = get_unet()
print(str(model.summary()))
print('-' * 30)
print('Fitting model...')
print('-' * 30)
results_dir, checkpoint_dir = make_logs_dirs()
checkpoint = ModelCheckpoint(checkpoint_dir + '/weights.{epoch:02d}-loss_{loss:.3f}.hdf5', monitor='loss', verbose=0,
save_best_only=False, mode='auto')
save_results = SaveResults(train_data, results_dir, checkpoint_dir)
model.fit_generator(generator=train_generator, steps_per_epoch=11300, verbose=1, epochs=10,
callbacks=[checkpoint, save_results], validation_data=test_generator, validation_steps=125)
model.save(model_filename)
def predict():
model = load_model(model_filename)
print('-' * 30)
print('Loading and preprocessing test data...')
print('-' * 30)
test_filenames = load_test_not_none()
shuffle(test_filenames)
pred_dir = 'preds'
if not os.path.exists(pred_dir):
os.mkdir(pred_dir)
real_dir = 'real'
if not os.path.exists(real_dir):
os.mkdir(real_dir)
for i in range(10):
print("test[" + str(i) + "]")
print("rgb = " + str(test_filenames[i]["image"]))
print("depth = " + str(test_filenames[i]["depth"]))
rgb_img = read_rgb_image(test_filenames[i]["image"])
depth_img = cv2.imread(test_filenames[i]["depth"])
depth_img = preprocess(depth_img)
cv2.imwrite(real_dir + '/real_depth' + str(i) + '.pgm', depth_img)
rgb_img = rgb_img[np.newaxis, :, :, :]
predicted_depth = reverse_depth_image(model.predict(rgb_img)[0])
cv2.imwrite(pred_dir + '/predicted_depth' + str(i) + '.pgm', predicted_depth)
if __name__ == '__main__':
train()
# predict()
| true |
836b252404e3bd2c76fa8dd08ac7f6ff50e7d256 | Python | higorsilvaa/Numerical_Methods | /Root-Finding_Algorithms/MPF.py | UTF-8 | 1,229 | 3.828125 | 4 | [] | no_license | import pandas as pd
def f(x):
return #definir a função
def fi(x):
#fi nada mais é do que o ilosamento de um x
#Ex.: Dada a função y = x²-x+9, fi¹(x) poderia ser x²+9, onde isolamos -x e fi²(x) poderia ser ²v(x-9), ou seja, raiz quadrada de x-9.
return #definir a função de isolamento de x
def dfi(x):
return #definir a derivada de fi(x)
def MPF(x, t): #Onde x é o chute inicial e t é a precisão, f é a função de x, fi é a função onde isolamos um x e dfi é a derivada de fi
a, x0 = dfi(x), x
if abs(a) <= 1.0: #Condição de convergência
print('Derivada dfi(x): %f\n' % a)
table = pd.DataFrame({'x':[x0], 'fi(x)':[fi(x0)], 'f(x)':[f(x0)], '|x - x0|':[abs(fi(x0)-x0)]})
table.index.names = ['it']
while True:
x1 = fi(x0)
if abs(f(x1)) < t or abs(x1 - x0) < t:
break
x0 = x1
table.loc[len(table)] = [x0, fi(x0), f(x0), abs(fi(x0)-x0)] # Adicionando mais uma linha no dataframe
print('Tabela de execuções (MPF)\n')
print(table, '\n')
return x1
else:
print("Não possui raiz nesse intervalo!")
| true |
5ba4c6c94deb66a1745f9e85f91f9bcacb896d2b | Python | BennyW23/AdventOfCode | /aoc2018/day4_p2.py | UTF-8 | 1,888 | 3.078125 | 3 | [] | no_license | def read_input(inp):
f = open(inp, "r")
l = f.readlines()
for i in range(len(l)):
l[i] = l[i].strip("\n")
return l
def sort_input(l):
ans = []
for line in l:
i = 0
while True:
if i == len(ans):
ans.append(line)
break
elif before(line, ans[i]):
ans.insert(i, line)
break
else:
i += 1
return ans
def before(l1, l2):
mo1, mo2 = int(l1[6:8]), int(l2[6:8])
d1, d2 = int(l1[9:11]), int(l2[9:11])
h1, h2 = int(l1[12:14]), int(l2[12:14])
m1, m2 = int(l1[15:17]), int(l2[15:17])
if mo1 == mo2:
if d1 == d2:
if h1 == h2:
return m1 < m2
else:
return h1 < h2
else:
return d1 < d2
else:
return mo1 < mo2
l = read_input("day4.txt")
guard_number = 0
time_asleep = {} # entries in this are lists of 60 long
# l = read_input('day4ex.txt')
inp = sort_input(l)
for line in inp:
if line[19] == "G":
guard_number = int(line[26:].split(" ", 1)[0])
elif line[19] == "f":
begintime = int(line[15:17])
elif line[19] == "w":
if guard_number in time_asleep:
tup = time_asleep[guard_number]
for i in range(begintime, int(line[15:17])):
tup[i] += 1
time_asleep[guard_number] = tup
else:
tup = [0 for i in range(0, 60)]
for i in range(begintime, int(line[15:17])):
tup[i] += 1
time_asleep[guard_number] = tup
maxid = 0
maxminute = 0
maxvalue = 0
for key, tup in time_asleep.items():
for i in range(60):
if tup[i] > maxvalue:
maxvalue = tup[i]
maxminute = i
maxid = key
print maxvalue, maxminute, maxid
print maxminute * maxid
| true |
30ca5aeead9e372910777ddb4bc9669f35652720 | Python | mikepqr/algorithms | /dpv/00-big-oh/fib.py | UTF-8 | 1,254 | 3.640625 | 4 | [] | no_license | import expsq
import functools
class matrix(object):
'''Trivial 2x2 matrix class implementing multiplication only.'''
def __init__(self, a, b, c, d):
# X = [[a b]
# [c d]]
self.values = [a, b, c, d]
def __repr__(self):
return "{}({}, {}, {}, {})".format(self.__class__.__name__,
*self.values)
def __mul__(self, other):
a = self.values[0] * other.values[0] + self.values[1] * other.values[2]
b = self.values[0] * other.values[1] + self.values[1] * other.values[3]
c = self.values[2] * other.values[0] + self.values[3] * other.values[2]
d = self.values[2] * other.values[1] + self.values[3] * other.values[3]
return matrix(a, b, c, d)
# http://mike.place/2016/memoization/
@functools.lru_cache()
def fib1(n):
'''Return the nth Fibonnaci number using recursion and memoization.'''
if n == 0:
return 0
if n == 1:
return 1
return fib1(n - 1) + fib1(n - 2)
def fib3(n):
'''Return the nth Fibonnaci number using matrix exponentiation.'''
if n == 0:
return 0
if n == 1:
return 1
x = matrix(0, 1, 1, 1)
xn = expsq.expsq(x, n)
return xn.values[1]
| true |
03f32ced4334fe875804705424285f63f0d3d8bb | Python | Forest-Y/AtCoder | /boot/hard/b.py | UTF-8 | 160 | 2.90625 | 3 | [] | no_license | n, l = map(int, input().split())
a = [l] * n
ans = 0
for i in range(1, n):
a[i] += i
if abs(a[ans]) > abs(a[i]):
ans = i
print(sum(a) - a[ans]) | true |
a69b8d7133218508ab3b83f174f7f561df3b0ad3 | Python | DQDH/Algorithm_Code | /ProgramForLeetCode/Recruit/xiecheng2.py | UTF-8 | 562 | 3.015625 | 3 | [] | no_license | class solution(object):
def auc_func(self,l,p):
two_list = list(zip(p,l))
rank = [values2 for values1,values2 in sorted(two_list,key=lambda x:x[0])]
st = [i+1 for i in range(len(rank)) if rank[i]==1]
tp,fp = 0,0
for i in range(len(l)):
if(l[i]==1):
tp+=1
else:
fp+=1
auc = (sum(st)- (tp*(tp+1))/2)/(tp*fp)
return auc
n = int(input())
l = []
p = []
for i in range(n):
s = input().split(' ')
l.append(int(s[0]))
p.append(float(s[1]))
print(solution().auc_func(l,p)) | true |
2c59d484a08f91fe512503a70a4f4c8055d0030b | Python | Rev8Crew/adcp-filter | /app/Model.py | UTF-8 | 9,936 | 3.140625 | 3 | [] | no_license | import pandas as pd
import math
from .Validator import Validator
class Model:
N = 0
deleteNumber = '-32768'
sep = ',,'
def __init__(self, n=50, delete_num=-32768, v=1, sep=',,', average: int = 0):
self.N = n
self.speedLimit = v
self.deleteNumber = self.check_delete_num(delete_num)
self.sep = sep
self.fileData = ""
self.fileRef = ""
self.average = average
@staticmethod
def check_delete_num(delete_num) -> str:
if isinstance(delete_num, str):
return delete_num
return str(delete_num)
def get_delete_number(self) -> str:
return self.deleteNumber
def set_average_num(self, num):
self.average = int(float(num))
def set_speed_limit(self, speed_limit):
self.speedLimit = int(float(speed_limit))
def set_delete_num(self, delete_num):
self.deleteNumber = self.check_delete_num(delete_num)
def read_file(self, file: str, names: list) -> pd.DataFrame:
return pd.read_csv(file, sep=self.sep, engine="python", names=names)
def set_two_files(self, file_data: str, file_ref: str) -> bool:
if Validator.fileExist(file_ref) and Validator.fileExist(file_data):
self.fileData = file_data
self.fileRef = file_ref
return True
return False
def ini_average(self):
self.average_arr = {}
@staticmethod
def lineplot(arr, x_label="", y_label="", title=""):
import matplotlib.pyplot as plt
# Create the plot object
_, ax = plt.subplots()
df = pd.DataFrame(arr, columns=[ 'dist', 'depth', 'speed', 'angle'])
# Plot the best fit line, set the linewidth (lw), color and
# transparency (alpha) of the line
#ax.plot(x_data, y_data, lw=2, color='#539caf', alpha=1)
df.plot(x='dist', y=['depth', 'speed'], kind='area')
# Label the axes and provide a title
#ax.set_title(title)
#ax.set_xlabel(x_label)
#ax.set_ylabel(y_label)
plt.show()
@staticmethod
def get_key_round(key):
if isinstance(key, float):
return round(key)
if isinstance(key, str):
return int(float(key.strip()))
return int(key)
def add_to_average(self, key, u, v, w, db):
key = self.get_key_round(key)
if key not in self.average_arr.keys():
self.average_arr[key] = [[u, v, w, db]]
return;
self.average_arr[key].append([u, v, w, db])
def get_average(self, key):
key = self.get_key_round(key)
if key not in self.average_arr.keys():
return False
u = 0
v = 0
w = 0
db = 0
ln = len(self.average_arr[key])
for item in self.average_arr[key]:
u += float(item[0]) / ln
v += float(item[1]) / ln
w += float(item[2]) / ln
db += float(item[3]) / ln
return [u, v, w, db]
@staticmethod
def get_angle(u,v):
angle = 0
if v == 0.0 or u == 0.0:
print('Zero:', v, u)
return 0
if u > 0.0 and v > 0.0:
angle = math.atan(u / v) / 0.0175
elif u > 0.0 and v < 0.0:
angle = 90.0 + math.atan(abs(v) / u) / 0.0175
elif u < 0.0 and v < 0.0:
angle = 180.0 + math.atan(abs(u) / abs(v)) / 0.0175
elif u < 0.0 and v > 0.0:
angle = 270.0 + math.atan(v / abs(u)) / 0.0175
return angle
@staticmethod
def print_float_count(fl):
return float("{0:.3f}".format(fl)) if isinstance(fl, float) else "{}".format(fl)
@staticmethod
def print_to_file(i, ref_frame, u, v, w, db, f, print_depth=False):
depth = ref_frame.at[i, 'maxDepth']
if print_depth:
depth = print_depth
def print_float_count(fl):
return float("{0:.3f}".format(fl)) if isinstance(fl, float) else "{}".format(fl)
#ref_frame.at[i, 'id']
print( i,
ref_frame.at[i, 'latitude'],
ref_frame.at[i, 'longitude'],
ref_frame.at[i, 'distance'],
ref_frame.at[i, 'speed'],
depth, u, v, w, print_float_count(db),
file=f)
def get_real_vector(self, file='ret.txt'):
dat_frame = pd.read_csv(file, sep=' ', names=['id', 'lat', 'long', 'dist', 'speed', 'depth', 'u', 'v', 'w', 'db' ])
d = {}
angle = 0
arr = []
for i in range(dat_frame.count()[0]):
dist = dat_frame.at[i, 'dist']
speed = dat_frame.at[i, 'speed']
depth = dat_frame.at[i, 'depth']
u = float(dat_frame.at[i, 'u'])
v = float(dat_frame.at[i, 'v'])
w = float(dat_frame.at[i, 'w'])
db = float(dat_frame.at[i, 'db'])
angle = self.get_angle(u,v)
if dist not in d.keys():
d[dist] = {}
d[dist][depth] = [math.sqrt( u** 2 + v** 2), angle]
arr.append([ dist, -depth, math.sqrt( u** 2 + v** 2), angle])
for item in d.keys():
print('Distance:',self.print_float_count(item))
print('-----------')
for depth in d[item].keys():
print("{}: Real:[{}] | Angle:[{}]".format(self.print_float_count(depth), d[item][depth][0], d[item][depth][1]))
print()
self.lineplot( arr, "Distance", "Speed", "Real components")
#self.lineplot(dept.keys(), [d[x][0] for x in dept.keys()], "depth", "Speed", "Real components")
def from_two_files(self, file_data: str = '', file_ref: str = '', file_save='ret.txt'):
if file_data == '':
file_data = self.fileData
print('[Q] file_data is %s' % file_data)
if file_ref == '':
file_ref = self.fileRef
print('[Q] file_ref is %s' % file_ref)
if Validator.fileExist(file_ref) is False:
raise FileExistsError("Файл[REF] '%s' не найден" % file_ref)
if Validator.fileExist(file_data) is False:
raise FileExistsError("Файл[DATA] '%s' не найден" % file_data)
ref_frame = self.read_file(file_ref, ["id", "latitude", "longitude", "distance", "speed", "maxDepth", "depth"])
dat_frame = self.read_file(file_data, ['U', 'V', 'W', 'Db'])
print(self.speedLimit)
with open(file_save, 'w') as f:
self.ini_average()
#Для подсчета осреднения
count = 0
# Номер который будет записан в файле если есть осреднение
file_count = 0
for i in range(ref_frame.count()[0]):
# Компонента потока U
u = dat_frame.at[i, 'U'].split(',')
# Компонента потока V
v = dat_frame.at[i, 'V'].split(',')
# Компонента потока W
w = dat_frame.at[i, 'W'].split(',')
# Уровень сигнала
db = dat_frame.at[i, 'Db'].split(',')
# Разбиение по глубине
item = ref_frame.at[i, 'depth'].split(',')
# Фильтр по скорости лодки
speed = ref_frame.at[i, 'speed']
if Validator.ValidLen(self.N, [u, v, w, db]) is False:
print("Skip row at line {} [{} {} {} {} | N = {}]".format(
i, len(u), len(v), len(w), len(db), self.N))
continue
if Validator.ValidSpeed(speed, self.speedLimit) is False:
continue
# Для каждой ячейки глубины
for j in range(len(item)):
if Validator.InvalidNumber(self.get_delete_number(), [u[j], v[j], w[j], db[j]]):
continue
# Если задано усреднение то добавляем текущие значения компонентов потока U, V, W, DB
# Если не задано то записываем в файл сразу
if self.average:
#item[j] - глубина
self.add_to_average(item[j], u[j], v[j], w[j], db[j])
else:
self.print_to_file(i, ref_frame, u[j], v[j], w[j], db[j], f)
count += 1
if count == self.average and self.average:
#Осредненные компоненты
final_array = list([0, 0, 0, 0])
for j in range(len(item)):
final_array = self.get_average(item[j])
if final_array is False:
continue
self.print_to_file(file_count * self.average, ref_frame, final_array[0], final_array[1],
final_array[2], final_array[3], f, print_depth=item[j])
file_count += 1
count = 0
self.ini_average()
if count and self.average:
# Осредненные компоненты
final_array = list([0, 0, 0, 0])
for j in range(len(item)):
final_array = self.get_average(item[j])
if final_array is False:
continue
self.print_to_file(file_count * self.average, ref_frame, final_array[0], final_array[1],
final_array[2], final_array[3], f, print_depth=item[j])
self.get_real_vector()
return Validator.fileExist(file_save)
| true |
0db989cd754f1f7821dd1df86ae161d3d1a5d9b7 | Python | cp4011/Algorithms | /热题/312_戳气球.py | UTF-8 | 1,493 | 3.875 | 4 | [] | no_license | """有 n 个气球,编号为0 到 n-1,每个气球上都标有一个数字,这些数字存在数组 nums 中。
现在要求你戳破所有的气球。每当你戳破一个气球 i 时,你可以获得 nums[left] * nums[i] * nums[right] 个硬币。 这里的
left 和 right 代表和 i 相邻的两个气球的序号。注意当你戳破了气球 i 后,气球 left 和气球 right 就变成了相邻的气球。
求所能获得硬币的最大数量。
说明: 你可以假设 nums[-1] = nums[n] = 1,但注意它们不是真实存在的所以并不能被戳破。
0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
示例: 输入: [3,1,5,8]
输出: 167
解释: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
"""
class Solution:
def maxCoins(self, nums):
if not nums:
return 0
nums = [1] + nums + [1] # 设置哨兵
l = len(nums)
dp = [[0] * l for _ in range(l)] # dp[i][j]表示戳破 [i+1...j-1] 号气球的最大收益,保留i,j,因为哨兵的气球不能被戳破,
for j in range(2, l): # j从2开始
for i in range(j - 2, -1, -1): # 从i到j
for k in range(i + 1, j): # 戳破k位置上的气球
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j])
return dp[0][-1]
print(Solution().maxCoins([3, 1, 5, 8]))
| true |
a24ea0cdb072528fc566723aeb51f9da2f4762a3 | Python | JoinNova/practice_py | /18nov06_pandas02.py | UTF-8 | 82 | 2.734375 | 3 | [] | no_license | import pandas as pd
import numpy as np
s=pd.Series([1,3,5,np.nan,6,8])
print(s)
| true |
e046c8b8ee8260e1ba57bff711bdd4866ab86de5 | Python | MaureenZOU/i-CPCL-Algorithm | /CPCL.py | UTF-8 | 11,248 | 2.859375 | 3 | [] | no_license | import numpy as np
from random import shuffle
import matplotlib.pyplot as plt
import sys
import csv
import json
import pandas
import time
import copy
################################################
##Original CPCL with cluster adjustment#########
################################################
## the class is about data point, point is the x, y location of the data point
class data:
def __init__(self, point):
##point: numpy.array
self.point = point
def __repr__(self):
return str(self.point)
## the class is about the seed point, which capture the information of previous location of the point, current location
## of the point, and distance between current seed and win seed
class seed:
def __init__(self, prePoint, curPoint, seedWinNum, seedWinD, positionNum):
self.prePoint = prePoint ##numpy.array
self.curPoint = curPoint ##numpy.array
self.seedWinNum = seedWinNum ##integer
self.seedWinD = seedWinD ##float, distance between current seed and win seed
self.positionNum = positionNum
def setCurPoint(self, point):
self.prePoint = self.curPoint
self.curPoint = point
def setSeedWinD(self, value):
self.seedWinD = value
def setSeedDataD(self, value):
self.seedDataD = value
def updateSeedWinNum(self):
self.seedWinNum = self.seedWinNum + 1
def setPositionNum(self, value):
self.positionNum = value
def __repr__(self):
return str(self.prePoint) + " " + str(self.curPoint) + " " + str(self.seedWinNum) + " " + str(self.seedWinD)
def generateData(clusterNum):
fileName = "./data/CPCL_sudoData_Cluster" + str(clusterNum) + "_sigma"+str(sigma)+"_"+str(count)+".csv"
#fileName = "./data/s1_data.csv"
dataSet = readData(fileName)
output = []
x = []
y = []
for i in range(0, len(dataSet)):
plt.plot(dataSet[i][0], dataSet[i][1], 'k,')
x.append(dataSet[i][0])
y.append(dataSet[i][1])
output.append(data(dataSet[i]))
d = ((max(x)-min(x))**(2)+(max(y)-min(y))**(2))**(.5)
return output, d
def generateSeed(clusterNum):
fileName = './seed/seed_' +str(clusterNum)+ "_"+str(seedNum)+ "_sigma"+str(sigma)+"_"+str(seedCount)+".csv"
#fileName = './seed/'+str(seedNum)+'_s1_seed.csv'
seeds = readData(fileName)
output = []
for i in range(0, len(seeds)):
obj = seed(np.array([0, 0]), np.array(seeds[i]), 1, 0, i)
output.append(obj)
return output
# def generateSeed(n, dataSet):
# maxX = -10000000
# maxY = -10000000
# minX = sys.maxsize
# minY = sys.maxsize
# for data in dataSet:
# if data.point[0] >= maxX:
# maxX = data.point[0]
# elif data.point[0] < minX:
# minX = data.point[0]
# if data.point[1] >= maxY:
# maxY = data.point[1]
# elif data.point[1] < minY:
# minY = data.point[1]
# seedX = np.random.random(n) * (maxX - minX) + minX
# seedY = np.random.random(n) * (maxY - minY) + minY
# output = []
# for i in range(0, len(seedX)):
# obj = seed(np.array([0, 0]), np.array([seedX[i], seedY[i]]), 1, 0, i)
# output.append(obj)
# return output
def winSeed(inputData, seedPoints):
distanceVector = []
for i in range(len(seedPoints)):
distanceVector.append(seedPoints[i].curPoint - inputData)
distanceValue = []
sumSeedWinNum = 0
for data in seedPoints:
sumSeedWinNum = sumSeedWinNum + data.seedWinNum
for i in range(len(distanceVector)):
Gama = seedPoints[i].seedWinNum / sumSeedWinNum
value = (distanceVector[i][0] * distanceVector[i][0] + distanceVector[i][1] * distanceVector[i][
1]) * Gama
distanceValue.append(value)
min = sys.maxsize
loc = 0
for i in range(len(distanceValue)):
if distanceValue[i] < min:
min = distanceValue[i]
loc = i
return loc
def updateCooperative(McObject, MuObject, XtObject, T):
Mc = McObject.curPoint
Mu = MuObject.curPoint
Xt = XtObject.point
VMcXt = Mc - Xt
VMuXt = Mu - Xt
DMcXt = (VMcXt[0] ** (2) + VMcXt[1] ** (2)) ** (0.5)
DMuXt = (VMuXt[0] ** (2) + VMuXt[1] ** (2)) ** (0.5)
row = DMcXt / max(DMcXt, DMuXt)
locVector = MuObject.curPoint + (0.0016) * row * (XtObject.point - MuObject.curPoint)
MuObject.setCurPoint(locVector)
def updatePenalize(McObject, MpObject, XtObject, T):
Mc = McObject.curPoint
Mp = MpObject.curPoint
Xt = XtObject.point
VMcXt = Mc - Xt
VMpXt = Mp - Xt
DMcXt = (VMcXt[0] ** (2) + VMcXt[1] ** (2)) ** (0.5)
DMpXt = (VMpXt[0] ** (2) + VMpXt[1] ** (2)) ** (0.5)
locVector = MpObject.curPoint - (0.0016) * (DMcXt / DMpXt) * (XtObject.point - MpObject.curPoint)
MpObject.setCurPoint(locVector)
def calError(seedPoints):
E = 0
for data in seedPoints:
dis = data.curPoint - data.prePoint
E = E + (dis[0] ** (2) + dis[1] ** (2)) ** (0.5)
return E
def readData(fileName):
dataframe = pandas.read_csv(fileName,
engine='python', header=None)
dataset = dataframe.values
dataSet = dataset.astype('float32')
return dataSet
def writeFile(writeMatrix, fileName):
with open(fileName, 'w') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in writeMatrix:
spamwriter.writerow(row)
def Algorithm(clusterNum, seedNum, seedList, epoch, RMSE, realEpoch):
dataSet, d = generateData(clusterNum) ##cluster points
seedPoints = generateSeed(clusterNum)
e = 0.0001 ##standard error rate
Tmax = 10000 ##max iteration
T = 1 ##actual iteration
E = sys.maxsize ##actual error
w, h = len(seedPoints), len(seedPoints)
edgeMatrix = [[0 for x in range(w)] for y in range(h)]
oldEdgeMatrix = [[0 for x in range(w)] for y in range(h)]
edgeMatrix = np.array(edgeMatrix)
color = "mx"
start = time.time()
for k in range(0, realEpoch):
print("epoch: "+str(k))
for i in range(0, len(dataSet)):
winLoc = winSeed(dataSet[i].point, seedPoints)
for j in range(0, len(seedPoints)):
vectorWin = seedPoints[winLoc].curPoint - seedPoints[
j].curPoint ## the vector between win point and seed points j
valueWin = (vectorWin[0] * vectorWin[0] + vectorWin[1] * vectorWin[1]) ** (.5)
seedPoints[j].setSeedWinD(valueWin)
WinSeedData = seedPoints[winLoc].curPoint - dataSet[i].point
WinSeedDataDistance = (WinSeedData[0] * WinSeedData[0] + WinSeedData[1] * WinSeedData[1]) ** (.5)
Sc = [] ##all the data that falls in the territory region
for data in seedPoints:
if data.seedWinD != 0 and data.seedWinD < WinSeedDataDistance:
Sc.append(data)
Sc = sorted(Sc, key=lambda Data: Data.seedWinD)
Q = len(Sc)
lRate = 0.005
Qu = int(Q * min(1, lRate * seedPoints[winLoc].seedWinNum))
Su = [] ##cooperation data points
Sp = [] ##penalized data points
Su = Sc[0:Qu]
Sp = Sc[Qu:]
for data in Su:
updateCooperative(seedPoints[winLoc], data, dataSet[i], T)
edgeMatrix[winLoc][data.positionNum] = edgeMatrix[winLoc][data.positionNum] + 1
for data in Sp:
updatePenalize(seedPoints[winLoc], data, dataSet[i], T)
edgeMatrix[winLoc][data.positionNum] = edgeMatrix[winLoc][data.positionNum] - 1
locVector = seedPoints[winLoc].curPoint + 0.001 * (
dataSet[i].point - seedPoints[winLoc].curPoint) ##location vector of new win seed point
seedPoints[winLoc].setCurPoint(locVector)
seedPoints[winLoc].updateSeedWinNum()
E = calError(seedPoints)
T = T + 1
for i in range(0, len(seedPoints)):
seedList[i][0].append(seedPoints[i].curPoint[0])
seedList[i][1].append(seedPoints[i].curPoint[1])
rmse = 0
for i, seed in enumerate(seedPoints):
rmse = rmse + ((seed.curPoint[0] - seed.prePoint[0])**(2) + (seed.curPoint[0] - seed.prePoint[0])**(2))**(0.5)
RMSE.append([k,rmse/(len(seedPoints)*d)])
CMSE.append([time.time()-start,rmse/(len(seedPoints)*d)])
end = time.time()
print("Execution Time: "+str(end-start)+" secs")
return seedList, dataSet, seedPoints, d
def appendFile(line, fileName):
with open(fileName, "a") as myfile:
myfile.write(line)
# clusterNum = int(sys.argv[1])
# seedPointNum = int(sys.argv[2])
# epoch = int(sys.argv[3])
clusterNum = 3
seedNum = int(sys.argv[1])
epoch = int(sys.argv[2])
sigma = 2
count = 1
seedCount = 1
RMSE = []
CMSE = []
realEpoch = epoch
seedList = [[[],[]] for i in range(0, seedNum)] #store the movement of each seed point
seedList, dataSet, seedPoints, d = Algorithm(clusterNum, seedNum, seedList, epoch, RMSE, realEpoch)
fileName = "./centroid/CPCL_centroid_Cluster" + str(clusterNum) + "_sigma"+str(sigma)+"_"+str(count)+".csv"
#fileName = "./centroid/s1_center.csv"
centerData = readData(fileName)
distance = 0
for seed in seedPoints:
plt.plot(seed.curPoint[0], seed.curPoint[1], 'r*')
minDistance = sys.maxsize
for cen in centerData:
curDistance = np.linalg.norm(cen-np.array([seed.curPoint[0], seed.curPoint[1]]))
if curDistance < minDistance:
minDistance = curDistance
distance = distance + minDistance
copySeed = copy.copy(seedPoints)
for seed in seedPoints:
count = 0
for i, copy in enumerate(copySeed):
if np.linalg.norm(seed.curPoint - copy.curPoint) > 0.1 and np.linalg.norm(seed.curPoint - copy.curPoint) < 4000:
copySeed.pop(i-count)
count = count + 1
print(len(copySeed))
print(distance/(len(seedPoints)*d))
fileName = "./animation/CPCL_Animation_" +str(clusterNum)+ "_"+str(seedNum)+"_sigma"+str(sigma)+"_"+str(count)+"_"+str(seedCount)+".csv"
#fileName = "./animation/CPCL_Animation_s1.csv"
seedList = np.array(seedList)
seedList = np.reshape(seedList, (seedNum, realEpoch*2))
writeFile(np.array(seedList), fileName)
fileName = "./rmse/CPCL_RMSE_" +str(clusterNum)+ "_"+str(seedNum)+"_sigma"+str(sigma)+"_"+str(count)+"_"+str(seedCount)+".csv"
#fileName = "./epoch/CPCL_RMSE_s1_"+str(seedNum)+".csv"
writeFile(RMSE, fileName)
#fileName = "./cpu/CPCL_RMSE_s1_"+str(seedNum)+".csv"
#writeFile(CMSE, fileName)
line = "CPCL_RMSE_s1_"+str(seedNum)+": "+ str(distance/(len(seedPoints)*d))+"\n"
fileName = "result.log"
#appendFile(line, fileName)
plt.show()
| true |
62aec298587da3bae69c62537dd01a06d64c851d | Python | little-forests/pandas | /时间序列(datetimeIndex+periodIndex).py | UTF-8 | 908 | 2.890625 | 3 | [] | no_license | import pandas as pd
import numpy as np
from datetime import datetime
path_in = r"C:\Users\x\Desktop\filtered.csv"
path_out = r"C:\Users\x\Desktop\filtered_x.csv"
df = pd.read_csv(path_in, engine='python',encoding='utf_8_sig')
#将“订单创建时间”字段的str转换成datetime
df_date = df['订单创建时间'].map(lambda x:datetime.strptime(str(x[:19]),"%Y-%m-%d %H:%M:%S"))
df.insert(1,'订单日期',df_date)
df.set_index('订单日期',inplace=True)
#更改切片内容以及频率
#dfs = df.to_period('Y')再进行透视,是按照年份求和及平均值
#dfs = df.to_period('M')再进行透视,是按照年月份求和及平均值
# dfs = df['2017':'2018'].to_period('M')
dfs = df['2016'].to_period('M')
pivot = pd.pivot_table(dfs,index=['订单日期'],values=['买家实际支付金额'],aggfunc=[np.sum,np.mean])
print(pivot)
# dfs.to_csv(path_out,index=False,encoding='utf_8_sig')
| true |
c2f5c143392cda778e729adf1396c64502f26725 | Python | esnguyenvan/DEP | /MapVarClass.py | UTF-8 | 3,206 | 2.59375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 16 15:25:07 2018
@author: e.nguyen-van
"""
import numpy as np
import math
import sys
class MapVar:
Names={'Vel':'Velocity', 'Beta':'Side Slipe angle', 'Gamma':'Climb angle', 'Omega':'Turn rate'}
Units={'Vel':'m/s','Beta':'\xb0','Gamma':'\xb0','Omega':'\xb0/s'}
fixposition={'Vel':0, 'Beta':1, 'Gamma':2, 'Omega':3}
DimUnits="rad"
def __init__(self,Var1,Var2,Min1,Max1,Step1,Min2,Max2,Step2):
self.FirstVar=Var1
self.SecondVar=Var2
self.Min1=Min1
self.Max1=Max1
self.Step1=Step1
self.Min2=Min2
self.Max2=Max2
self.Step2=Step2
self.FirstDim = np.arange(Min1,Max1,Step1)
self.SecondDim = np.arange(Min2,Max2,Step2)
#default behaviour transform to rad
if Var1 == "Beta" or Var1 == "Gamma":
self.FirstDim=self.FirstDim/180*math.pi
if Var2 == "Beta" or Var2 == "Gamma":
self.SecondDim=self.SecondDim/180*math.pi
def ReArrangefix(self,i,j, Vel,Beta,gamma,omega):
fix=np.array([Vel,Beta,gamma,omega])
fix[self.fixposition[self.FirstVar]]=self.FirstDim[i]
fix[self.fixposition[self.SecondVar]]=self.SecondDim[j]
return fix
def getUnit(self,a):
if a=='x':
return self.Units[self.FirstVar]
elif a=='y':
return self.Units[self.SecondVar]
else:
sys.exit("Error, only 'x' or 'y' entry correct for units")
def getXlocator(self):
delta=abs(self.Step1/2)
Locators=np.copy(self.FirstDim[0:-1])
if self.FirstVar=="Beta" or self.FirstVar=="Gamma":
if self.DimUnits=="rad":
Locators=Locators/math.pi*180
return Locators+delta
def getYlocator(self):
delta=abs(self.Step2/2)
Locators=np.copy(self.SecondDim[0:-1])
if self.SecondVar=="Beta" or self.SecondVar=="Gamma":
if self.DimUnits=="rad":
Locators=Locators/math.pi*180
return Locators+delta
def getName(self,a):
if a=='x':
return self.Names[self.FirstVar]
elif a=='y':
return self.Names[self.SecondVar]
else:
sys.exit("Error, only 'x' or 'y' entry correct for variable name")
def Dim2rad(self):
if self.FirstVar == "Beta" or self.FirstVar == "Gamma" or self.FirstVar == "Omega":
self.FirstDim=self.FirstDim/180*math.pi
if self.SecondVar == "Beta" or self.SecondVar == "Gamma" or self.SecondVar == "Omega":
self.SecondDim=self.SecondDim/180*math.pi
self.DimUnits="rad"
def Dim2deg(self):
if self.FirstVar == "Beta" or self.FirstVar == "Gamma" or self.FirstVar == "Omega":
self.FirstDim=self.FirstDim/math.pi*180
if self.SecondVar == "Beta" or self.SecondVar == "Gamma" or self.SecondVar == "Omega":
self.SecondDim=self.SecondDim/math.pi*180
self.DimUnits="deg" | true |
7b36a88eeecfd062f98992477a5a9d4a0d511687 | Python | acomeaux93/Dewitt-Data-Dashboard | /credit_piechart_app.py | UTF-8 | 5,769 | 2.640625 | 3 | [] | no_license | #THIS IS THE CREDIT ACCUMULATION PIE CHART
### Data
import pandas as pd
import pickle
### Graphing
import plotly.graph_objects as go
### Dash
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Output, Input
## Navbar
from navbar import Navbar
#imports from MY program
import os
import dash_table
from six.moves.urllib.parse import quote
from plotly.subplots import make_subplots
# from jupyterlab_dash import AppViewer
# viewer = AppViewer()
#Build App
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
#df = pd.read_csv('/Users/teacher/Desktop/DeWitt Data/creditsattemptedvsearnedpiechart.csv')
clinton_url='https://raw.githubusercontent.com/angelojc/dewittclinton/master/creditsattemptedvsearnedpiechart.csv'
df = pd.read_csv(clinton_url,sep=",")
df[' Count'] = range(1, len(df) + 1)
mid2020_differential = pd.Series(['float64'])
for i in range(len(df)):
if df['Off Class 3'][i] == 'Y':
mid2020_differential[i] = df['Earned'][i] - 5.5
elif df['Off Class 3'][i] == 'X':
mid2020_differential[i] = df['Earned'][i] - 16.5
elif df['Off Class 3'][i] == 'W':
mid2020_differential[i] = df['Earned'][i] - 27.5
elif df['Off Class 3'][i] == 'V':
mid2020_differential[i] = df['Earned'][i] - 33.5
else:
mid2020_differential[i] = df['Earned'][i] - 33.5
df.insert(15,"Mid2020 Differential", mid2020_differential)
df['Mid2020 Differential']=df['Mid2020 Differential'].astype(float)
df = df.round({'Mid2020 Differential': 3})
education_list = ['All Students','General Education', 'Special Education/504', 'ENL/ESL']
education_codes = [['1', '2', '3', '4', 'S', 'L', 'T', 'E', 'B',],['1', '2', '3', '4'],['S', 'L', 'T','E'],['B']]
#education_codes = [[1, 2, 3, 4],['S', 'L', 'T','E'],['B']]
nav = Navbar()
server = app.server
#App Layout
def CreditPieChart():
layout = html.Div([
nav,
html.Div([ html.Br()]),
html.Div([
html.H1(children='Student Credit Data: On-track Credit Accumulation Breakdown')
], style={'display':'block', 'margin-left':'auto', 'margin-right':'auto','width':'95%', 'border':'3px solid crimson', 'padding': '10px', 'backgroundColor': 'white'}),
html.Div([ html.Br()]),
html.Div([
html.H5(children='Description:'),
dcc.Markdown('''
* This dashboard shows the percentages and count of students in each cohort that are on or off track in terms of credit accumulation
* The drop down menu can be used to look at subsets of student populations: General Education, Special Education, and ENL/ESL
* Users can view the percentage and category totals by hovering over the graph sections
* __This tool could be used to identify target students per cohort that are off track in terms of credit accumulation__
'''),
],style={'display':'block', 'margin-left':'auto', 'margin-right':'auto','width':'95%', 'border':'3px solid black', 'padding': '10px', 'backgroundColor': 'white'}
),
html.Div([ html.Br()]),
html.Div([
html.H5(children='Select student data set/subset'),
dcc.Dropdown(
id='education',
options=[{'label': education_list[i], 'value': i} for i in range(len(education_list))],
value= 0
),
dcc.Graph(id='pie')
], style={'display':'block', 'margin-left':'auto', 'margin-right':'auto','width':'95%', 'border':'3px solid black', 'padding': '10px', 'backgroundColor': 'white'}
)
], style={'backgroundColor':'whitesmoke'})
return layout
def update_credit_pie_graph(education):
sub_df = df
education_values = []
education_items = education_codes[education]
for item in education_items:
education_values.append(item)
print (education_values)
education_conditions = df['Off Class 2'].isin(education_values)
labels = ['On Track', 'Ahead of Track (5+ extra credits)', 'Off Track (0 - 5 credits behind)','Severely Off Track (more than 5 credits behind)']
colors = ['green', 'blue', 'orange', 'red']
fig = make_subplots(rows=1, cols=4, specs=[[{'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}]])
cohorts = ['Y', 'X', 'W', 'V']
for i in range(len(cohorts)):
filter_df = sub_df[education_conditions]
cohort_df = filter_df[(filter_df['Off Class 3'] == cohorts[i])]
categories = [0, 0 ,0, 0]
categories[0] = len(cohort_df[(cohort_df['Mid2020 Differential'] >= 0) & (cohort_df['Mid2020 Differential'] <5)])
categories[1] = len(cohort_df[(cohort_df['Mid2020 Differential'] >= 5)])
categories[2] = len(cohort_df[(cohort_df['Mid2020 Differential'] < 0) & (cohort_df['Mid2020 Differential'] >-5)])
categories[3] = len(cohort_df[(cohort_df['Mid2020 Differential'] < -5)])
fig.add_trace(go.Pie(labels=labels, values=categories, name="testing"), 1, i + 1)
fig.update_traces(hole=.4, marker=dict(colors=colors))
fig.update_layout(
title_text="Credit On-track percentage by cohort",
# Add annotations in the center of the donut pies.
annotations=[dict(text='Y cohort', x=0.08, y=0.5, font_size=12, showarrow=False),
dict(text='X cohort', x=0.37, y=0.5, font_size=12, showarrow=False),
dict(text='W cohort', x=0.63, y=0.5, font_size=12, showarrow=False),
dict(text='V cohort', x=0.92, y=0.5, font_size=12, showarrow=False)])
return fig
#viewer.show(app)
| true |
072c4cefbe815985220897d2c835279eab681b1b | Python | QkqBeer/PythonSubject | /面试练习/686.py | UTF-8 | 559 | 3.125 | 3 | [] | no_license | __author__ = "那位先生Beer"
import copy
def repeatedStringMatch( self, A, B ):
"""
:type A: str
:type B: str
:rtype: int
"""
if set( A ) < set( B ):
return -1
if len( A ) > len( B ):
if A.count( B ) >= 1:
return 1
else:
return 2 if (A * 2).count( B ) >= 1 else -1
count = 1
cp = copy( A )
while B not in A:
A += cp
count += 1
if len( A ) >= 3 * len( B ):
return -1
return count
print(repeatedStringMatch("abcd", "cdabcdab")) | true |
5bdc24c43325166f2aba6df35f1cb68df576cea8 | Python | mfreer/eufar-egads | /egads/egads/algorithms/thermodynamics/temp_potential_cnrm.py | UTF-8 | 2,413 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | __author__ = "mfreer"
__date__ = "$Date:: $"
__version__ = "$Revision:: $"
__all__ = ["TempPotentialCnrm"]
import egads.core.egads_core as egads_core
import egads.core.metadata as egads_metadata
class TempPotentialCnrm(egads_core.EgadsAlgorithm):
"""
FILE temp_potential_cnrm.py
VERSION $Revision$
CATEGORY Thermodynamics
PURPOSE Calculates potential temperature
DESCRIPTION Calculates potential temperature given static temperature, pressure,
and the ratio of gas constant and specific heat of air.
INPUT T_s vector K or C static temperature
P_s vector hPa static pressure
Racpa coeff. gas constant of air divided by
specific heat of air at constant pressure
OUTPUT theta vector same as T_s potential temperature
SOURCE CNRM/GMEI/TRAMM
REFERENCES Triplet-Roche.
"""
def __init__(self, return_Egads=True):
egads_core.EgadsAlgorithm.__init__(self, return_Egads)
self.output_metadata = egads_metadata.VariableMetadata({'units':'K',
'long_name':'potential temperature',
'standard_name':'air_potential_temperature',
'Category':['Thermodynamic', 'Atmos State']})
self.metadata = egads_metadata.AlgorithmMetadata({'Inputs':['T_s', 'P_s', 'Racpa'],
'InputUnits':['K', 'hPa', ''],
'Outputs':['theta'],
'Processor':self.name,
'ProcessorDate':__date__,
'ProcessorVersion':__version__,
'DateProcessed':self.now()},
self.output_metadata)
def run(self, T_s, P_s, Racpa):
return egads_core.EgadsAlgorithm.run(self, T_s, P_s, Racpa)
def _algorithm(self, T_s, P_s, Racpa):
theta = T_s * (1000.0 / P_s) ** (Racpa)
return theta
| true |
e8954a7e7d7ffce434a3d490bbee4818b79af099 | Python | arce/DiokolCluster | /clients/Python/Example_03_04.py | UTF-8 | 661 | 3.5625 | 4 | [] | no_license | import p5d
# Learning Processing
# Daniel Shiffman
# http://www.learningprocessing.com
# Example 3-4: Drawing a continuous line
def setup():
global x1,x2,y1,y2
pg.size(480, 270)
pg.background(255)
x1 = pg.number(0)
y1 = pg.number(0)
x2 = pg.number(0)
y2 = pg.number(0)
def draw():
global x1,x2,y1,y2
pg.stroke(0)
# Draw a line from previous mouse location to current mouse location.
pg.line(x1, y1, x2, y2)
def mouseMoved():
global x1,x2,y1,y2
pg.set(x1,pg.pmouseX)
pg.set(y1,pg.pmouseY)
pg.set(x2,pg.mouseX)
pg.set(y2,pg.mouseY)
pg = p5d.PGraphics()
pg.setupFunc(setup)
pg.drawFunc(draw)
pg.mouseMovedFunc(mouseMoved)
pg.listen() | true |
7fa5e84a17f25d3f746eae451f9a0ff3597e0cea | Python | suryak24/python-code | /42.py | UTF-8 | 123 | 3.609375 | 4 | [] | no_license | str1=input("String1:")
str2=input("String2:")
if str1>str2:
print(str1)
elif str1==str2:
print(str2)
else:
print(str2)
| true |
5e0ee147fc4c84c581653478add8dfd44e7b2b90 | Python | irenium/irenium.github.io | /insight/bsdown.py | UTF-8 | 3,456 | 2.84375 | 3 | [] | no_license | #!/usr/bin/python
"""Use pandoc to convert markdown to html, and then embed in a bootstrap
html template."""
import argparse
import subprocess
import tempfile
from bs4 import BeautifulSoup
BOOTSTRAP_HEADER = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head
content must come *after* these tags -->
<title>Going the Distance</title>
<!-- Bootstrap -->
<!-- link href="css/bootstrap.min.css" rel="stylesheet" -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous">
<style type="text/css">
div.content {
float: none;
max-width: 700px;
}
.center {
margin: 0 auto;
}
.content img {
max-width: 100%;
}
body {
font-size: 15px;
}
h1, h2 {
color:#37B5EF;
}
</style>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="jumbotron" style="background-color: #c9daf8; padding-bottom:0;">
<img class="center" style="display: block; max-width: 1000px;" src="runner_trace4.png" width="70%"/>
</div>
<div class="content center">
"""
BOOTSTRAP_FOOTER = """
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<!-- script src="js/bootstrap.min.js"></script -->
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
</body>
</html>
"""
def make_page(input_path, output_path):
tmp = tempfile.NamedTemporaryFile(delete=False)
subprocess.check_call(['pandoc', '--from=markdown_github',
'--to=html5', input_path], stdout=tmp)
tmp.close()
with open(tmp.name, 'r') as infile:
soup = BeautifulSoup(infile.read(), 'lxml')
with open(output_path, 'w') as outfile:
outfile.write(BOOTSTRAP_HEADER)
for x in soup.body.contents:
outfile.write(str(x))
outfile.write(BOOTSTRAP_FOOTER)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('input_path', help='Path to the markdown input file')
parser.add_argument('output_path', help='Path to the output html file')
args = parser.parse_args()
make_page(args.input_path, args.output_path)
if __name__ == '__main__':
main()
| true |
bedb87b18a03e142ae6c526ebe7f93a10929a451 | Python | BartMassey/nb-misc | /queuetest.py | UTF-8 | 1,324 | 3.40625 | 3 | [
"MIT"
] | permissive | # Queue tests.
# Copyright © 2014 Bart Massey
# [This program is licensed under the "MIT License"]
# Please see the file COPYING in the source
# distribution of this software for license terms.
from random import randrange
# Array-based circular queue tests.
def arrayqueuetest(constructor):
print("base test")
q = constructor(3)
assert q.is_empty()
assert not q.is_full()
q.enqueue(1)
assert not q.is_empty()
assert not q.is_full()
q.enqueue(2)
assert not q.is_empty()
assert not q.is_full()
q.enqueue(3)
assert not q.is_empty()
assert q.is_full()
assert q.dequeue() == 1
assert q.dequeue() == 2
q.enqueue(4)
assert q.dequeue() == 3
assert q.dequeue() == 4
assert q.is_empty()
def test():
q = constructor(100)
v = 1
w = 1
for _ in range(randrange(100) + 1):
q.enqueue(v)
v += 1
while True:
if randrange(2) == 1:
if q.is_full():
break
q.enqueue(v)
v += 1
else:
if q.is_empty():
break
assert q.dequeue() == w
w += 1
print("random tests")
for _ in range(100):
test()
print(".", end="")
print()
| true |
f11c6f7aba27fce8989a90d41635b9cecac54049 | Python | a2zazure/mypythoncodes | /collection/collection_list.py | UTF-8 | 1,082 | 3.953125 | 4 | [] | no_license | #python collection (Arrays)
'''
there are 4 types of collection in Python.
1. list [use same value also in a list]
2. Tupel [same as list.but cant change the value in Tuple]
3. set [unorder and unindex and no same value, well defined object]
4. Dictionary [with key value pair]
'''
l1 = [2,4,65,7,4] #[] is use for list
print ('print my first list is:', l1)
#indexing in Python
print ('print my first number in that list is :', l1[0]) #count starts with 0
print ('print my 4th number in that list is :', l1[3]) #count starts with 0
#add aliment in the list
l1.append(524)
print ('print my changed first list is:', l1)
#change value
l1[5]= 65
#remove aliment in the list
l1.pop(1) #here value is reffer to INDEX number
print ('print my changed first list is:', l1)
l1.remove(4) #here value is list VALUE. search and delete.
print ('print my changed first list is:', l1)
#clear list
l1.clear()
print ('print my changed first list is:', l1)
#list can hold int string and flout or list
l2=[2,'test',[2,4,5]]
print('print list2', l2)
print('print index2 from inside list2', l2[2][2]) | true |
e084f2179b2f0c2442021e8c46167b48fa885fc7 | Python | ansmtz/caesar-cipher | /main.py | UTF-8 | 1,499 | 3.53125 | 4 | [] | no_license | from alphabets import alphabets_dict
def main():
is_process_stopped = False
while not is_process_stopped:
lang = input("Type your language to work with (ru, en): ").strip().lower()
action = input("Do you want to decode or encode your message? (decode/encode) ").lower()
user_text = input("Type anything you want: ").lower()
shifted_value = int(input("Type value for shifting: "))
chosen_lang = alphabets_dict[lang]
shifted_value = preserve_oversize(shifted_value, chosen_lang)
print(caesar_in_action(action, user_text, shifted_value, chosen_lang))
is_continue = input('Type "n" if you want to exit the program: ').lower()
if is_continue == "n":
is_process_stopped = True
def caesar_in_action(action, user_text, shifted_value, chosen_lang):
if action == "decode":
shifted_value *= -1
result = ''
for char in user_text:
if char in chosen_lang:
shifted_index = chosen_lang.index(char) + shifted_value
if shifted_index >= len(chosen_lang):
result += chosen_lang[shifted_index - len(chosen_lang)]
else:
result += chosen_lang[shifted_index]
else:
result += char
return result
def preserve_oversize(shifted_value, chosen_lang):
# предотвращаем большое переполнение
shifted_value = shifted_value % len(chosen_lang)
return shifted_value
main()
| true |
ce8d21bdbd1eb3c81ab1fa21571026dfe04d2422 | Python | turovod/Otus | /3_API_тысты/0_argparse/1_sys_args_method.py | UTF-8 | 134 | 2.734375 | 3 | [
"MIT"
] | permissive | import sys
print(sys.argv)
args = sys.argv
def calculate(num1, num2):
return num1 + num2
print(calculate(args[1], args[2]))
| true |
2eaf43df031fc31d1da55cfa817b95148be84f82 | Python | filipematos95/Data-Mining-Class | /daan/score.py | UTF-8 | 2,548 | 2.859375 | 3 | [] | no_license | #########################################
# #
# Group 24 #
# (2018) #
# Vrije Universiteit #
# LambdaMART score #
# #
#########################################
import pyltr
import matplotlib.pyplot as plt
import pandas as pd
import sys
import math
import copy
import re
import numpy as np
"""
scoring of a LabmdaMart model
"""
################################### scoring functions #########################################
#### version 1
def compute(r):
#k = min(len(r),5)
k = len(r)
return ndcg_at_k(r,k)
def dcg_at_k(r,k):
r = np.asfarray(r)[:k]
if r.size:
return np.sum(np.subtract(np.power(2, r), 1) / np.log2(np.arange(2, r.size + 2)))
return 0.
def ndcg_at_k(r, k):
idcg = dcg_at_k(sorted(r, reverse=True), k)
if not idcg:
return 0.
return dcg_at_k(r, k) / idcg
#### version 2
def get_max_ndcg(k, *ins):
'''This is a function to get maxium value of DCG@k. That is the DCG@k of sorted ground truth list. '''
#print ins
l = [i for i in ins]
l = copy.copy(l[0])
l.sort(None,None,True)
#print l
max = 0.0
for i in range(k):
#print l[i]/math.log(i+2,2)
max += (math.pow(2, l[i])-1)/math.log(i+2,2)
#max += l[i]/math.log(i+2,2)
return max
def get_ndcg(s, k):
'''This is a function to get ndcg '''
z = get_max_ndcg(k, s)
dcg = 0.0
for i in range(k):
#print s[i]/math.log(i+2,2)
dcg += (math.pow(2, s[i])-1)/math.log(i+2,2)
#dcg += s[i]/math.log(i+2,2)
if z ==0:
z = 1;
ndcg = dcg/z
#print "Line:%s, NDCG@%d is %f with DCG = %f, z = %f"%(s, k, ndcg,dcg, z)
return ndcg
# function that returns in two ways the computed ndcg score
def scores(Epred, Eqids, Ey):
X = pd.DataFrame([Epred, Eqids])
X = X.T
X. columns = ['prob', 'srch_id']
X['points'] = Ey
X_sort = X.sort_values(['srch_id', 'prob'],ascending=[True, False])
# score 1
X_sort['score'] = X_sort.groupby('srch_id').apply(lambda x: compute(x.points.values))
print('score 1 = ', X_sort[['score']].dropna().mean())
# score2
X_sort['score2'] = X_sort.groupby('srch_id').apply(lambda x: get_ndcg(list(x.points.values),len(x)))
print('score 2 = ', X_sort[['score2']].dropna().mean())
return pd.DataFrame([X_sort['score'].dropna(),X_sort['score2'].dropna()]).T
| true |
60c436598215b391512b4a69899aa070faadd6b2 | Python | ugapanyuk/metagraph_mongo | /metagraph/processor.py | UTF-8 | 1,788 | 3 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
from mongoengine import *
from asq.initiators import *
from metagraph.configuration import *
from metagraph.datamodel import *
class MetagraphModelProcessor:
"""
Класс для обработки метаграфовой модели
"""
metagraphModelConfig = None
db = None
def __init__(self , metagraph_model_config_param):
"""
Конструктор класса
:type metagraph_model_config_param: MetagraphModelConfig
"""
self.metagraphModelConfig = metagraph_model_config_param
self.db = connect(self.metagraphModelConfig.db_name)
def create_vertex(self, vertex_name: str) -> Vertex:
"""
Добавление вершины
"""
v = Vertex(name=vertex_name)
v.save()
return v
def create_edge(self, edge_name: str, src: Vertex, dest: Vertex) -> Edge:
"""
Добавление связи
"""
e = Edge(name=edge_name)
e.s = src
e.d = dest
e.save()
return e
def drop_db(self):
try:
self.db.drop_database(self.metagraphModelConfig.db_name)
except Exception:
pass
def vertices_by_name(self, name_param: str):
"""
Список всех вершин с заданным именем
"""
vs = Vertex.objects(name=name_param).all()
return vs
def first_vertex_by_name(self, name_param: str):
"""
Вершина с заданным именем (предполагается что имя уникальное)
"""
vs = self.vertices_by_name(name_param)
if len(vs) > 0:
return vs[0]
else:
return None
| true |
0d7eab29b10fe1a3510bdedbcde984fa9096d368 | Python | pablo-cerve/confucio | /hsk_check/hsk_check.py | UTF-8 | 4,096 | 2.875 | 3 | [] | no_license | import sys
sys.path.append('.')
import math
import os
import unidecode
from file_utils.text_utils.text_file_reader import TextFileReader
from file_utils.csv_utils.csv_reader import CSVReader
class HSKCheck:
CHINO_PATH = "/Users/pablocerve/Documents/CHINO"
MY_FILE_PATH = CHINO_PATH + "/repo/confucio/lessons/hsk3"
MY_FILE_FILENAME = "hsk3.csv"
OFFICIAL_PATH = CHINO_PATH + "/HSK3/palabras/official_list"
IMAGES_PATH = CHINO_PATH + "/HSK3/palabras/oficiales"
@classmethod
def compare_with_official(cls):
official_words = cls.get_official_words("HSK3.txt")
assert(len(official_words) == 600)
my_words = cls.get_my_words(0)
assert(len(my_words) == 600)
assert(official_words == my_words)
print("compare_with_official - SUCCESS!")
# cls.compare_with_official_diff(official_words, my_words)
@classmethod
def compare_with_images(cls):
my_pinyin = cls.get_my_words(1)
assert(len(my_pinyin) == 600)
my_pinyin = [unidecode.unidecode(word) for word in my_pinyin]
words = cls.get_images()
assert(len(words) == 600)
words = [word.upper() for word in words]
words = [unidecode.unidecode(word) for word in words]
assert(my_pinyin == words)
print("compare_with_images - SUCCESS!")
# cls.compare_with_images_diff(my_pinyin, words)
######################################################################
@classmethod
def compare_with_official_diff(cls, official_words, my_words):
official_not_my = list(set(official_words) - set(my_words))
official_not_my_length = len(official_not_my)
print("official_not_my - " + str(official_not_my_length))
assert(official_not_my_length == 0)
cls.print_array(official_not_my)
print
my_not_official = list(set(my_words) - set(official_words))
my_not_official_length = len(my_not_official)
print("my_not_official - " + str(my_not_official_length))
assert(my_not_official_length == 0)
cls.print_array(my_not_official)
prev = 1
for idx, word in enumerate(official_words):
my_word = my_words[idx]
if my_word != word:
if idx != prev + 1:
print(idx, word, my_word)
prev = idx
@classmethod
def compare_with_images_diff(cls, my_pinyin, words):
for idx, word in enumerate(words):
pinyin = my_pinyin[idx]
word_upper = word.upper()
pinyin_un = unidecode.unidecode(pinyin)
word_un = unidecode.unidecode(word_upper)
if pinyin_un != word_un:
print(idx + 1, pinyin_un, word_un)
assert(pinyin_un == word_un)
@classmethod
def print_array(cls, array):
for word in array:
print(word)
@classmethod
def get_official_words(cls, filename):
file = TextFileReader(cls.OFFICIAL_PATH, filename)
array = []
while file.continue_reading:
word = file.read_line().strip()
array.append(word)
return array
@classmethod
def get_my_words(cls, column_number):
lines = CSVReader(cls.MY_FILE_PATH, cls.MY_FILE_FILENAME).lines
array = []
lines.pop(0)
for line in lines:
word = line[column_number].strip()
array.append(word)
return array
@classmethod
def get_images(cls):
words = []
for folder_name in sorted(os.listdir(cls.IMAGES_PATH)):
if ".DS_Store" in folder_name:
continue
# print(folder_name)
for image_name in sorted(os.listdir(cls.IMAGES_PATH + "/" + folder_name)):
if ".DS" in image_name:
continue
word_start = image_name.find("-") + 1
word_end = image_name.find("_")
word = image_name[word_start:word_end]
# print(word)
words.append(word)
return words
| true |
378d5abea3ab25d8c9157db9720b88db392b8e7c | Python | NatanaelEmilioC/bolsa_pred | /Meu_Scrapy/Meu_Scrapy/historico_bolsa.py | UTF-8 | 557 | 2.78125 | 3 | [] | no_license | """from googlefinance.get import get_datum
df = get_datum('KRX:005930', period='2M', interval =86400)
print(df)
"""
import numpy as np
import pandas as pd
from pandas.io.json import json_normalize
import json
#print(pd.read_csv('historico_petr4.csv', delimiter=','))
with open("spiders/istoe.json") as datafile:
data = json.load(datafile)
dataframe = pd.DataFrame(data)
grouped = dataframe.groupby('data')
#grp = df.groupby('Name')
for name, group in grouped:
print(str(name))
print(str(group))
print()
#print(grouped.groups)
| true |
5aa92870db438858446030d4da7544960503977c | Python | chen1711/Projects | /NLP/CYK/code.py | UTF-8 | 703 | 2.609375 | 3 | [] | no_license | ## given a set of CNF rules with prob , and a tagged sent
## gives the cyk tree
## rules input - S -> NP VP = 1.0
## sent The_DET man_NN saw_VB the_DET girl_NN ._SYM
import cyk
import sys
#f = open('rules_cnf.txt','r')
f = open(sys.argv[1],'r')
text = f.readlines()
f.close()
rules ={}
for t in text:
t = t[:-1]
r,p = t.split('=')
rules[r.strip()] = p.strip()
#f = open('English_Test_Parse.txt','r')
f=open(sys.argv[2],'r')
text = f.readlines()
f.close()
sentences = []
for t in text:
print t
tag =[]
tag.append('ROOT')
t = t[:-1]
t = t.split()
for i in t:
w,pos = i.split('_')
tag.append(pos)
sentences.append(tag)
cyk.build_tree(tag,rules)
| true |
ff6eadcab2847e23b37a0ab54afaf05014041016 | Python | GaboPP/Tarea2-Distribuidos | /Actividad 2/server/server.py | UTF-8 | 3,703 | 2.59375 | 3 | [] | no_license | import pika, time, json
from datetime import datetime
class server:
def __init__(self, queue = "server"):
self.id = 0
self.queue = queue
self.commands = ['exit', '__list', '__messages', '__connect__']
self.list_clients = []
self.dicc_messages = {}
# Init logs
log = open('log.txt', 'w')
log.write('---------------------Logs------------------------\n')
log.close()
self.connection = pika.BlockingConnection(pika.ConnectionParameters('192.168.99.100 '))
self.channel = self.connection.channel()
self.channel.queue_declare(queue=self.queue)
# self.channel.queue_delete(queue="server")
# suscribirse a los mensajes que llegan mediante la f(x) callback
self.channel.basic_consume( queue=self.queue, on_message_callback=self.callback)
print(' [*] Waiting for messages. To exit press CTRL+C')
self.channel.start_consuming()
# función callback, recibe los mensajes
def callback(self, ch, method, properties, body):
self.id +=1
msg = json.loads(body.decode("utf-8"))
print(" [x] Received %r" % msg)
if msg['msg'] not in self.commands:
print(msg['msg'])
#log mensaje
self.log_message(msg)
#registrar mensaje de cliente
if (msg['queue_from'] in self.dicc_messages):
self.dicc_messages[msg['queue_from']].append(msg)
else:
self.dicc_messages[msg['queue_from']] = [msg]
#reenviar
self.send_message(body, msg['queue_dest'])
elif msg['msg'] == '__list':
print(msg['msg'])
self.clients_list(msg, msg['queue_from'])
elif msg['msg'] == '__messages':
print(msg['msg'])
self.client_message(msg, msg['queue_from'])
elif msg['msg'] == '__connect__':
print(msg['msg'])
self.register_client(msg['queue_from'])
ch.basic_ack(delivery_tag = method.delivery_tag)
def register_client(self, client):
self.list_clients.append(client)
def send_message(self, msg, queue_dest):
channel = self.connection.channel()
channel.queue_declare(queue = queue_dest)
channel.basic_publish(exchange='', routing_key=queue_dest, body=msg)
def log_message(self, request):
#la cola guarda y dps envia lo que faltba por enviarse.
log = open('log.txt', 'a')
log.write('| Id: ' + str(self.id) + '\n')
log.write('| Client: ' + str(request['queue_from']) + '\n')
log.write('| Mensaje: ' + request['msg'] + '\n')
log.write('| Timestamp: ' + request['time'] + '\n')
log.write('-------------------------------------------------\n')
def clients_list(self, msg, queue_from):
msg['msg'] = json.dumps(self.list_clients)
del msg['time']
self.send_message( bytes(json.dumps(msg), "utf-8"), queue_from)
def client_message(self, msg, queue_from):
if queue_from in self.dicc_messages:
messages = [message['msg'] for message in self.dicc_messages[queue_from]]
response = bytes(json.dumps(messages), "utf-8")
else:
response = bytes(json.dumps({'msg': 'sin mensajes :('}), "utf-8")
print(response)
self.send_message( response, queue_from)
def close_connection(self):
self.connection.close()
servidor = server()
try:
while True:
time.sleep(86400)
except KeyboardInterrupt:
servidor.close_connection() | true |
0f80387d59d09c19f8a87c41825df70b39ab68e7 | Python | happinessbaby/Code_Wars | /zero.py | UTF-8 | 163 | 2.828125 | 3 | [] | no_license | import math
import functools
def zero(n):
return functools.reduce(lambda r, i: r + math.floor(n/(5**i)), range(0, len(str(n))+2))
print(zero(1000))
| true |
66c043f2dc39a5cf1bc71b8fec6d76f4bb95a411 | Python | orbache/pythonExercises | /exercise5.py | UTF-8 | 667 | 4.25 | 4 | [] | no_license | #!/usr/bin/python
__author__ = "Evyatar Orbach"
__email__ = "evyataro@gmail.com"
'''Exercise 5
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
Make sure your program works on two lists of different sizes.
'''
listA = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,13]
listB = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
newList = []
listA.sort()
listB.sort()
for itemA in listA:
if itemA in listB and itemA not in newList:
newList.append(itemA)
print newList
| true |
590449fe000376a0249565bf1b01c8ea12123f8a | Python | The-Art-of-Hacking/h4cker | /programming_and_scripting_for_cybersecurity/recon_scripts/scanning/simple_scapy_scan.py | UTF-8 | 3,057 | 3.34375 | 3 | [
"MIT"
] | permissive | import argparse
from scapy.all import *
def arp_scan(ip):
"""
Network scanning using ARP requests to an IP address or a range of IP addresses.
Args:
ip (str): An IP address or IP address range to scan. For example:
- 192.168.88.1 to scan a single IP address
- 192.168.88.1/24 to scan a range of IP addresses.
Returns:
A list of dictionaries mapping IP addresses to MAC addresses. For example:
[
{'IP': '192.168.88.1', 'MAC': 'D3:4D:B3:3F:88:99'}
]
"""
request = Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip)
ans, unans = srp(request, timeout=2, retry=1)
result = []
for sent, received in ans:
result.append({'IP': received.psrc, 'MAC': received.hwsrc})
return result
def tcp_scan(ip, ports):
"""
TCP SYN scanning.
Args:
ip (str): An IP address or hostname to target.
ports (list or tuple of int): A list or tuple of ports to scan.
Returns:
A list of ports that are open.
"""
try:
syn = IP(dst=ip) / TCP(dport=ports, flags="S")
except socket.gaierror:
raise ValueError('Hostname {} could not be resolved.'.format(ip))
ans, unans = sr(syn, timeout=2, retry=1)
result = []
for sent, received in ans:
if received[TCP].flags == "SA":
result.append(received[TCP].sport)
return result
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(
dest="command", help="Command to perform.", required=True
)
arp_subparser = subparsers.add_parser(
'ARP', help='Perform a network scan using ARP requests.'
)
arp_subparser.add_argument(
'IP', help='An IP address (e.g. 192.168.88.1) or address range (e.g. 192.168.88.0/24) to scan.'
)
tcp_subparser = subparsers.add_parser(
'TCP', help='Perform a TCP scan using SYN packets.'
)
tcp_subparser.add_argument('IP', help='An IP address or hostname to target.')
tcp_subparser.add_argument(
'ports', nargs='+', type=int,
help='Ports to scan, delimited by spaces. When --range is specified, scan a range of ports. Otherwise, scan individual ports.'
)
tcp_subparser.add_argument(
'--range', action='store_true',
help='Specify a range of ports. When this option is specified, <ports> should be given as <low_port> <high_port>.'
)
args = parser.parse_args()
if args.command == 'ARP':
result = arp_scan(args.IP)
for mapping in result:
print('{} ==> {}'.format(mapping['IP'], mapping['MAC']))
elif args.command == 'TCP':
if args.range:
ports = tuple(args.ports)
else:
ports = args.ports
try:
result = tcp_scan(args.IP, ports)
except ValueError as error:
print(error)
exit(1)
for port in result:
print('Port {} is open.'.format(port))
if __name__ == '__main__':
main()
| true |
fcb523b3cd858053ebe042a39f1da161c84d019a | Python | ErickJR13/379-Project2 | /game.py | UTF-8 | 2,317 | 3.765625 | 4 | [] | no_license | # DON'T CHANGE ANYTHING IN THIS FILE!!
from random import *
MAX_ATTEMPTS = 5
# Set up instructions to be sent to client
INSTRUCTIONS = """\nThis is hangman. You will guess one letter at a time. If the letter is in
the hidden word, the "-" will be replaced by the correct letter. Guessing multiple letters at
a time will be considered as guessing the entire word (which will result in either a win
or loss automatically - win if correct, loss if incorrect). You win if you either guess all of
the correct letters or guess the word correctly. You lose if you run out of attempts. Attempts
will be decremented in the case of an incorrect or repeated letter guess.\n\n"""
def open_file():
fp = open("words.txt")
fp_list = fp.read().split('\n')
fp.close()
return fp_list
def checkGuessCh(word, word_blanks, guess):
for i, ch in enumerate(word):
if guess == ch and word_blanks[i] == "-":
word_blanks = word_blanks[:i] + ch + word_blanks[i+1:]
return word_blanks
def checkGuessWord(word, guess):
if word == guess:
return 1
return 0
def gameSetup(args):
if args[1] == '-r':
# get random word
fp_list = open_file()
word = sample(fp_list, 1)[0]
while len(word) == 1:
word = sample(fp_list, 1)
else:
word = args[1]
word_blanks = "-"*len(word)
attempts = MAX_ATTEMPTS
win = False
return word, word_blanks, attempts, win
def checkGuess(word, word_blanks, attempts, guess, win):
# Whole word? Win or lose
if len(guess) > 1:
print("Guess was more than 1 char - win/lose only")
win = checkGuessWord(word, guess)
print("Win status: {}".format(win))
return word_blanks, attempts, win
#break
# Otherwise check letter and update word_blanks
word_blanks_check = checkGuessCh(word, word_blanks, guess)
if word_blanks_check == word_blanks:
# wrong letter
print("Incorrectly or already guessed char")
attempts -= 1
print("Attempts left: {}".format(attempts))
else:
print("Correctly guessed char")
# correct letter
word_blanks = word_blanks_check
print("Attempts left: {}".format(attempts))
if word == word_blanks:
print("Correctly guessed word")
win = True
print("Win status: {}".format(win))
return word_blanks, attempts, win
| true |
f80e27fa026fed24e7abc132dd10d1447a4dd77a | Python | dgketchum/raster-vision | /tests/evaluation/test_class_evaluation_item.py | UTF-8 | 1,780 | 2.640625 | 3 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | import unittest
from rastervision.evaluation import ClassEvaluationItem
class TestClassEvaluationItem(unittest.TestCase):
def setUp(self):
pass
def test_merge_both_empty(self):
a = ClassEvaluationItem()
b = ClassEvaluationItem()
a.merge(b)
self.assertEqual(a.precision, None)
self.assertEqual(a.recall, None)
self.assertEqual(a.f1, None)
self.assertEqual(a.count_error, None)
self.assertEqual(a.gt_count, 0)
def test_merge_first_empty(self):
a = ClassEvaluationItem()
b = ClassEvaluationItem(
precision=1, recall=1, f1=1, count_error=0, gt_count=1)
a.merge(b)
self.assertEqual(a.precision, 1)
self.assertEqual(a.recall, 1)
self.assertEqual(a.f1, 1)
self.assertEqual(a.count_error, 0)
self.assertEqual(a.gt_count, 1)
def test_merge_second_empty(self):
a = ClassEvaluationItem(
precision=1, recall=1, f1=1, count_error=0, gt_count=1)
b = ClassEvaluationItem()
a.merge(b)
self.assertEqual(a.precision, 1)
self.assertEqual(a.recall, 1)
self.assertEqual(a.f1, 1)
self.assertEqual(a.count_error, 0)
self.assertEqual(a.gt_count, 1)
def test_merge(self):
a = ClassEvaluationItem(
precision=1, recall=1, f1=1, count_error=0, gt_count=1)
b = ClassEvaluationItem(
precision=0, recall=0, f1=0, count_error=1, gt_count=2)
a.merge(b)
self.assertEqual(a.precision, 1 / 3)
self.assertEqual(a.recall, 1 / 3)
self.assertEqual(a.f1, 1 / 3)
self.assertEqual(a.count_error, 2 / 3)
self.assertEqual(a.gt_count, 3)
if __name__ == '__main__':
unittest.main()
| true |
121f978233227e73a834d061791b93f1bafaae5a | Python | Matt444/Test-Tool-Licence-Plate-Recognition | /app/lprs.py | UTF-8 | 1,935 | 2.9375 | 3 | [
"Python-2.0"
] | permissive | import time
class LicensePlatesRecognitionStats:
def __init__(self):
self.location_time = 0
self.recognition_time = 0
self.found_plates = 0
self.all_plates = 0
self.correctly_found_plates = 0
self.average_recognition_accuracy = 0
self.images_processed = 0
self.images_to_process = 1
self.all_process_time = time.time()
def show(self, args):
print("\n-----------------STATS-----------------")
print("Processed images:", self.images_processed)
if args["verify_locations"]:
print("All available plates:", self.all_plates)
print("Found plates:", self.found_plates)
if args["verify_locations"]:
print("Correctly found plates:", self.correctly_found_plates)
print("Average location accuracy:", str(round(self.correctly_found_plates/self.found_plates * 100, 2)) + '%')
if not args["verify_locations"] and args["verify_characters_recognition"]:
print("Average recognition accuracy:", str(round(self.average_recognition_accuracy / self.images_processed, 2)) + '%')
if args["verify_locations"] and args["verify_characters_recognition"]:
print("Average recognition accuracy:", str(round(self.average_recognition_accuracy/self.correctly_found_plates, 2)) + '%')
location_time = round(self.location_time * 1000)
recognition_time = round(self.recognition_time * 1000)
all_process_time = round((time.time() - self.all_process_time) * 1000)
print("----------------TIMERS----------------")
print("Location time:", location_time, "ms")
print("Recognition time:", recognition_time, "ms")
print("All process time:", all_process_time, "ms")
print("Time for image:", all_process_time/self.images_processed, "ms")
print(round((self.images_processed/all_process_time)*1000,2), "images/s")
| true |
2eb669e281c28626673ec6103e0ab06c74827b47 | Python | JeppeLindberg/Crawler | /titles_request_processor.py | UTF-8 | 939 | 2.84375 | 3 | [] | no_license | import validators
from request_processor import RequestProcessor
from bs4 import BeautifulSoup
class TitlesProcessor(RequestProcessor):
def __init__(self, io_handler):
super().__init__(io_handler)
def process(self, request):
print(f"[{request.url}]")
parse = BeautifulSoup(request.text, 'html.parser')
title = None
parse_title = parse.find('title')
if parse_title is not None:
if parse_title.string is not None:
title = parse_title.string.replace("\n", "")
self._io_handler.add_to_pages(request.url, title)
self._io_handler.add_to_queue(self._find_hrefs(parse))
def _find_hrefs(self, parse):
urls = [a.get('href') for a in parse.find_all('a')]
urls = [u for u in urls if (u is not None) and (validators.url(u))]
urls = [u.split('?')[0] for u in urls]
return urls
| true |
c4561fdaa091079a5a8bdc220960acc92dc33aa1 | Python | gbeckers/agldata | /agldata/stringdata.py | UTF-8 | 18,818 | 3.421875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | import sys, random
from collections import OrderedDict
from .argvalidation import checkpositiveint, checkstring
from .datafiles import get_datadict
__all__ = ['get_stringdata', 'get_data', 'String', 'StringDict', 'StringData',
'StringLabelTuple']
# FIXME use properties instead of methods whenever possible
class String(str):
"""A sequence of tokens.
For efficiency reasons this is implemented as a subclass of Python str,
with added `readingframe` and `tokens` attributes. The reading frame
determines how many characters make up one token.
Note that all methods are inherited from str and return str objects, not
String objects. Most inherited methods do not respect the `readingframe`
of the string, and operate on python string characters.
Parameters
----------
value: object
Object to be interpreted as an agldata String.
readingframe: positive, nonzero int, default None
The number of characters that make up one string token. This will
often be `1`, so that, e.g. the string "abcd" has 4 tokens. However if
there are more tokens than can be coded in one character position,
larger readingframes are the solution. E.g., if readingframe is 2,
then "a1a2" has two tokens, namely "a1" and "a2". If this parameter is
`None`, the readingframe will be taken from `value` if that has a
readingframe, and if it doesn't it will default to 1.
"""
@staticmethod
def _is_valid(value, readingframe):
return (len(value) % readingframe) == 0
def __new__(cls, value, readingframe=None):
value = str(value)
if readingframe is None:
readingframe = getattr(value, 'readingframe', 1)
if readingframe != getattr(value, 'readingframe', readingframe):
raise ValueError(f"`readingframe` parameter ({readingframe}) "
f"does not match that of `value` ({value.readingframe})")
if not cls._is_valid(value, readingframe):
raise ValueError(f"The length of '{value}' ({len(value)}) is not "
f"compatible with a reading frame of {readingframe}")
return super().__new__(cls, value)
def __init__(self, value, readingframe=None):
value = str(value)
if readingframe is None:
readingframe = getattr(value, 'readingframe', 1)
if readingframe != getattr(value, 'readingframe', readingframe):
raise ValueError("`readingframe` parameter does not match that of `value`")
checkpositiveint(readingframe)
self.__readingframe = readingframe
@property
def readingframe(self):
"""The number of characters that make up one string token. Normally 1,
so that, e.g. the string "abcd" has 4 tokens. However if there exist
many tokens, these can be coded with multiple ascii symbols. E.g., if
readingframe is 2, then "a1a2" has two tokens, namely "a1" and "a2"."""
return self.__readingframe
@property
def tokens(self):
"""The set of fundamental units that the string consists of. If the
`readingframe` is 1, then this would be {'a', 'b', 'c', 'd'} in the case
of an "abcd" string. If `readingframe` is 2, then this would be
{'ab', 'cd'}"""
return set([self[i:i + self.__readingframe]
for i in range(0, len(self), self.__readingframe)])
class StringDict(OrderedDict):
"""
An ordered dictionary of string label to token string mappings.
This is handy when strings are long and are easiest referred to by a
label, or when a label is more descriptive:E.g. {'hab1': 'ababcbaba',
'hab2': 'aacbbb'}. The dictionary can be created in the way they are
normally created in Python, but you can also just provide a sequence
or set of strings, in which case the labels of the strings will be the
same as the strings themselves.
StringDict() -> new empty dictionary
StringDict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
StringDict(iterable) -> new dictionary initialized as (key, value)
pairs, if possible. If the iterable just generates python strings,
then initialized as (string, string) pairs, so that a string value
becomes a key to itself.
StringDict(**kwargs) -> new dictionary initialized with the label= string
pairs in the keyword argument list.
For example: StringDict(A='abcd', B='efgh')
Additional parameters
---------------------
readingframe: positive, nonzero int, default 1
The number of characters that make up one string token. This will
often be `1`, so that, e.g. the string "abcd" has 4 tokens. However if
there are more tokens than can be coded in ascii symbols,
the larger readingframes are the solution. E.g., if readingframe is 2,
then "a1a2" has two tokens, namely "a1" and "a2". The readingframe of
all strings should be identical.
"""
def __init__(self, *args, readingframe=None, anchorsymbol=None, **kwargs):
self.__readingframe = readingframe # to be set later if None, need it now for empty dict
try:
super().__init__(*args, **kwargs)
except ValueError:
seq = args[0]
if isinstance(seq[0], dict): # a list of 1-item dictionaries
super().__init__(tuple(d.items())[0] for d in seq)
else: # a sequence of string values, no keys
super().__init__([(s, s) for s in seq])
# use our string subclass
for key, item in self.items():
if anchorsymbol is not None:
item = f'{anchorsymbol}{item}{anchorsymbol}'
self[key] = String(item, readingframe=readingframe)
if readingframe is None: # we use the one on the string
readingframe = self[key].readingframe
self.__readingframe = readingframe
@property
def readingframe(self):
"""The number of characters that make up one string token. Normally 1,
so that, e.g. the string "abcd" has 4 tokens. However if there exist
many tokens, these can be coded with multiple ascii symbols. E.g., if
readingframe is 2, then "a1a2" has two tokens, namely "a1" and "a2"."""
return self.__readingframe
@property
def tokens(self):
"""The set of fundamental units that the strings in the dictionary
consist of. If the `readingframe` is 1, then this would be
{'a', 'b', 'c', 'd'} in the case of an "abcd" string. If `readingframe`
is 2, then this would be {'ab', 'cd'}"""
t = []
for key, value in self.items():
t.extend(value.tokens)
return set(t)
def __setitem__(self, key, value):
value = String(value, readingframe=self.__readingframe)
self.__readingframe = value.readingframe # in case it was None
super().__setitem__(key, value)
def __str__(self):
maxlabellen = max(map(len, tuple(self.keys())))
lines = ['Readingframe: {}\n'.format(self.readingframe)]
lines.append('Strings: \n')
for l, s in self.items():
lines.append(' {:<{fill}}: {}\n'.format(l, s,
fill=maxlabellen + 1))
return ''.join(lines)
class StringLabelTuple:
"""A tuple of token strings, based on their labels.
Parameters
----------
stringlabels: sequence
A sequence of labels (python str objects) that refer to token
strings. The labels should be keys in the stringdict, if provided.
If stringdict is not provided, then the labels are assumed to be
identical to the token strings (i.e. 'aba' stands for the token
sequence (a,b,a).
stringdict: StringDict
An agldata StringDict that has the stringlabels as keys and the
corresponding token strings as values.
readingframe: positive, nonzero int, default 1
The number of characters that make up one string token. This will
often be `1`, so that, e.g. the string "abcd" has 4 tokens. However if
there are more tokens than can be coded in ascii symbols,
the larger readingframes are the solution. E.g., if readingframe is 2,
then "a1a2" has two tokens, namely "a1" and "a2".
"""
def __init__(self, stringlabels, stringdict=None, readingframe=None):
stringlabels = tuple(stringlabels)
if stringdict is not None:
if not set(stringlabels).issubset(stringdict):
raise ValueError(f'Not all stringlabels are keys in stringdict:'
f'{set(stringlabels).difference(stringdict)}')
if readingframe is not None:
if readingframe != stringdict.readingframe:
raise ValueError(
"`readingframe` not compatible with `stringdict`")
readingframe = stringdict.readingframe
else:
if readingframe is None:
readingframe = 1
self._stringdict = stringdict
self._labels = stringlabels
self.__readingframe = readingframe
@property
def readingframe(self):
return self.__readingframe
@property
def tokens(self):
"""The set of fundamental units that the strings in the tuple
consist of. If the `readingframe` is 1, then this would be
{'a', 'b', 'c', 'd'} in the case of an "abcd" string. If `readingframe`
is 2, then this would be {'ab', 'cd'}"""
t = []
for s in self.strings():
t.extend(s.tokens)
return set(t)
def __iter__(self):
if self._stringdict: # labels are different from strings
for l in self._labels:
yield (l, self._stringdict[l])
else: # the strings are identical to labels
for l in self._labels:
yield (l, l)
def __getitem__(self, item):
items = self._labels[item]
if not isinstance(items, tuple):
items = (items,)
return StringLabelTuple(items, stringdict=self._stringdict)
def __str__(self):
return str(self._labels)
def __repr__(self):
return '<stringlabeltuple: {}>'.format(self._labels)
def strings(self):
return tuple((self._stringdict[l] for l in self._labels))
def labels(self):
return self._labels
def items(self):
return tuple((l, s) for l, s in self)
class StringData:
"""String data set
Parameters
----------
strings: StringDict
It can be a StringDict or anything that is accepted by the StringDict
class at instantiation.
readingframe: positive, nonzero int, default 1
The number of characters that make up one string token. This will
often be `1`, so that, e.g. the string "abcd" has 4 tokens. However if
there are more tokens than can be coded in ascii symbols,
the larger readingframes are the solution. E.g., if readingframe is 2,
then "a1a2" has two tokens, namely "a1" and "a2".
categories: dict, optional
A dictionary of category label to StringLabelTuple mappings.
categorycomparisons: sequence
A sequence of category pairs that are to be compared.
categorycolors: dict
A dictionary with category to default color mappings. Handy for
figures or tables, e.g. to give violating strings a particular color
that matches the one used in a publication.
"""
def __init__(self, strings, readingframe=None, categories=None,
categorycolors=None, categorycomparisons=None,
tokendurations=None, tokenintervalduration=None,
anchorsymbol=None):
if isinstance(strings, StringDict):
if readingframe is None:
readingframe = strings.readingframe
else:
if not readingframe == strings.readingframe:
raise ValueError(f"`readingframe` parameter ({readingframe}) "
f"is not the same as reading frame of "
f"strings ({strings.readingframe})")
elif readingframe is None:
readingframe = 1
self.strings = strings = StringDict(strings,
readingframe=readingframe,
anchorsymbol=anchorsymbol)
self.readingframe = readingframe
if categories is None:
categories = {}
self.categories = {}
for l, c in categories.items():
self.categories[l] = StringLabelTuple(c, stringdict=strings)
if categorycomparisons is None:
categorycomparisons = (('All', 'All'),)
self.categorycomparisons = categorycomparisons
self.tokendurations = tokendurations
self.tokenintervalduration = tokenintervalduration
categorycolors = {} if categorycolors is None else categorycolors
self.stringlabelcolors = {}
for category, color in categorycolors.items():
for sl in self.categories[category]:
self.stringlabelcolors[sl] = color
for label, string in self.strings.items():
if label not in self.stringlabelcolors:
self.stringlabelcolors[label] = 'black'
if 'All' not in self.categories:
l = list(self.strings.keys())
self.categories['All'] = StringLabelTuple(l, stringdict=strings)
def __getitem__(self, item):
return self.categories[item]
def __str__(self):
lines = [str(self.strings)]
lines.append('Categories:\n')
for category, strt in self.categories.items():
if not category == 'All':
lines.append(' {}: {}\n'.format(category, strt))
return ''.join(lines)
__repr__ = __str__
@property
def tokens(self):
"""The set of fundamental units that the strings in the data
consist of. If the `readingframe` is 1, then this would be
{'a', 'b', 'c', 'd'} in the case of an "abcd" string. If `readingframe`
is 2, then this would be {'ab', 'cd'}"""
return self.strings.tokens
def get_data(study, anchorsymbol=None):
"""Returns a dictionary with at least a 'strings' key. In addition it may
contain a 'readingframe' key, a 'comparisons' key and a 'categories' key,
and anything you defined in that file.
"""
return StringData(**get_datadict(study), anchorsymbol=anchorsymbol)
# FIXME raise depreciation warning
get_stringdata = get_data
def _get_random(randomseed=None):
if randomseed is None:
randomseed = random.randrange(sys.maxsize)
return random.Random(randomseed)
def shuffled(seq, randomseed=None):
seqc = [s for s in seq] # make copy
_get_random(randomseed=randomseed).shuffle(seqc)
return seqc
def stimuli_wilsonetal_2013_jneurosci(randomseed=None, anchorsymbol=None):
"""Returns a string sequence to model the stimulus sequences in the
study: "Wilson B, Slater H, Kikuchi Y, Milne AE, Marslen-Wilson WD,
Smith K, Petkov CI (2013) Auditory Artificial Grammar Learning in Macaque
and Marmoset Monkeys. J Neurosci 33:18825–18835."
The sequence is what a single individual monkey received.
Parameters
----------
randomseed
Returns
-------
dict
A dictionary with info on stimulus sequence.
"""
# Macaques:
# *Habituation* was done as follows: 9 strings per minute, inter-string
# interval was 4 s. For the duration of 2 hours in the afternoon the day
# before testing, and 10 min. immediately before testing (see 'Habituation
# phase' on page 18828). Hence each subject heard 9 * 60 * 2 = 1080 (afternoon
# day before) and then 10 * 9 = 90 (just before test) habituation strings.
# In total: 1170. There are 9 habituation strings, so each one was played 130
# times.
#
# *Testing* was done as follows: randomly selected test string of the eight
# (correct or violation; see below Fam, Novel and Viol strings) strings was
# individually presented (4 times each, for a total of 32 testing trials; at
# an average rate of 1/min; interstring intervals ranged between 45 and
# 75 s).
#
# Marmosets:
# "Four marmosets were available for study, thus, to obtain sufficient data
# for analysis they were each tested four times. Each testing run was
# separated by at least 1 week and followed an identical procedure to the
# macaque experiment, including a habituation and testing phase."
sd = get_stringdata('wilsonetal_2013_jneurosci', anchorsymbol=anchorsymbol)
habstrings = list(sd.categories['Hab'].strings())
habstim = shuffled(habstrings * 130, randomseed=randomseed)
hablabel = ['Hab'] * len(habstim)
teststim = []
testlabel = []
for testcategory in ('Fam', 'Novel', 'ViolbA', 'ViolnbA'):
strings = sd.categories[testcategory].strings()
teststim.extend(strings * 4)
testlabel.extend([testcategory] * len(strings) * 4)
# shuffle the sequence
testlabel, teststim = zip(*shuffled(zip(testlabel, teststim),
randomseed=randomseed))
return {'category': hablabel + list(testlabel),
'string': habstim + list(teststim)}
#FIXME numbers in exposure and test are not clear from paper
def stimuli_attaheri_etal_2015_brainlanguage(randomseed=None):
# stimulus delivery, from the paper:
# "During the first phase of the experiment the animals
# were exposed for 30 min with the exemplary consistent AG
# sequences (Suppl. Fig. S2A). The exposure phase was followed by
# a ~30 min testing phase (240 completed test sequence trials)
# where randomly selected consistent and violation testing
# sequences were individually presented (Suppl. Figs. S1–2)."
# unfortunately the paper is not clear on the exact number of exposure
# stimuli. according to suppl info they were randomized.
# it is probably reasonable to assume there are 240 exposure stimuli (
# 8 strings), so every string 30 times.
#
sd = get_stringdata('attaheri_etal_2015_brainlanguage')
expstrings = list(sd.categories['Exposure'].strings())
expstim = shuffled(expstrings * 30, randomseed=randomseed)
constrings = list(sd.categories['Consistent'].strings())
violstrings = list(sd.categories['Violating'].strings())
teststrings = constrings + violstrings
teststim = shuffled(teststrings * 15, randomseed=randomseed)
return expstim, teststim
| true |
ec1316118dff77d612768797bd76e8d9ce021949 | Python | MAZimmermann/maz-pyapps | /scripts/ohlc.py | UTF-8 | 1,207 | 2.8125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 6 12:49:33 2018
@author: MAZimmermann
"""
import os
import json
import datetime as dt
from datetime import timedelta
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader.data as web
def ohlcInfo(appended):
# Specify start and end date
start = dt.datetime.now() + timedelta(-30)
end = dt.datetime.now()
# Grab the ticker appended to the url and make it uppercase (not sure if this is necessary...)
ticker = appended.upper()
# Creating new dataframe (basically a spreadsheet)
df = web.DataReader(ticker, 'iex', start, end)
filename = ticker
# Save our dataframe as a csv
df.to_csv(filename)
# Read the newly saved csv and turn it into a pandas dataframe
df = pd.read_csv(filename)
# Data that will be passed to application.py and rendered via an html template
chart_data = df.to_dict(orient='records')
chart_data = json.dumps(chart_data, indent=2)
data = {'chart_data': chart_data}
# Delete 'filename' once we're done
os.unlink(filename)
# Return data in dictionary format
return(data) | true |
5e460c4efb37fb7e5e6558908f6fbd6accf0f47e | Python | pemami4911/spriteworld | /spriteworld/environment.py | UTF-8 | 6,207 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | # Copyright 2019 DeepMind Technologies Limited.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
# python2 python3
"""Spriteworld environment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import dm_env
import numpy as np
import six
class Environment(dm_env.Environment):
"""Environment class for Spriteworld.
This environment uses the `dm_env` interface. For details, see
https://github.com/deepmind/dm_env
Modifications by @pemami4911
- uses a random grayscale background
"""
def __init__(self,
task,
action_space,
renderers,
init_sprites,
keep_in_frame=True,
max_episode_length=1000,
metadata=None):
"""Construct Spriteworld environment.
Args:
task: Object with methods:
- reward: sprites -> float.
- success: sprites -> bool.
action_space: Action space with methods:
- step: action, sprites, keep_in_frame -> reward.
- action_spec: Callable returning ArraySpec or list/dict of such.
renderers: Dict where values are renderers and keys are names, reflected
in the keys of the observation.
init_sprites: Callable returning iterable of sprites, called upon
environment reset.
keep_in_frame: Bool. Whether to keep sprites in frame when they move. This
prevents episodes from terminating frequently when an agent moves a
sprite out of frame.
max_episode_length: Maximum number of steps beyond which episode will be
terminated.
metadata: Optional object to be added to the global_state.
"""
self._task = task
self._action_space = action_space
self._renderers = renderers
self._init_sprites = init_sprites
self._keep_in_frame = keep_in_frame
self._max_episode_length = max_episode_length
self._sprites = self._init_sprites()
self._step_count = 0
self._reset_next_step = True
self._renderers_initialized = False
self._metadata = metadata
self._bg_color = 0
def reset(self):
self._sprites = self._init_sprites()
self._step_count = 0
self._reset_next_step = False
self._bg_color = np.random.randint(200)
return dm_env.restart(self.observation())
def success(self):
return self._task.success(self._sprites)
def should_terminate(self):
timeout = self._step_count >= self._max_episode_length
out_of_frame = any([sprite.out_of_frame for sprite in self._sprites])
return self.success() or out_of_frame or timeout
def step(self, action):
"""Step the environment with an action."""
if self._reset_next_step:
return self.reset()
self._step_count += 1
reward = self._action_space.step(
action, self._sprites, keep_in_frame=self._keep_in_frame)
# Update sprite positions from their velocities
for sprite in self._sprites:
sprite.update_position(keep_in_frame=self._keep_in_frame)
reward += self._task.reward(self._sprites)
observation = self.observation()
if self.should_terminate():
self._reset_next_step = True
return dm_env.termination(reward=reward, observation=observation)
else:
return dm_env.transition(reward=reward, observation=observation)
def sample_contained_position(self):
"""Sample a random position contained in a sprite.
This is useful for hand-crafted random agents.
Note that this function does not uniformly sample with respect to sprite
areas. Instead, it randomly selects a sprite, then selects a random position
within that sprite. Consequently, small sprites are represented equally to
large sprites, and in the case of occlusion forground sprites may be
overrepresented relative to background sprites.
Returns:
Float numpy array of shape (2,) in [0, 1]. Position contained in one of
the sprites.
"""
sprite = self._sprites[np.random.randint(len(self._sprites))]
return sprite.sample_contained_position()
def get_sprite_positions(self):
positions = []
for s in self._sprites:
positions += [np.array([s.x, s.y])]
return np.stack(positions)
def pick_attempt(self, point):
for s in self._sprites:
if s.contains_point(point):
return True
return False
def any_occluded(self):
for s1 in self._sprites:
for s2 in self._sprites:
if (s1.position == s2.position).all():
continue
if s1.is_occluded_by(s2):
return True
return False
def state(self):
global_state = {
'success': self.success(),
'bg_color': self._bg_color
}
if self._metadata:
global_state['metadata'] = self._metadata
return {'sprites': self._sprites, 'global_state': global_state}
def observation(self):
state = self.state()
observation = {
name: renderer.render(**state)
for name, renderer in six.iteritems(self._renderers)
}
return observation
def observation_spec(self):
if not self._renderers_initialized:
# Force a rendering so that the sizes of observeration_specs are correct.
self.observation()
self._renderers_initialized = True
renderer_spec = {
name: renderer.observation_spec()
for name, renderer in six.iteritems(self._renderers)
}
return renderer_spec
def action_spec(self):
return self._action_space.action_spec()
@property
def action_space(self):
return self._action_space
| true |
f9aedb4238fd2add0476beb3b192483d2fce19f9 | Python | connorwagner/PiDay | /PiDay.pyw | UTF-8 | 64,159 | 2.53125 | 3 | [] | no_license | import kivy
kivy.require('1.0.6')
from kivy.app import App
from kivy.config import Config
from kivy.clock import Clock
from kivy.uix.popup import Popup
from kivy.uix.progressbar import ProgressBar
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.boxlayout import BoxLayout
from ConnectFour import ConnectFour
from Simon import Simon
from Othello import Othello
from TicTacToe import TicTacToe
import time
import json
import urllib.request
import subprocess
from datetime import datetime, timedelta
from functools import partial
import operator
from pyicloud import PyiCloudService
from config import getUsername, getPassword, getStocks, getWeatherLocale, getCalendarExceptions, getQuotaCurl
class TimeWidget(RelativeLayout):
def __init__(self, timedUpdates, **kwargs):
super(TimeWidget, self).__init__(**kwargs)
# Initialize labels
self.timeLabel = Label(text='12:34 AP', font_size='42', halign='center', valign='center', pos_hint={'x': 0, 'y': 0.25}, size_hint=(1, 0.8))
self.dateLabel = Label(text='Month 12', font_size='20', halign='center', valign='center', pos_hint={'x': 0, 'y': 0.2}, size_hint=(1, 0.2))
self.timedUpdates = timedUpdates
# Update clock every second
Clock.schedule_interval(self.updateTime, 1)
# Add labels to view
self.add_widget(self.timeLabel)
self.add_widget(self.dateLabel)
def updateTime(self, *largs):
self.timeLabel.text = time.strftime("%-I:%M %p")
self.dateLabel.text = time.strftime("%B %-d")
now = datetime.now()
secondsSinceMidnight = (now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()
for updateFrequency in self.timedUpdates:
if secondsSinceMidnight % updateFrequency < 1:
for updateFun in self.timedUpdates[updateFrequency]:
updateFun()
class QuoteWidget(BoxLayout):
def __init__(self, **kwargs):
super(QuoteWidget, self).__init__(**kwargs)
# Initialize label
self.quoteLabel = Button(background_color=[0, 0, 0, 1], on_press=self.timerFun, text='Quote here', halign='center', valign='center')
# Add label to view
self.add_widget(self.quoteLabel)
# Configure label to adjust height to fit text (can only be done after label has been added to a view)
self.quoteLabel.size = (self.quoteLabel.parent.width * 1.85, self.quoteLabel.texture_size[1])
self.quoteLabel.text_size = (self.quoteLabel.width, None)
self.timerFun()
def timerFun(self, *largs):
# Get quote from API call
quote = makeHTTPRequest("http://ron-swanson-quotes.herokuapp.com/v2/quotes")
# If makeHTTPRequest returned False then there was an error, end the function
if not quote:
return
quote = quote[1:-1] + "\n–Ron Swanson"
# Update text on label
self.quoteLabel.text = quote
class WeatherWidget(RelativeLayout):
def __init__(self, **kwargs):
super(WeatherWidget, self).__init__(**kwargs)
# Initialize data variables
self.weatherString = ""
# Initialize label
self.weatherLabel = Label(text='Weather here', halign='center', valign='center', pos_hint={'x': 0, 'y': 0}, size_hint=(1, 1))
self.timerFun()
# Add label to view
self.add_widget(self.weatherLabel)
def timerFun(self, *largs):
# API key: 533616ff356c7a5963e935e12fbb9306
# Lat / long: 40.4644155 / -85.5111644
# City ID for Upland: 4927510
# City Query for Upland: Upland,IN,US
# Sample URL: http://api.openweathermap.org/data/2.5/forecast?id=4927510&appid=533616ff356c7a5963e935e12fbb9306&units=imperial
# JSON Structure: dictionary object 'list' is a list of dictionaries, each index increments by 3 hours
# one item in that dictionary is 'weather', that is a dictionary containing the weather conditions
# another item in that dictionary is 'main', that is a dictionary containing the weather statistics
# Get forecast data and convert to dictionary from JSON
forecastJsonStr = makeHTTPRequest("http://api.openweathermap.org/data/2.5/forecast?zip=%s&appid=533616ff356c7a5963e935e12fbb9306&units=imperial" % getWeatherLocale())
# Get current weather data and convert to dictionary from JSON
currentJsonStr = makeHTTPRequest("http://api.openweathermap.org/data/2.5/weather?zip=%s&appid=533616ff356c7a5963e935e12fbb9306&units=imperial" % getWeatherLocale())
# If makeHTTPRequest returned False then there was an error, end the function
if not forecastJsonStr or not currentJsonStr:
return
forecastJsonDict = json.loads(forecastJsonStr)
currentJsonDict = json.loads(currentJsonStr)
# Get city name from dictionary
city = currentJsonDict['name']
# Get current weather data
currentTemp = "%i°F" % int(round(currentJsonDict['main']['temp']))
currentCond = currentJsonDict['weather'][0]['main']
# Loop through all future weather conditions supplied to determine high and low temperatures for the day
currentDateString = time.strftime("%Y-%m-%d")
highTempsList = list()
lowTempsList = list()
weatherList = forecastJsonDict['list']
for i in range(len(weatherList)):
weatherDict = weatherList[i]
tempsDict = weatherDict['main']
if i == 0 and weatherDict['dt_txt'][:10] != currentDateString:
currentDateString = weatherDict['dt_txt'][:10]
if weatherDict['dt_txt'][:10] == currentDateString:
lowTempsList.append(tempsDict['temp_min'])
highTempsList.append(tempsDict['temp_max'])
highTemp = str(round(max(highTempsList))) + "°F"
lowTemp = str(round(min(lowTempsList))) + "°F"
# Create string to display data and set label to show new string
self.weatherString = "Weather for " + city + "\n" + currentTemp + " and " + currentCond + "\nHigh: " + highTemp + "\nLow: " + lowTemp
self.updateUI()
def updateUI(self):
self.weatherLabel.text = self.weatherString
class StockWidget(RelativeLayout):
def __init__(self, **kwargs):
super(StockWidget, self).__init__(**kwargs)
# Initialize data variables
self.stockString = ""
self.recur = None
# Initialize label
self.stockButton = Button(background_color=[0, 0, 0, 1], on_press=self.openStockDetailsWidget, text='Stocks here', halign='center', valign='center', pos_hint={'x': 0, 'y': 0}, size_hint=(1, 1))
self.timerFun()
# Add label to view
self.add_widget(self.stockButton)
def timerFun(self, *largs):
# Get list of stocks desired from config file
stocksListOfLists = getStocks()
pricesStr = str()
stocksListStr = str()
for stockList in stocksListOfLists:
stocksListStr += stockList[0] + ','
stocksListStr = stocksListStr[:-1]
# Get price for desired stocks and add them to the string for the label
jsonData = makeHTTPRequest('https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=' + stocksListStr + '&apikey=DBC2MS0TUABOLZ04')
# If makeHTTPRequest returns False then there was an error, end the function
if not jsonData:
pricesStr = "Error retrieving data"
self.updateUI()
return
data = json.loads(jsonData)
try:
for stockInfo in data["Stock Quotes"]:
pricesStr += "%s: $%.2f\n" % (stockInfo["1. symbol"], float(stockInfo["2. price"]))
except:
pricesStr = "Error retrieving data"
self.updateUI()
return
# Remove trailing newline character
self.stockString = pricesStr[:-1]
self.updateUI()
def updateUI(self):
self.stockButton.text = self.stockString
def openStockDetailsWidget(self, *largs):
self.stockDetailsWidget = StockDetailsWidget()
self.popup = Popup(title="Stock Details", content=self.stockDetailsWidget)
self.stockDetailsWidget.closeButton.bind(on_press=self.popup.dismiss)
self.popup.open()
class StockDetailsWidget(BoxLayout):
def __init__(self, **kwargs):
super(StockDetailsWidget, self).__init__(**kwargs)
self.orientation = 'vertical'
self.spacing = 10
self.stockPriceList = []
self.accountGainLoss = 0
self.accountWorth = 0
self.loadStocks()
self.topContainer = BoxLayout(orientation='horizontal', spacing=10, size_hint=(1, 0.15))
self.bottomContainer = BoxLayout(orientation='vertical', spacing=10, size_hint=(1, 0.70))
self.closeButton = Button(text="Close", halign='center', valign='center', size_hint=(1, 0.15))
if self.accountGainLoss < 0:
self.accountGainLossLabel = Label(text="Account Loss: $ " + str("%.2f" % abs(self.accountGainLoss)))
else:
self.accountGainLossLabel = Label(text="Account Gain: $ " + str("%.2f" % abs(self.accountGainLoss)))
if self.accountWorth < 0:
self.accountWorthLabel = Label(text="Account Worth: - $ " + str("%.2f" % abs(self.accountWorth)))
else:
self.accountWorthLabel = Label(text="Account Worth: $ " + str("%.2f" % self.accountWorth))
self.topContainer.add_widget(self.accountWorthLabel)
self.topContainer.add_widget(self.accountGainLossLabel)
self.tempContainer = BoxLayout(orientation='horizontal', spacing=10)
self.tempContainer.add_widget(Label(text="Stock Symbol:"))
self.tempContainer.add_widget(Label(text="Gain/Loss:"))
self.tempContainer.add_widget(Label(text="Current Value:"))
self.tempContainer.add_widget(Label(text="Bought at:"))
self.tempContainer.add_widget(Label(text="Owned:"))
self.bottomContainer.add_widget(self.tempContainer)
for x in range(len(self.stockPriceList)):
rowContainer = BoxLayout(orientation='horizontal', spacing=10)
for y in range(5):
rowContainer.add_widget(Label(text=self.stockPriceList[x][y]))
self.bottomContainer.add_widget(rowContainer)
self.add_widget(self.topContainer)
self.add_widget(self.bottomContainer)
self.add_widget(self.closeButton)
def loadStocks(self, *largs):
stocksListOfLists = getStocks()
stocksListStr = str()
for stockList in stocksListOfLists:
stocksListStr += stockList[0] + ','
stocksListStr = stocksListStr[:-1]
# Get price for desired stocks and add them to the string for the label
jsonData = makeHTTPRequest('https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=' + stocksListStr + '&apikey=DBC2MS0TUABOLZ04')
data = json.loads(jsonData)
try:
for stockInfo in data["Stock Quotes"]:
for stockList in stocksListOfLists:
if stockList[0] != stockInfo["1. symbol"]:
continue
boughtAtString = str(stockList[1])
boughtAtInt = int(stockList[1])
if float(boughtAtInt) == stockList[1]:
boughtAtString += "0"
price = stockInfo["2. price"]
gainLossString = ""
gainLoss = (float(price) - float(stockList[1])) * stockList[2]
if gainLoss < 0:
gainLossString = "- $ " + str("%.2f" % abs(gainLoss))
else:
gainLossString = "+ $ " + str("%.2f" % abs(gainLoss))
self.accountGainLoss += gainLoss
self.accountWorth += float(price) * stockList[2]
self.stockPriceList.append([str(stockList[0]), gainLossString, ("$ %.2f" % float(price)), "$ " + boughtAtString, str(stockList[2])])
except:
pricesStr = "Error retrieving data"
self.updateUI()
return
class DaySelector(BoxLayout):
def __init__(self, calendarObject, **kwargs):
super(DaySelector, self).__init__(**kwargs)
# Configure DaySelector object
self.orientation = 'horizontal'
self.spacing = 2
# Initialize data variables
self.dayList = ['U', 'M', 'T', 'W', 'R', 'F', 'S']
self.dayAdjustment = int(time.strftime("%w"))
self.calendarObject = calendarObject
self.timerFun()
def timerFun(self, *largs):
self.dayAdjustment = int(time.strftime("%w"))
self.selectedDay = 0
# Remove all existing widgets
self.clear_widgets()
# Add all other buttons
for i in range(0, len(self.dayList)):
btn = None
if i == self.selectedDay:
btn = ToggleButton(text=self.dayList[self.dayAdjustment % len(self.dayList)], group='daySelector', state='down')
else:
btn = ToggleButton(text=self.dayList[(i + self.dayAdjustment) % len(self.dayList)], group='daySelector')
btn.bind(on_press=self.dayChanged)
self.add_widget(btn)
def dayChanged(self, pressedBtn):
self.selectedDay = self.dayList.index(pressedBtn.text) - self.dayAdjustment
self.calendarObject.updateUI()
def getSelectedDay(self):
return self.selectedDay
class CalendarEvent(RelativeLayout):
def __init__(self, event, **kwargs):
super(CalendarEvent, self).__init__(**kwargs)
# Initialize data variables
self.event = event
self.displayString = ""
# Generate string to display
self.getDisplayString()
# Create labels
self.label = Label(text=self.displayString, halign='center', valign='center')
# Add labels to view
self.add_widget(self.label)
def getDisplayString(self):
# Sanitize edge cases
startHour = self.event['localStartDate'][4]
startHourAmPm = "AM"
if startHour >= 12:
startHour -= 12
startHourAmPm = "PM"
if startHour == 0:
startHour = 12
endHour = self.event['localEndDate'][4]
endHourAmPm = "AM"
if endHour >= 12:
endHour -= 12
endHourAmPm = "PM"
if endHour == 0:
endHour = 12
# Create string to display
self.displayString = "%s: %i:%02i %s to %i:%02i %s at %s" % (self.event['title'], startHour, self.event['localStartDate'][5], startHourAmPm, endHour, self.event['localEndDate'][5], endHourAmPm, self.event['location'])
# If there is no location then remove the end of the string (… at …)
if self.event['location'] is None:
self.displayString = self.displayString[:-8]
class CalendarWidget(BoxLayout):
def __init__(self, **kwargs):
super(CalendarWidget, self).__init__(**kwargs)
# Configure CalendarWidget object
self.orientation = 'vertical'
self.spacing = 5
# Create auth variables
self.twoFactorDone = False
self.twoFactorScreen = None
self.icloudApi = None
# Initialize data variables
self.daySeparatedEventList = []
# Create DaySelector widget
self.daySelector = DaySelector(self, size=(0, 35), size_hint=(1, None))
self.add_widget(self.daySelector)
def finishInitSetup(self):
# Get calendar data
self.timerFun()
def authenticate(self):
self.icloudApi = PyiCloudService(getUsername(), getPassword())
if self.icloudApi.requires_2fa:
self.twoFactorScreen = TwoFactorAuthScreen(self)
else:
self.finishInitSetup()
def timerFun(self, *largs):
now = datetime.now()
# Get list of exceptions from config
exceptions = getCalendarExceptions()
# Try to get calendar data, if an error is thrown then reauthenticate and try again
events = None
try:
events = self.icloudApi.calendar.events(now, now + timedelta(days=6))
except:
self.icloudApi = PyiCloudService(getUsername(), getPassword())
events = self.icloudApi.calendar.events(now, now + timedelta(days=6))
# Separate events into a list of lists separated by day
dateFormat = "%Y%m%d"
today = time.strftime(dateFormat)
self.daySeparatedEventList = [list(), list(), list(), list(), list(), list(), list()]
for event in events:
# Ensure that the event is not on a calendar that the user does not wish to see
if event['pGuid'] not in exceptions:
print(event['pGuid'], event['title'])
daysDiff = (datetime.strptime(str(event['localStartDate'][0]), dateFormat) - datetime.strptime(today, dateFormat)).days
# Try statement needed because the API hands back a list of the next 7 days with events in them, so if the current day has no events then it will hand back too many days and the number of days' difference will be 7, exceeding the length of our list
try:
self.daySeparatedEventList[daysDiff].append(event)
except:
pass
# Sort each list of events by start time
for listOfEvents in self.daySeparatedEventList:
listOfEvents.sort(key=operator.itemgetter('localStartDate'))
self.updateUI()
def updateUI(self, *largs):
# Remove all existing widgets except for the day selector
for child in self.children[:]:
if child != self.daySelector:
self.remove_widget(child)
# Add new widgets
for event in self.daySeparatedEventList[self.daySelector.getSelectedDay()]:
# Add widgets at index 1 so they do not go below the day selector
self.add_widget(CalendarEvent(event), index=1)
if len(self.daySeparatedEventList[self.daySelector.getSelectedDay()]) == 0:
self.add_widget(Label(text="There are no events on this day."), index=1)
class BrightnessWidgets(BoxLayout):
def __init__(self, **kwargs):
super(BrightnessWidgets, self).__init__(**kwargs)
# Configure BrightnessWidgets object
self.orientation = 'vertical'
self.spacing = 5
# Initialize variables
self.isDark = False
self.darkTitle = "Go Dark"
self.brightTitle = "Go Bright"
# Create button
self.button = Button(text=self.darkTitle, halign='center', valign='center')
# Configure button
self.button.bind(on_press=self.switchBrightness)
# Add button to view
self.add_widget(self.button)
def switchBrightness(self, *largs):
if self.isDark:
self.isDark = False
self.brightScreen()
self.button.text = self.darkTitle
else:
self.isDark = True
self.darkScreen()
self.button.text = self.brightTitle
def darkScreen(self, *args):
self.modifyBrightness(11)
def decrBrightness(self):
brightness = self.getBrightness()
# Display shuts off below 11 so we want to make sure we will not go below 11
if brightness <= 26:
self.modifyBrightness(11)
else:
self.modifyBrightness(brightness - 15)
def incrBrightness(self):
brightness = self.getBrightness()
# Maximum value for brightness is 255, we want to ensure that we will not exceed it
if brightness >= 240:
self.modifyBrightness(255)
else:
self.modifyBrightness(brightness + 15)
def brightScreen(self, *args):
self.modifyBrightness(255)
def getBrightness(self):
# Open brightness file to read current value
with open('/sys/class/backlight/rpi_backlight/brightness', 'r') as brightnessFile:
return int(brightnessFile.read())
def modifyBrightness(self, brightness):
# Open brightness file to write modified brightness value to
with open('/sys/class/backlight/rpi_backlight/brightness', 'w') as brightnessFile:
subprocess.call(['echo',str(brightness)],stdout=brightnessFile)
class QuotaWidget(BoxLayout):
def __init__(self, **kwargs):
super(QuotaWidget, self).__init__(**kwargs)
# Configure QuotaWidget object
self.orientation = 'vertical'
self.spacing = 10
# Create container object so pictures are displayed side by side
self.container = BoxLayout(orientation='horizontal', spacing=15)
self.add_widget(self.container)
# Create variables for later use
self.curlCall = []
curlStr = getQuotaCurl()
inQuotes = False
lastIndex = 0
for i in range(len(curlStr)):
if curlStr[i] == ' ':
if not inQuotes:
newStr = curlStr[lastIndex:i].replace("'",'').strip()
if len(newStr) > 0:
self.curlCall.append(newStr)
lastIndex = i + 1
if curlStr[i] == "'":
if inQuotes:
inQuotes = False
newStr = curlStr[lastIndex:i].replace("'",'').strip()
if len(newStr) > 0:
self.curlCall.append(newStr)
lastIndex = i + 1
else:
inQuotes = True
lastIndex = i + 1
lastStr = curlStr[lastIndex:].strip()
if len(lastStr) > 0:
self.curlCall.append(lastStr)
self.workingDir = str(subprocess.check_output('pwd'))[2:-3]
self.dailyImage = None
self.weeklyImage = None
self.popup = None
# Add close button for popup
self.closeButton = Button(text="Close", halign='center', valign='center', size_hint=(1, 0.15))
self.add_widget(self.closeButton)
def updateImageDisplays(self):
self.dailyImage = Image(source='%s/dailyQuota.png' % self.workingDir)
self.weeklyImage = Image(source='%s/weeklyQuota.png' % self.workingDir)
self.container.add_widget(self.dailyImage)
self.container.add_widget(self.weeklyImage)
def loadDailyImage(self, *largs):
dailyCurl = self.curlCall[:]
dailyCurl[1] += "daily"
with open('%s/dailyQuota.png' % self.workingDir, 'w') as file:
subprocess.call(dailyCurl, stdout=file)
def loadWeeklyImage(self, *largs):
weeklyCurl = self.curlCall[:]
weeklyCurl[1] += "weekly"
with open('%s/weeklyQuota.png' % self.workingDir, 'w') as file:
subprocess.call(weeklyCurl, stdout=file)
class SystemMenuWidget(BoxLayout):
def __init__(self, **kwargs):
super(SystemMenuWidget, self).__init__(**kwargs)
self.orientation = 'vertical'
self.spacing = 10
self.container = BoxLayout(orientation='horizontal', spacing=10)
self.exitButton = Button(text="Exit PiDay", halign='center', valign='center')
self.rebootButton = Button(text="Reboot Pi", halign='center', valign='center')
self.closeButton = Button(text="Close Popup", halign='center', valign='center')
self.container.add_widget(self.exitButton)
self.container.add_widget(self.rebootButton)
self.add_widget(self.container)
self.add_widget(self.closeButton)
self.exitButton.bind(on_press=quitProg)
self.rebootButton.bind(on_press=rebootPi)
class GamesWidget(RelativeLayout):
def __init__(self, **kwargs):
super(GamesWidget, self).__init__(**kwargs)
self.orientation = 'vertical'
self.spacing = 10
# Make the gameWidget containers (will hold rows of game buttons)
self.containerTop = BoxLayout(orientation='horizontal', spacing=10, pos_hint={'x': 0, 'y': 0.60}, size_hint=(1, 0.40))
self.containerBottom = BoxLayout(orientation='horizontal', spacing=10, pos_hint={'x': 0, 'y': 0.17}, size_hint=(1, 0.40))
self.containerClose = BoxLayout(orientation='horizontal', spacing=10, pos_hint={'x': 0, 'y': 0})
self.othelloButton = Button(text="Othello", halign='center', valign='center')
self.connectFourButton = Button(text="Connect Four", halign='center', valign='center')
self.tttButton = Button(text="TicTacToe", halign='center', valign='center')
self.simonButton = Button(text="Simon", halign='center', valign='center')
self.closeButton = Button(text="Close", halign='right', valign='center', size_hint=(1, 0.15))
# Top row will contain TicTacToe, and Connect Four
# Bottom row will contain Othello and Simon
self.containerTop.add_widget(self.tttButton)
self.containerTop.add_widget(self.connectFourButton)
self.containerBottom.add_widget(self.othelloButton)
self.containerBottom.add_widget(self.simonButton)
self.containerClose.add_widget(self.closeButton)
self.add_widget(self.containerTop)
self.add_widget(self.containerBottom)
self.add_widget(self.containerClose)
# Bind game buttons to respective launcher functions
self.tttButton.bind(on_press=self.openTicTacToe)
self.othelloButton.bind(on_press=self.openOthello)
self.simonButton.bind(on_press=self.openSimon)
self.connectFourButton.bind(on_press=self.openConnectFour)
# Opens the TicTacToe popup
def openTicTacToe(self, *largs):
self.tttWidget = TicTacToeWidget()
self.tttPopup = Popup(title="Tic Tac Toe", content=self.tttWidget)
self.tttWidget.exitButton.bind(on_press=self.tttPopup.dismiss)
self.tttPopup.open()
# Opens the Othello popup
def openOthello(self, *largs):
self.othelloWidget = OthelloWidget()
self.othelloPopup = Popup(title="Othello", content=self.othelloWidget)
self.othelloWidget.exitButton.bind(on_press=self.othelloPopup.dismiss)
self.othelloPopup.open()
# Opens the Simon Popup, and the Start popup (not totally functional)
def openSimon(self, *largs):
self.simonWidget = SimonWidget()
self.simonPopup = Popup(title="Simon", content=self.simonWidget)
self.simonPopup.open()
self.simonWidget.startingPopUp()
self.simonWidget.exitButton.bind(on_press=self.simonPopup.dismiss)
# Opens the connect four popup
def openConnectFour(self, *largs):
self.connectFourWidget = ConnectFourWidget()
self.connectFourPopup = Popup(title="Connect Four", content=self.connectFourWidget)
self.connectFourPopup.open()
self.connectFourWidget.exitButton.bind(on_press=self.connectFourPopup.dismiss)
class TicTacToeWidget(BoxLayout):
def __init__(self, *largs, **kwargs):
super(TicTacToeWidget, self).__init__(**kwargs)
self.orientation = 'horizontal'
self.spacing = 7
# Create the containers for the popup
self.boardContainer = BoxLayout(orientation='vertical', spacing=5, size_hint=(0.90, 1))
self.leftSideContainer = BoxLayout(orientation='vertical', spacing=10, size_hint=(0.10, 1))
self.ttt = TicTacToe()
# Create control buttons to be put in the side container
self.exitButton = Button(text="Exit", halign='right', valign='center')
self.resetButton = Button(text="Reset", halign='right', valign='center', on_press=self.resetGame)
self.containerList = []
self.btnList = []
# Add buttons to rows in rowsContainer
for row in range(3):
self.containerList.append(BoxLayout(orientation='horizontal', spacing=5))
self.tempList = []
for col in range(3):
temp = Button(text='X', color=[192, 192, 192, 0.30], halign='right', valign='top', background_normal='atlas://data/images/defaulttheme/button_disabled', font_size=84, on_press=partial(self.playerMoveHelper, row, col))
self.containerList[row].add_widget(temp)
self.tempList.append(temp)
self.btnList.append(self.tempList)
for container in self.containerList:
self.boardContainer.add_widget(container)
# Add widgets to their respective containers
self.leftSideContainer.add_widget(self.exitButton)
self.leftSideContainer.add_widget(self.resetButton)
self.add_widget(self.leftSideContainer)
self.add_widget(self.boardContainer)
# Helper function for playerMove() (called by pressing a button)
def playerMoveHelper(self, row, col, *largs):
state = self.ttt.whoseTurn()
self.ttt.playerMove(row, col, state)
# Disable the chosen spot, and set it's text properly
self.btnList[row][col].disabled = True
if state == 1:
self.btnList[row][col].text = "X"
else:
self.btnList[row][col].text = "O"
# Code below is used to show whose turn it is / possible moves
for x in range(3):
for y in range(3):
if self.ttt.gameBoard[x][y] == 0:
if state == 2:
self.btnList[x][y].text = "X"
else:
self.btnList[x][y].text = "O"
self.isWinner(row, col, state)
# Determines if there is a winner, and displays an appropriate popup if there is
def isWinner(self, row, col, state):
if self.ttt.isWinner(row, col, state):
for row in range(3):
for col in range(3):
self.btnList[row][col].disabled = True
if self.ttt.gameBoard[row][col] == 0:
self.btnList[row][col].text = ""
if state == 1:
self.popupWinner = Popup(title="Game Over", content=Label(text="Player X Wins!!"), size_hint=(0.50, 0.50))
self.popupWinner.open()
return
else:
self.popupWinner = Popup(title="Game Over", content=Label(text="Player O Wins!!"), size_hint=(0.50, 0.50))
self.popupWinner.open()
return
if self.ttt.getNumSpotsLeft() == 0:
self.popupDraw = Popup(title="Game Over", content=Label(text="Draw!!"), size_hint=(0.50, 0.50))
self.popupDraw.open()
# Resets game board and visual board
def resetGame(self, *largs):
self.ttt.spotsUsed = 0
self.ttt.recentState = 1
self.ttt.recentCol = 0
self.ttt.recentRow = 0
self.ttt.winner = -1
for row in range(3):
for col in range(3):
self.ttt.gameBoard[row][col] = 0
self.btnList[row][col].text = "X"
self.btnList[row][col].color = [192, 192, 192, 0.30]
self.btnList[row][col].disabled = False
class OthelloWidget(BoxLayout):
def __init__(self, *largs, **kwargs):
super(OthelloWidget, self).__init__(**kwargs)
self.orientation = 'horizontal'
self.spacing = 7
# Create containers to divide the othello popup
self.boardContainer = BoxLayout(orientation='vertical', spacing=1, size_hint=(0.90, 1))
self.leftSideContainer = BoxLayout(orientation='vertical', spacing=10, size_hint=(0.10, 1))
self.rightSideContainer = BoxLayout(orientation='vertical', spacing=10, size_hint=(0.10, 1))
self.othello = Othello()
# Create exit & reset button for left side container
self.exitButton = Button(text="Exit", halign='right', valign='center')
self.resetButton = Button(text="Reset", halign='right', valign='center', on_press=self.resetGame)
# Create buttons to track # of black and white tokens, as well as whose turn it is (for right side container)
self.blackTokenButton = Button(text=str(self.othello.twoCtr), background_disabled_normal='atlas://data/images/defaulttheme/button', halign='right', valign='center', disabled=True, background_color=[0, 0, 0, 1])
self.whiteTokenButton = Button(text=str(self.othello.oneCtr), color=[0, 0, 0, 1], background_disabled_normal='atlas://data/images/defaulttheme/button', halign='right', valign='center', disabled=True, background_color=[60, 179, 113, 1])
self.whoseTurnButton = Button(text="Turn", halign='right', background_disabled_normal='atlas://data/images/defaulttheme/button', valign='center', disabled=True, background_color=[0, 0, 0, 1])
self.containerList = []
self.btnList = []
# Add buttons to rows in rowsContainer
for row in range(8):
self.containerList.append(BoxLayout(orientation='horizontal', spacing=1))
self.tempList = []
for col in range(8):
temp = Button(halign='right', valign='top', background_disabled_normal='atlas://data/images/defaulttheme/button', background_color=[0, 100, 0, 0.50], on_press=partial(self.playerMoveHelper, row, col, self.othello.whoseTurn()))
self.containerList[row].add_widget(temp)
self.tempList.append(temp)
self.btnList.append(self.tempList)
# Manually add the four center tokens (do this so whoseTurn() isn't messed up, as black must go first)
self.othello.gameBoard[3][3] = 1
self.othello.gameBoard[3][4] = 2
self.othello.gameBoard[4][3] = 2
self.othello.gameBoard[4][4] = 1
self.btnList[3][3].background_color = [60, 179, 113, 1]
self.btnList[3][4].background_color = [0, 0, 0, 1]
self.btnList[4][3].background_color = [0, 0, 0, 1]
self.btnList[4][4].background_color = [60, 179, 113, 1]
self.btnList[3][3].disabled = True
self.btnList[3][4].disabled = True
self.btnList[4][3].disabled = True
self.btnList[4][4].disabled = True
# Add all the container rows to the row container
for container in self.containerList:
self.boardContainer.add_widget(container)
# Add widgets to their respective containers
self.rightSideContainer.add_widget(self.whiteTokenButton)
self.rightSideContainer.add_widget(self.blackTokenButton)
self.rightSideContainer.add_widget(self.whoseTurnButton)
self.leftSideContainer.add_widget(self.exitButton)
self.leftSideContainer.add_widget(self.resetButton)
self.add_widget(self.leftSideContainer)
self.add_widget(self.boardContainer)
self.add_widget(self.rightSideContainer)
for x in range(8):
for y in range(8):
if self.btnList[x][y].background_color == [0, 100, 0, 0.50]:
if self.othello.checkForSwaps(x, y, self.othello.whoseTurn()) == []:
self.btnList[x][y].disabled = True
else:
self.btnList[x][y].disabled = False
# Function called by the reset button, resets the game
def resetGame(self, *largs):
self.othello.oneCtr = 2
self.othello.twoCtr = 2
self.othello.placeCtr = 4
for row in range(8):
for col in range(8):
self.othello.gameBoard[row][col] = 0
self.btnList[row][col].background_color = [0, 100, 0, 0.50]
self.btnList[row][col].disabled = False
# Manually add the four center tokens (do this so whoseTurn() isn't messed up, as black must go first)
self.othello.gameBoard[3][3] = 1
self.othello.gameBoard[3][4] = 2
self.othello.gameBoard[4][3] = 2
self.othello.gameBoard[4][4] = 1
self.btnList[3][3].background_color = [60, 179, 113, 1]
self.btnList[3][4].background_color = [0, 0, 0, 1]
self.btnList[4][3].background_color = [0, 0, 0, 1]
self.btnList[4][4].background_color = [60, 179, 113, 1]
self.btnList[3][3].disabled = True
self.btnList[3][4].disabled = True
self.btnList[4][3].disabled = True
self.btnList[4][4].disabled = True
# Disable buttons for invalid moves
for x in range(8):
for y in range(8):
if self.btnList[x][y].background_color == [0, 100, 0, 0.50]:
if self.othello.checkForSwaps(x, y, self.othello.whoseTurn()) == []:
self.btnList[x][y].disabled = True
else:
self.btnList[x][y].disabled = False
# Update the display buttons
self.blackTokenButton.text = str(self.othello.twoCtr)
self.whiteTokenButton.text = str(self.othello.oneCtr)
self.whoseTurnButton.background_color = [0, 0, 0, 1]
self.whoseTurnButton.color = [1, 1, 1, 1]
# Helper function called when a placeButton is pressed
def playerMoveHelper(self, row, col, state, *largs):
state = self.othello.whoseTurn()
# Check for any swaps, if there are any, swap them
self.allSwaps = self.othello.playerMove(row, col, state)
if self.allSwaps != []:
for item in self.allSwaps:
if state == 2:
self.btnList[item[0]][item[1]].background_color = [0, 0, 0, 1]
else:
self.btnList[item[0]][item[1]].background_color = [60, 179, 113, 1]
# Disabled place button that was pressed
self.btnList[row][col].disabled = True
# Swap the whoseTurnButton, and the color of the pressed button
if state == 2:
self.whoseTurnButton.background_color = [60, 179, 113, 1]
self.whoseTurnButton.color = [0, 0, 0, 1]
self.btnList[row][col].background_color = [0, 0, 0, 1]
else:
self.whoseTurnButton.background_color = [0, 0, 0, 1]
self.whoseTurnButton.color = [1, 1, 1, 1]
self.btnList[row][col].background_color = [60, 179, 113, 1]
# Update the # of tokens there are currently on the buttons
self.blackTokenButton.text = str(self.othello.twoCtr)
self.whiteTokenButton.text = str(self.othello.oneCtr)
for x in range(8):
for y in range(8):
if self.btnList[x][y].background_color == [0, 100, 0, 0.50]:
if self.othello.checkForSwaps(x, y, self.othello.whoseTurn()) == []:
self.btnList[x][y].disabled = True
else:
self.btnList[x][y].disabled = False
self.checkWinner()
# Determines if there was a winner, and produces a popup for that winner
def checkWinner(self):
if self.othello.isWinner():
if self.othello.twoCtr > self.othello.oneCtr:
self.popupWinner = Popup(title="Game Over", content=Label(text="Black player wins!!"), size_hint=(0.50, 0.50))
self.popupWinner.open()
elif self.othello.oneCtr > self.othello.twoCtr:
self.popupWinner = Popup(title="Game Over", content=Label(text="White player wins!!"), size_hint=(0.50, 0.50))
self.popupWinner.open()
else:
self.popupWinner = Popup(title="Game Over", content=Label(text="Draw!!"), size_hint=(0.50, 0.50))
self.popupWinner.open()
class SimonWidget(BoxLayout):
def __init__(self, *largs, **kwargs):
super(SimonWidget, self).__init__(**kwargs)
self.orientation = 'horizontal'
self.spacing = 7
# Instantiate the buttons that will be in the side container
self.exitButton = Button(text="Exit", halign='right', valign='center')
self.resetButton = Button(text="Reset", halign='right', valign='center', on_press=self.resetGame)
self.simon = Simon()
# Main container will contain top and bot containers, which will contain the colored buttons
self.sideContainer = BoxLayout(orientation='vertical', spacing=10, size_hint=(0.10, 1))
self.mainContainer = BoxLayout(orientation='vertical', spacing=10, size_hint=(0.90, 1))
self.topContainer = BoxLayout(orientation='horizontal', spacing=10)
self.botContainer = BoxLayout(orientation='horizontal', spacing=10)
# buttonList holds the color buttons
self.buttonList = []
# Holds the user inputted colors
self.userColorList = []
# Instantiate the color buttons, and bind them to add their respective color to the list
self.greenButton = Button(halign='right', valign='center', disabled=True, background_color=[0, 1, 0, 0.20], on_press=partial(self.addToUserColorList, "G"))
self.redButton = Button(halign='right', valign='center', disabled=True, background_color=[1, 0, 0, 0.20], on_press=partial(self.addToUserColorList, "R"))
self.yellowButton = Button(halign='right', valign='center', disabled=True, background_color=[255, 255, 0, 0.20], on_press=partial(self.addToUserColorList, "Y"))
self.blueButton = Button(halign='right', valign='center', disabled=True, background_color=[0, 0, 1, 0.20], on_press=partial(self.addToUserColorList, "B"))
self.buttonList.append(self.greenButton)
self.buttonList.append(self.redButton)
self.buttonList.append(self.yellowButton)
self.buttonList.append(self.blueButton)
# Add all widgets in proper order
self.topContainer.add_widget(self.greenButton)
self.topContainer.add_widget(self.redButton)
self.botContainer.add_widget(self.yellowButton)
self.botContainer.add_widget(self.blueButton)
self.sideContainer.add_widget(self.exitButton)
self.sideContainer.add_widget(self.resetButton)
self.mainContainer.add_widget(self.topContainer)
self.mainContainer.add_widget(self.botContainer)
self.add_widget(self.sideContainer)
self.add_widget(self.mainContainer)
# Create the start popup, which SHOULD start the game upon its dismissal, and has a 'Start' button that calls a function to dismiss itself
self.popupStart = Popup(title="Simon", content=Button(text="Start Game", on_press=self.dismissPopup), on_dismiss=self.startGame, size_hint=(0.50, 0.50))
def startingPopUp(self):
self.popupStart.open()
def dismissPopup(self, *largs):
self.popupStart.dismiss()
# Displays initial color, and allows for first userInput
def startGame(self, *largs):
self.simon.addColor()
self.displayOrder()
self.userInput()
# Use for debugging currently, will fully reset the game later
def resetGame(self, *largs):
self.userColorList = []
# If the user sequence was correctly, flash buttons green
def displayCorrect(self):
for button in self.buttonList:
button.disabled = True
button.background_color = [0, 1, 0, 1]
# Adds color to the list, and determines whether to let user continue input, or to stop the game
def addToUserColorList(self, color, *largs):
self.userColorList.append(color)
# If the user hasn't inputted enough colors, make sure their current input is correct, otherwise its game over
if len(self.simon.colorList) > len(self.userColorList):
if self.simon.colorList[0:len(self.userColorList)] == self.userColorList:
return
else:
self.popupWinner = Popup(title="Game Over", content=Label(text="Incorrect Order!"), size_hint=(0.50, 0.50))
self.popupWinner.open()
return
# If the user has inputted enough colors, check the userColors again the gameColors
else:
# If the user is correct, flash green, return the buttons to normal colors, add a color to list,
# display current list, and await user input
if self.simon.isCorrect(self.userColorList):
self.displayCorrect()
time.sleep(3)
self.reAdjustColors()
self.simon.addColor()
self.displayOrder()
self.userInput()
else:
self.popupWinner = Popup(title="Game Over", content=Label(text="Incorrect Order!"), size_hint=(0.50, 0.50))
self.popupWinner.open()
# Used to return buttons to normal colors after flashing green
def reAdjustColors(self):
for i in range(len(self.buttonList)):
if i == 0:
self.buttonList[0].background_color = [0, 1, 0, 0.20]
elif i == 1:
self.buttonList[1].background_color = [1, 0, 0, 0.20]
elif i == 2:
self.buttonList[2].background_color = [255, 255, 0, 0.20]
elif i == 3:
self.buttonList[3].background_color = [0, 0, 1, 0.20]
# Enabled all buttons to enable input
def userInput(self):
self.buttonList[0].background_color = [0, 1, 0, 1]
self.buttonList[0].disabled = False
self.buttonList[1].background_color = [1, 0, 0, 1]
self.buttonList[1].disabled = False
self.buttonList[2].background_color = [255, 255, 0, 1]
self.buttonList[2].disabled = False
self.buttonList[3].background_color = [0, 0, 1, 1]
self.buttonList[3].disabled = False
# Iterates through gameColors, and displays each color in that order
def displayOrder(self):
order = self.simon.colorList
for i in range(len(order)):
if order[i] == "G":
#self.buttonList[0].background_color = [0, 1, 0, 1]
time.sleep(3)
self.buttonList[0].background_color = [255, 255, 255, 1]
time.sleep(3)
self.buttonList[0].background_color = [0, 1, 0, 0.20]
elif order[i] == "R":
time.sleep(3)
#self.buttonList[1].background_color = [1, 0, 0, 1]
self.buttonList[0].background_color = [255, 255, 255, 1]
time.sleep(3)
self.buttonList[1].background_color = [1, 0, 0, 0.20]
elif order[i] == "Y":
time.sleep(3)
#self.buttonList[2].background_color = [255, 255, 0, 1]
self.buttonList[0].background_color = [255, 255, 255, 1]
time.sleep(3)
self.buttonList[2].background_color = [255, 255, 0, 0.20]
elif order[i] == "B":
time.sleep(3)
#self.buttonList[3].background_color = [0, 0, 1, 1]
self.buttonList[0].background_color = [255, 255, 255, 1]
time.sleep(3)
self.buttonList[3].background_color = [0, 0, 1, 0.20]
class ConnectFourWidget(BoxLayout):
def __init__(self, *largs,**kwargs):
super(ConnectFourWidget, self).__init__(**kwargs)
self.orientation = 'horizontal'
self.spacing = 7
# Create exit button for the pop up
self.exitButton = Button(text="Exit", halign='right', valign='center')
self.resetButton = Button(text="Reset", halign='right', valign='center', on_press=self.resetGame)
# Create ConnectFour object, and list to hold the placement buttons
self.connectFour = ConnectFour()
self.btnList = []
# Create buttons for each column, and place them in list
for i in range(7):
self.btnList.append(Button(text=str(i+1), halign='right', valign='top', on_press=partial(self.playerMoveHelper, i)))
# Create containers for the connect four game layout
self.boardContainer = BoxLayout(orientation='vertical', spacing=5, size_hint=(0.90, 1))
self.topContainer = BoxLayout(orientation='horizontal', spacing=1, size_hint=(1, 0.10))
self.rowsContainer = BoxLayout(orientation='vertical', spacing=1, size_hint=(1, 0.90))
self.sideContainer = BoxLayout(orientation='vertical', spacing=10, size_hint=(0.10, 1))
# Add each button in the list to the topContainer
for button in self.btnList:
self.topContainer.add_widget(button)
# containerList will hold the rows of buttons, boardButtonList is a 2d list of all gameButtons
self.containerList = []
self.boardButtonList = []
# Add labels to rows in rowsContainer
for row in range(6):
self.containerList.append(BoxLayout(orientation='horizontal', spacing=1))
self.tempList = []
for col in range(7):
temp = Button(halign='right', valign='top', disabled=True)
self.containerList[row].add_widget(temp)
self.tempList.append(temp)
self.boardButtonList.append(self.tempList)
# Add all the container rows to the row container
for container in self.containerList:
self.rowsContainer.add_widget(container)
# Determine which color to make the control buttons
if self.connectFour.whoseTurn() == 1:
for button in self.btnList:
button.background_color = [0, 0, 1, 1]
else:
for button in self.btnList:
button.background_color = [1, 0, 0, 1]
# Add all of the containers and buttons
self.boardContainer.add_widget(self.topContainer)
self.boardContainer.add_widget(self.rowsContainer)
self.sideContainer.add_widget(self.exitButton)
self.sideContainer.add_widget(self.resetButton)
self.add_widget(self.sideContainer)
self.add_widget(self.boardContainer)
# Function called by resetButton, resets all game boards and button colors for a new game
def resetGame(self, *largs):
for row in range(6):
for col in range(7):
self.boardButtonList[row][col].background_color = [169, 169, 169]
self.connectFour.reset()
for button in self.btnList:
button.disabled = False
if self.connectFour.whoseTurn() == 1:
button.background_color = [0, 0, 1, 1]
else:
button.background_color = [1, 0, 0, 1]
# Helper function for connectFour's playerMove() function
def playerMoveHelper(self, col, *largs):
# When pressing a control button, if it is the last button in the col, disable the respective control btn
if self.connectFour.getSpotState(1, col) != 0:
self.btnList[col].disabled = True
self.btnList[col].background_color = [0, 0, 0, 1]
x, y = self.connectFour.playerMove(col, self.connectFour.whoseTurn())
self.checkWinner(col)
self.buttonControl(x, y)
# Disable all the control buttons (for use after a player wins)
def disableControlButtons(self):
for button in self.btnList:
button.disabled = True
# Determine who won, and display a popUp
def checkWinner(self, col):
if self.connectFour.isWinner(col, self.connectFour.recentState):
if self.connectFour.recentState == 1:
self.popupWinner = Popup(title="Game Over", content=Label(text="Blue player wins!!"), size_hint=(0.50, 0.50))
self.popupWinner.open()
self.disableControlButtons()
else:
self.popupWinner = Popup(title="Game Over", content=Label(text="Red player wins!!"), size_hint=(0.50, 0.50))
self.popupWinner.open()
self.disableControlButtons()
# Determine which buttons to disable and change color of
def buttonControl(self, x, y):
if self.connectFour.whoseTurn() == 1:
self.boardButtonList[x][y].background_color = [1, 0, 0, 1]
for button in self.btnList:
if not button.disabled:
button.background_color = [0, 0, 1, 1]
else:
self.boardButtonList[x][y].background_color = [0, 0, 1, 1]
for button in self.btnList:
if not button.disabled:
button.background_color = [1, 0, 0, 1]
class ControlWidgets(BoxLayout):
def __init__(self, **kwargs):
super(ControlWidgets, self).__init__(**kwargs)
# Configure ControlWidgets object
self.orientation = 'vertical'
self.spacing = 10
# Define variables for later use
self.quotaWidget = None
self.popup = None
# Create widgets
self.brightnessWidgets = BrightnessWidgets()
self.gameButton = Button(text="Games", halign='center', valign='center')
self.quotaButton = Button(text="View Quota", halign='center', valign='center')
self.menuButton = Button(text="System Menu", halign='center', valign='center')
# Configure buttons
self.quotaButton.bind(on_press=self.openQuotaWidget)
self.menuButton.bind(on_press=self.openSystemMenu)
self.gameButton.bind(on_press=self.openGamesWidget)
# Add widgets to view
self.add_widget(self.brightnessWidgets)
self.add_widget(self.quotaButton)
self.add_widget(self.gameButton)
self.add_widget(self.menuButton)
def openSystemMenu(self, *largs):
self.systemMenuWidget = SystemMenuWidget()
self.popup = Popup(title="System Menu", content=self.systemMenuWidget)
self.systemMenuWidget.closeButton.bind(on_press=self.popup.dismiss)
self.popup.open()
def openGamesWidget(self, *largs):
self.gameWidget = GamesWidget()
self.popup = Popup(title="Games Selection", content=self.gameWidget)
self.gameWidget.closeButton.bind(on_press=self.popup.dismiss)
self.popup.open()
def openQuotaWidget(self, *largs):
# Create QuotaWidget object to display
self.quotaWidget = QuotaWidget()
self.quotaWidget.loadDailyImage()
self.quotaWidget.loadWeeklyImage()
# Display popup
self.popup = Popup(title="Quota Usage", content=self.quotaWidget)
self.quotaWidget.closeButton.bind(on_press=self.closeQuotaWidget)
self.popup.open()
self.quotaWidget.updateImageDisplays()
def closeQuotaWidget(self, *largs):
workingDir = str(subprocess.check_output('pwd'))[2:-3]
subprocess.call(['rm', '%s/dailyQuota.png' % workingDir, '%s/weeklyQuota.png' % workingDir])
self.popup.dismiss()
class RightPane(BoxLayout):
def __init__(self, **kwargs):
super(RightPane, self).__init__(**kwargs)
# Configure RightPane object
self.orientation = 'vertical'
self.spacing = 10
# Create widgets
self.controlWidgets = ControlWidgets()
# Add widgets to view
self.add_widget(self.controlWidgets)
class MiddlePane(BoxLayout):
def __init__(self, **kwargs):
super(MiddlePane, self).__init__(**kwargs)
# Configure MiddlePane object
self.orientation = 'vertical'
self.spacing = 10
# Create widget
self.calendarWidget = CalendarWidget()
# Add widget to view
self.add_widget(self.calendarWidget)
class LeftPane(BoxLayout):
def __init__(self, middlePane, **kwargs):
super(LeftPane, self).__init__(**kwargs)
# Configure LeftPane object
self.orientation = 'vertical'
self.spacing = 10
# Create widgets
self.quoteWidget = QuoteWidget()
self.weatherWidget = WeatherWidget()
self.stockWidget = StockWidget()
timedUpdates = {86400: [self.quoteWidget.timerFun, middlePane.calendarWidget.daySelector.timerFun],
300: [self.stockWidget.timerFun, self.weatherWidget.timerFun],
1800: [middlePane.calendarWidget.timerFun]}
self.timeWidget = TimeWidget(timedUpdates)
# Add widgets to view
self.add_widget(self.timeWidget)
self.add_widget(self.quoteWidget)
self.add_widget(self.weatherWidget)
self.add_widget(self.stockWidget)
class RootLayout(RelativeLayout):
def __init__(self, **kwargs):
super(RootLayout, self).__init__(**kwargs)
# Configure display panes
self.middlePane = MiddlePane(pos_hint={'x': 0.25, 'y': 0}, size_hint=(0.63, 1))
self.rightPane = RightPane(pos_hint={'x': 0.88, 'y': 0}, size_hint=(0.12, 1))
self.leftPane = LeftPane(self.middlePane, pos_hint={'x': 0, 'y': 0}, size_hint=(0.25, 1))
# Add panes to view
self.add_widget(self.leftPane)
self.add_widget(self.middlePane)
self.add_widget(self.rightPane)
class PiDay(App):
def __init__(self, **kwargs):
super(PiDay, self).__init__(**kwargs)
# Initialize presentation manager
self.rootLayout = RootLayout()
def build(self):
return self.rootLayout
def on_start(self):
self.checkLaunch()
# self.rootLayout.middlePane.calendarWidget.authenticate()
def checkLaunch(self):
self.yesButton = Button(text="Yes", on_press=self.launchApp)
self.noButton = Button(text="No", on_press=quitProg)
self.container = BoxLayout(orientation='horizontal')
self.container.add_widget(self.yesButton)
self.container.add_widget(self.noButton)
self.popup = Popup(title="Launch PiDay?", content=self.container)
self.popup.open()
def launchApp(self, *largs):
self.popup.dismiss()
self.rootLayout.middlePane.calendarWidget.authenticate()
# Helper classes and functions
class LoadingIndicator(Popup):
def __init__(self, **kwargs):
super(LoadingIndicator, self).__init__(**kwargs)
self.progressBar = ProgressBar(max=1, value=0)
self.popup = Popup(title="Loading…", content=self.progressBar)
self.popup.open()
def update(self, value):
self.progressBar.value = value
if value == 1:
self.popup.dismiss()
class TwoFactorAuthScreen(Popup):
def __init__(self, calendarWidgetObject, **kwargs):
super(TwoFactorAuthScreen, self).__init__(**kwargs)
self.title = "Two Factor Authentication"
# Initialize variables
self.calendarWidgetObject = calendarWidgetObject
self.device = None
self.container = BoxLayout(orientation='vertical', spacing=15)
self.add_widget(self.container)
self.numberString = ""
self.numberDisplay = Label(text=self.numberString, halign='center', valign='center')
self.container.add_widget(self.numberDisplay)
# Configure each row of buttons
self.firstRow = BoxLayout(orientation='horizontal', spacing=15)
self.oneButton = Button(text='1', valign='center', halign='center')
self.oneButton.bind(on_press=partial(self.numberPressed, 1))
self.firstRow.add_widget(self.oneButton)
self.twoButton = Button(text='2', valign='center', halign='center')
self.twoButton.bind(on_press=partial(self.numberPressed, 2))
self.firstRow.add_widget(self.twoButton)
self.threeButton = Button(text='3', valign='center', halign='center')
self.threeButton.bind(on_press=partial(self.numberPressed, 3))
self.firstRow.add_widget(self.threeButton)
self.secondRow = BoxLayout(orientation='horizontal', spacing=15)
self.fourButton = Button(text='4', valign='center', halign='center')
self.fourButton.bind(on_press=partial(self.numberPressed, 4))
self.secondRow.add_widget(self.fourButton)
self.fiveButton = Button(text='5', valign='center', halign='center')
self.fiveButton.bind(on_press=partial(self.numberPressed, 5))
self.secondRow.add_widget(self.fiveButton)
self.sixButton = Button(text='6', valign='center', halign='center')
self.sixButton.bind(on_press=partial(self.numberPressed, 6))
self.secondRow.add_widget(self.sixButton)
self.thirdRow = BoxLayout(orientation='horizontal', spacing=15)
self.sevenButton = Button(text='7', valign='center', halign='center')
self.sevenButton.bind(on_press=partial(self.numberPressed, 7))
self.thirdRow.add_widget(self.sevenButton)
self.eightButton = Button(text='8', valign='center', halign='center')
self.eightButton.bind(on_press=partial(self.numberPressed, 8))
self.thirdRow.add_widget(self.eightButton)
self.nineButton = Button(text='9', valign='center', halign='center')
self.nineButton.bind(on_press=partial(self.numberPressed, 9))
self.thirdRow.add_widget(self.nineButton)
self.fourthRow = BoxLayout(orientation='horizontal', spacing=15)
self.enterButton = Button(text='Enter', valign='center', halign='center')
self.enterButton.bind(on_press=self.enterButtonPress)
self.fourthRow.add_widget(self.enterButton)
self.zeroButton = Button(text='0', valign='center', halign='center')
self.zeroButton.bind(on_press=partial(self.numberPressed, 0))
self.fourthRow.add_widget(self.zeroButton)
self.deleteButton = Button(text='Delete', valign='center', halign='center')
self.deleteButton.bind(on_press=self.deleteButtonPress)
self.fourthRow.add_widget(self.deleteButton)
self.container.add_widget(self.firstRow)
self.container.add_widget(self.secondRow)
self.container.add_widget(self.thirdRow)
self.container.add_widget(self.fourthRow)
self.open()
self.promptForDevice()
def promptForDevice(self):
devicePrompt = "Your trusted devices are:\n"
devices = self.calendarWidgetObject.icloudApi.trusted_devices
for i, device in enumerate(devices):
devicePrompt += "[%d] %s\n" % (i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber')))
devicePrompt += "Which device would you like to use?"
self.displayMessage(devicePrompt)
deviceNum = 0
self.device = devices[deviceNum]
if not self.calendarWidgetObject.icloudApi.send_verification_code(self.device):
self.displayMessage("Failed to send verification code")
time.sleep(3)
exit()
self.displayMessage('Please enter validation code')
def displayMessage(self, message):
self.numberDisplay.text = message
def numberPressed(self, num, *largs):
self.addDigitToString(num)
def enterButtonPress(self, *largs):
if not self.calendarWidgetObject.icloudApi.validate_verification_code(self.device, self.numberString):
self.displayMessage("Failed to verify verification code")
time.sleep(3)
exit()
self.calendarWidgetObject.finishInitSetup()
self.dismiss()
def deleteButtonPress(self, *largs):
self.numberString = self.numberString[:-1]
self.numberDisplay.text = self.numberString
def addDigitToString(self, digit):
self.numberString += str(digit)
self.numberDisplay.text = self.numberString
def getTimeToMidnight():
now = datetime.now()
tomorrow = datetime(now.year, now.month, now.day) + timedelta(1)
return abs(tomorrow - now).seconds * 1000 + 1000
def makeHTTPRequest(url):
response = ""
try:
r = urllib.request.urlopen(url)
response = r.read().decode('utf-8')
r.close()
except:
response = False
return response
def quitProg(*largs):
quit()
def rebootPi(*largs):
workingDir = str(subprocess.check_output('pwd'))[2:-3]
subprocess.call(['rm', '%s/dailyQuota.png' % workingDir, '%s/weeklyQuota.png' % workingDir])
subprocess.call(['sudo', 'reboot'])
# Start the program
if __name__ == "__main__":
subprocess.call(['sudo', 'chmod', '666', '/sys/class/backlight/rpi_backlight/brightness'])
# We need to keep a reference to the PiDay object so it is not garbage collected
# If the object is garbage collected then the schedule calls will not work
app = PiDay()
app.run()
| true |
8515e26c8d068a91dd384f4db5c00a070f122266 | Python | johancastillo/mixtura-backend | /run.py | UTF-8 | 448 | 2.828125 | 3 | [] | no_license | # Import micro Framework Flask
from flask import Flask
# Intance of Flask class
app = Flask(__name__)
# Home page
@app.route('/')
def index():
return 'Hello world with Flask server'
# About page
@app.route('/about')
def about():
return 'It is page of about'
# Services page
@app.route('/services')
def services():
return 'It is page of services'
# Run application
if __name__ == "__main__":
app.run( debug = True, port = 8000 ) | true |
6307a22cd97416c69b4a0ba47ecc6138aa972732 | Python | joquizon/Python-Class | /EmployeeDataBaseProject/openerLoader.py | UTF-8 | 2,941 | 3 | 3 | [] | no_license | def clearscreen():
import os
from os import system
clear = lambda: system('cls')
clear()
# noclist is list
#elist is big giant nocmemlist
# nocmemlist =[]
# x = 'noclist'
def employeeloader(nlist,elist):
from cryptography.fernet import Fernet
fkey = open('testdocs/niterun/filekeyMain.night','rb')
key = fkey.read()
cipher = Fernet(key)
with open('testdocs/noclist.night','rb') as df:
encryptedfile = df.read()
decrypted_file = cipher.decrypt(encryptedfile)
stringnlist = (decrypted_file.decode()).splitlines()
for sm in range(len(stringnlist)):
nlist.append(stringnlist[sm])
for emp in range(len(stringnlist)):
from cryptography.fernet import Fernet
fkey = open('testdocs/niterun/filekeyMain.night','rb')
key = fkey.read()
cipher = Fernet(key)
search = stringnlist[emp]
with open('testdocs/'+search+'.night','rb') as et:
encryptedfileA = et.read()
decrypted_fileA = cipher.decrypt(encryptedfileA)
with open('testdocs/'+search+'sickdates.night','rb') as ms:
encryptedfileB = ms.read()
decrypted_fileB = cipher.decrypt(encryptedfileB)
with open('testdocs/'+search+'persdates.night','rb') as lm:
encryptedfileC = lm.read()
decrypted_fileC = cipher.decrypt(encryptedfileC)
with open('testdocs/'+search+'vacdates.night','rb') as nh:
encryptedfileD = nh.read()
decrypted_fileD = cipher.decrypt(encryptedfileD)
load = (decrypted_fileA.decode()).splitlines()
load2 = (decrypted_fileB.decode()).splitlines()
load3 = (decrypted_fileC.decode()).splitlines()
load4 = (decrypted_fileD.decode()).splitlines()
elist.append(load)
elist.append(load2)
elist.append(load3)
elist.append(load4)
# >>>>>>>>>>>>>>>>>>>>>>>Edits noclist basically fires employees
def terminator(list):
for x in range(len(list)):
print(f"{x}....{list[x]}")
connor = input('typed the line no. of the employee you wish to tuhminate or if termination is over type <*>:')
if connor == '*':
print('Termination Over')
else:
while True:
try:
connorno = int(connor)
if connorno <= len(list):
clearscreen()
print(f'hasta la vista {list[connorno]}')
list.pop(connorno)
for x in range(len(list)):
print(f"{x}....{list[x]}")
terminator(list)
else:
print('nooooo')
terminator(list)
except ValueError :
print('Exceptumondo Dude! this thing just takes numbers!!!Try again!')
terminator(list)
break
else:
break
| true |
fa86eb845209a1498bceb8694521456bfc092704 | Python | cjrzs/MyLeetCode | /区域和检索 - 数组不可变.py | UTF-8 | 557 | 3.421875 | 3 | [] | no_license | """
coding: utf8
@time: 2021/3/1 21:29
@author: cjr
@file: 区域和检索 - 数组不可变.py
题目链接:https://leetcode-cn.com/problems/range-sum-query-immutable/
"""
from typing import List
class NumArray:
def __init__(self, nums: List[int]):
self.nums = [0] + nums
f = [0] * (len(self.nums) + 1)
f[0] = self.nums[0]
for i in range(1, len(self.nums)):
f[i] = self.nums[i] + f[i - 1]
self.f = f
def sumRange(self, i: int, j: int) -> int:
return self.f[j + 1] - self.f[i]
| true |