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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
db6d9a9738e33b6a2044cd6d8dcbb6691356b205 | Python | rafeeknehad/fake-news | /final model/Embedding.py | UTF-8 | 1,769 | 2.609375 | 3 | [] | no_license | from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
import pandas as pd
import preprocessing
import csv
import pandas as pd
# def doc2vec_Fun ():
# df = pd.read_excel('fake_new_dataset.xlsx')
# df.title = df.title.astype(str)
# df.text = df.text.astype(str)
# df['news'] = df['title'] + df['text']
# df.drop(labels=['title', 'text'], axis=1, inplace=True)
# df.drop(labels=['subcategory'], axis=1, inplace=True)
# list_label =[df['label']]
# doc = []
# for item in df['news']:
# item = preprocessing.text_preprocessing(item)
# doc.append(item)
# tokenized_doc = []
# for d in doc:
# tokenized_doc.append(word_tokenize(d.lower()))
# tagged_data = [TaggedDocument(d, [i]) for i, d in enumerate(tokenized_doc)]
# model=Doc2Vec(tagged_data,vector_size=100,window=2, min_count=1,workers=4,epochs=100)
# list_data = []
# for index in range(0,len(model.dv)):
# list_data.append(model.dv[index])
# return list_data,list_label
def get_data():
df = pd.read_excel(r'D:\5May\Fake-news-detection-with-covid-19-20210504T230623Z-001\Fake-news-detection-with-covid-19\fake_new_dataset.xlsx')
df.title = df.title.astype(str)
df.text = df.text.astype(str)
df['news'] = df['title'] + df['text']
df.drop(labels=['title', 'text'], axis=1, inplace=True)
df.drop(labels=['subcategory'], axis=1, inplace=True)
return df['label']
def get_data2():
dataSetObject = open(r'D:\5May\Fake-news-detection-with-covid-19-20210504T230623Z-001\Fake-news-detection-with-covid-19\english_test_with_labels.csv', 'rt')
myreader = csv.reader(dataSetObject)
listOfData = list(myreader)
return listOfData | true |
7d9601a8f3ca073c7f615f15cc2377a27c4a847d | Python | wongcyrus/ite3101_introduction_to_programming | /lab/lab16/ch016_t13_lambda_syntax.py | UTF-8 | 116 | 2.6875 | 3 | [] | no_license | languages = ["HTML", "JavaScript", "Python", "Ruby"]
# Add arguments to the filter()
print(list(filter([], None)))
| true |
4265211d453636a55e10a8510ec3acb22e63f605 | Python | Joseuiltom/jogo-da-forca | /jogo_forca.py | UTF-8 | 6,575 | 3.328125 | 3 | [] | no_license | #importa a função para escolher uma das palavras
from random import choice
#importa o modulo tkinter
from tkinter import *
#importa o partial
from functools import partial
#escolhe qual dos temas vai ser sorteado
temas = ['animais','comidas',]
tema = choice(temas)
#escolhe qual palavra vai ser sorteada
animais = ['soinho','galinha','vaca','gato','girafa']
comidas = ['melancia','peixe','manga','bolacha','feijao']
if tema == 'animais':
palavra = choice(animais)
elif tema == 'comidas':
palavra = choice(comidas)
palavra2 = palavra
palavra = list(palavra.upper())
palavra_aux = []
palavra_aux2 = palavra.copy()
for letra in range(len(palavra)):
palavra_aux.append('_')
existentes = []
errados = []
#cria a lista com nossas letras
alfabeto = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
#cria a classe do nosso programa
class jogo_forca(object):
"""
classe que contém todo o nosso programa.
e a sua logica
"""
#inicializa nossos atributos
def __init__(self,i):
#atributo para verificar se a palavra ja foi terminada
self.aux = False
#cria o frame que contem o texto com o tema do jogo
self.frame1 = Frame(i)
self.frame1['bg'] = 'white'
self.frame1['pady'] = 10
self.frame1.pack()
#cria o frame que contém a imagen do jogo da forca
self.frame2 = Frame(i)
self.frame2['pady'] = 20
self.frame2['bg'] = 'white'
self.frame2.pack()
#frame com as palavras existentes erradas
self.frame_letras = Frame(i)
self.frame_letras['pady'] = 10
self.frame_letras['bg'] = 'white'
self.frame_letras.pack()
#cria o frame do texto com as letras da palavra escolhida
self.frame3 = Frame(i)
self.frame3['bg'] = 'white'
self.frame3.pack()
#frame dos botões
self.frame4 = Frame(i)
self.frame4['bg'] = 'white'
self.frame4['pady'] = 10
self.frame4.pack()
#cria a frame com o resultado das ações do usuário
self.frame5 = Frame(i)
self.frame5['bg'] = 'white'
self.frame5.pack()
#cria nossos sprites para ser ultilizados no nosso jogo
self.sprite1 = PhotoImage(file='imagens/imagem_1.ppm')
self.sprite2 = PhotoImage(file='imagens/imagem_2.ppm')
self.sprite3 = PhotoImage(file='imagens/imagem_3.ppm')
self.sprite4 = PhotoImage(file='imagens/imagem_4.ppm')
self.sprite5 = PhotoImage(file='imagens/imagem_5.ppm')
self.sprite6 = PhotoImage(file='imagens/imagem_6.ppm')
self.sprite7 = PhotoImage(file='imagens/imagem_7.ppm')
#widget do tema do jogo
self.texto_tema = Label(self.frame1,text=f'Tema:\n{tema} ',fg='green',bg='white',font=('Verdana',20,'bold'))
self.texto_tema.pack()
#widget da imagem do jogo da forca
self.imagem1 = Label(self.frame2)
self.imagem1['image'] = self.sprite1
self.imagem1.imagem = self.sprite1
self.imagem1.pack(side=LEFT)
#widget das palavras existentes e as erradas
self.texto_ex = Label(self.frame_letras,text=f'Existentes: {existentes}',bg='white',fg='green',font=('Verdana',15,'bold'))
self.texto_ex.pack(side=LEFT)
self.texto_er = Label(self.frame_letras,text=f'Errados: {errados}',bg='white',fg='green',font=('Verdana',15,'bold'))
self.texto_er.pack(side=LEFT)
self.mudar_ex()
self.mudar_er()
#widget do texto da palavra escolhida
letras = ''
for letra in palavra_aux:
letras += letra + ' '
self.texto1 = Label(self.frame3,text=letras,fg='green',bg='white',font=('Verdana',25,'bold'))
self.texto1.pack()
#cria os nossos botões
self.cont = 0
for i in range(len(alfabeto)):
if i % 5 == 0:
subframe = Frame(self.frame4)
subframe['padx'] = 5
subframe['bg'] = 'white'
subframe.pack()
a = Button(subframe,text=alfabeto[i],fg='green',width=10,command=partial(self.inserir,alfabeto[i]))
a.pack(side=LEFT)
#cria o widget do texto do resultado das ações do usuário
self.texto2 = Label(self.frame5,text='',bg='white',fg='green',font=('Verdana',25,'bold'))
self.texto2.pack()
#cria o metodo para inserir a palavra digitada
def inserir(self,letra):
if self.cont >= 6 or letra in existentes or '_' not in palavra_aux:
return
if letra in palavra:
for caractere in range(0,len(palavra)):
if letra == palavra[caractere]:
palavra_aux[caractere] = letra
self.mudar()
existentes.append(letra)
self.mudar_ex()
if '_' not in palavra_aux:
self.texto2['text'] = 'Parabéns você ganhou!'
else:
self.cont += 1
errados.append(letra)
self.mudar_er()
if self.cont == 1:
self.imagem1['image'] = self.sprite2
self.imagem1.imagem = self.sprite2
elif self.cont == 2:
self.imagem1['image'] = self.sprite3
self.imagem1.imagem = self.sprite3
elif self.cont == 3:
self.imagem1['image'] = self.sprite4
self.imagem1.imagem = self.sprite4
elif self.cont == 4:
self.imagem1['image'] = self.sprite5
self.imagem1.imagem = self.sprite5
elif self.cont == 5:
self.imagem1['image'] = self.sprite6
self.imagem1.imagem = self.sprite6
elif self.cont == 6:
self.imagem1['image'] = self.sprite7
self.imagem1.imagem = self.sprite7
self.texto2['text'] = f'Você perdeu!! a palavra era {palavra2}'
self.texto2['fg'] = 'red'
#metodo para mudar o texto da palavra
def mudar(self):
letras = ''
for letra in palavra_aux:
letras += letra + ' '
self.texto1['text'] = letras
def mudar_ex(self):
self.texto_ex['text'] = f'Existentes: {existentes}'
def mudar_er(self):
self.texto_er['text'] = f'Errados: {errados}'
#cria as nossa janela e define as coisas iniciais
janela = Tk()
jogo_forca(janela)
janela.title('Jogo da forca')
janela.geometry('800x600')
janela['bg'] = 'white'
janela.mainloop()
| true |
87b288a32257a98d319f4c7844f1746cbd82af4a | Python | benjazor/project-euler | /Python/005_Smallest_multiple.py | UTF-8 | 1,495 | 4.40625 | 4 | [
"MIT"
] | permissive | '''
2520 is the smallest number that can be divided by
each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly
divisible by all of the numbers from 1 to 20?
'''
# VERSION 1 : Works 'great' for 10 but too slow for 20
def smallest_multiple(number):
mult = 0
while True:
print(mult)
mult += 1
isOk = True
for i in range(1, number):
if mult % i != 0:
isOk = False
break
if isOk:
break
return mult
# print( smallest_multiple(20) )
def isPrime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
# Version 2: Uses prime numbers, works fine for 20 and 100 but 1000 is too slow
def smallestMultiple(number):
# Take all the prime numbers
primeNumbers = []
for i in range(2, number):
if isPrime(i):
primeNumbers.append(i)
# Multiply all the prime numbers
multiple = 1
for primeNumber in primeNumbers:
multiple *= primeNumber
# Find the smallest multiple
i = 0
while True:
i += 1
newMultiple = multiple * i
# Check if the number is a multiple of all numbers bellow
isOk = True
for j in range(1, number):
if newMultiple % j != 0:
isOk = False
break
if isOk:
return newMultiple
print( smallestMultiple(1000) )
| true |
b73266db894ccd2e4b93e68a8f0ce21b0fa09f5e | Python | tcheng878/DailyAlgos | /set_matrix_zeros.py | UTF-8 | 620 | 3 | 3 | [] | no_license | class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
lis = []
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if matrix[row][col] == 0:
lis.append([row, col])
for i in range(len(lis)):
for j in range(len(matrix)):
matrix[j][lis[i][1]] = 0
for j in range(len(matrix[0])):
matrix[lis[i][0]][j] = 0 | true |
0e36cc2bdcc833d571ddc6affb200468a66719b5 | Python | TBBLresearchInc/PAF | /grid.py | UTF-8 | 2,350 | 3.28125 | 3 | [] | no_license | __author__ = "quentinleroy"
# Quentin Leroy
# Pour le Tableur Logique, outil d'elucidation de conflits logiques
# quentin.leroy@telecom-paristech.fr
class Grid:
""" Classe decrivant le tableau du point de vue de l'application web
"""
grid = {}
grid_coords = []
def __init__(self):
self.grid = {}
self.grid_coords = []
# Ajoute ou edite une cellule
# Appelee a chaque requete POST sur l'URL /py/json
def update(self, row, column, content, color="wrong"):
"""
:param row: ligne de la cellule
:param column: colonne de la cellule
:param content: chaine de caractere que contient la cellule
"""
coords = (row, column)
self.grid[coords] = {"content": content, "row": row, "column": column, "color": color}
if not((row, column) in self.grid_coords):
self.grid_coords.append(coords)
# Renvoie le contenu d'une cellule en specifiant en arguments la ligne et la colonne
def get_cell_content(self, row, column):
coords = (row, column)
return self.grid[coords]["content"]
# Renvoie les coordonnes de la cellule placee a l'adresse index
# Utilse quand on parcourt le tableau dans l'ordre chronologique de saisie des cellules
def get_coords(self, index):
return self.grid_coords[index]
# Permet de supprimer une cellule du tableau en specifiant en arguments la ligne et la colonne
# Utile quand l'utilisateur a rentre du texte dans une cellule mais qu'il a par la suite decide de la laisser vide
def delete_cell(self, row, column):
coords = row, column
self.grid.__delitem__(coords)
index = 0
for i in range(0, len(self.grid_coords)):
if self.grid_coords[i] == (row, column):
index = i
self.grid_coords.pop(index)
def get_color(self, row, column):
coords = (row, column)
return self.grid[coords]["color"]
def set_color(self, row, column, color):
coords = (row, column)
self.grid[coords]["color"] = color
# Renvoie le nombre de cellules saisies
def nb_of_cells(self):
return len(self.grid_coords)
def toStr(self):
return str(self.grid)
# Appelee lors du chargement de la page web cote client
def reset(self):
self.grid = {}
self.grid_coords = []
| true |
51800f085b029777305a2ccb425d58615f48caad | Python | ubuntox84/Python-2021 | /Semana10/ejer3.py | UTF-8 | 245 | 3.40625 | 3 | [] | no_license | #lista[5,4,8,7,6,7,7], sumar y mostrar
lista=[5,4,8,[2,[2,5,6],4],6,4,1]
n=len(lista)
cad=" "
def listar (lista):
for n in lista:
if isinstance(n,list):
listar(n)
else:
print(n,end=" ")
listar(lista) | true |
d51e177ac99484e5f4da3fcad9ac248eea7b6607 | Python | ANTRIKSH-GANJOO/-HACKTOBERFEST2K20 | /Python/Projects/invisible_cloak.py | UTF-8 | 3,164 | 3.21875 | 3 | [
"Apache-2.0"
] | permissive | import cv2
import numpy as np
import time
# replace the red pixels ( or undesired area ) with
# background pixels to generate the invisibility feature.
## 1. Hue: This channel encodes color information. Hue can be
# thought of an angle where 0 degree corresponds to the red color,
# 120 degrees corresponds to the green color, and 240 degrees
# corresponds to the blue color.
## 2. Saturation: This channel encodes the intensity/purity of color.
# For example, pink is less saturated than red.
## 3. Value: This channel encodes the brightness of color.
# Shading and gloss components of an image appear in this
# channel reading the videocapture video
# in order to check the cv2 version
print(cv2.__version__)
# taking video.mp4 as input.
# Make your path according to your needs
capture_video = cv2.VideoCapture("video.mp4")
# give the camera to warm up
time.sleep(1)
count = 0
background = 0
# capturing the background in range of 60
# you should have video that have some seconds
# dedicated to background frame so that it
# could easily save the background image
for i in range(60):
return_val, background = capture_video.read()
if return_val == False :
continue
background = np.flip(background, axis = 1) # flipping of the frame
# we are reading from video
while (capture_video.isOpened()):
return_val, img = capture_video.read()
if not return_val :
break
count = count + 1
img = np.flip(img, axis = 1)
# convert the image - BGR to HSV
# as we focused on detection of red color
# converting BGR to HSV for better
# detection or you can convert it to gray
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
#-------------------------------------BLOCK----------------------------#
# ranges should be carefully chosen
# setting the lower and upper range for mask1
lower_red = np.array([100, 40, 40])
upper_red = np.array([100, 255, 255])
mask1 = cv2.inRange(hsv, lower_red, upper_red)
# setting the lower and upper range for mask2
lower_red = np.array([155, 40, 40])
upper_red = np.array([180, 255, 255])
upper_red = np.array([100, 255, 255])
mask2 = cv2.inRange(hsv, lower_red, upper_red)
#----------------------------------------------------------------------#
# the above block of code could be replaced with
# some other code depending upon the color of your cloth
mask1 = mask1 + mask2
# Refining the mask corresponding to the detected red color
mask1 = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((3, 3),
np.uint8), iterations = 2)
mask1 = cv2.dilate(mask1, np.ones((3, 3), np.uint8), iterations = 1)
mask2 = cv2.bitwise_not(mask1)
# Generating the final output
res1 = cv2.bitwise_and(background, background, mask = mask1)
res2 = cv2.bitwise_and(img, img, mask = mask2)
final_output = cv2.addWeighted(res1, 1, res2, 1, 0)
cv2.imshow("INVISIBLE MAN", final_output)
k = cv2.waitKey(10)
if k == 27:
break
| true |
05d3f6da691791f78e1befd9b2853be9717586eb | Python | OlyaIvanovs/python_cookbook | /chapter2/parser.py | UTF-8 | 277 | 3.28125 | 3 | [] | no_license | # Parse text according to a set of grammar rules and perform actions
# or build an abstract syntax tree representing the input.
import time
import cProfile
def addUpNumbers():
total = 0
for i in range(1, 1000001):
total += i
cProfile.run('addUpNumbers()')
| true |
7fefa5c0e2a8667b7f8c0df3577073c7a6f22c1f | Python | xd-lpc/sharemylove | /ex43.py | UTF-8 | 3,982 | 3.265625 | 3 | [] | no_license | from sys import exit
from random import randint
class Scene(object):
def enter(self):
print("This scene is not ye configured. Subclass it and implement enter()")
exit(1)
class Engine(object):
def __init__(self,scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.open_sence()
while True:
print("\n----------------------")
next_sence_name = current_scene.enter()
current_scene = self.scene_map.next_sence(next_sence_name)
class Deth(Scene):
quips = [
"you died, you kinda suck at this",
"you mom would be proud...if she were smarter",
"Oh! I'm sorry you died again",
"Such a luser"
]
def enter(self):
print (self.quips[randint(0,(len(self.quips)-1))])
exit(1)
class CentralCorridor(Scene):
def enter(self):
print("由于野生狗熊星人悄悄入侵飞船,飞船里的同胞毫无准备,惨遭屠杀")
print("你因为半夜起来尿尿,躲过一劫,现在你逃到了飞船的中央走廊里")
print("你计划先跑到武器库去找到炸弹,将狗熊星人干死")
print("正当你快要到武器库时,狗熊星人突然出现了")
print("这时,你会")
action = input("> ")
if action == '射爆':
print ("狗熊星人皮糙肉厚,你只开了两枪,就被一巴掌扇死了")
return 'death'
elif action == '逃跑':
print("由于你长期缺乏锻炼,跑不过狗熊,被追上干死")
return 'death'
elif action == '聊天':
print("你急中生智,背诵24字核心价值观,狗熊震惊了,没想到还有这种操作")
print("你趁机溜到武器库")
return 'Lasser_WeaponArmory'
else:
return 'Central_Corridor'
class LasserWeaponArmory(Scene):
def enter(self):
print("在武器库你疯狂找炸弹中,门外的狗熊也渐渐清醒过来,开始猛烈撞门")
print("留给你的时间不多了")
print("这时,你突然发现一个装着炸弹的箱子,但是需要输入三位数的密码")
print("你的输入是")
code = "%d%d%d" % (randint(1,9),randint(1,9),randint(1,9))
print(code)
guess = input("> ")
guesses = 0
while guess != code and guesses <10:
print ("密码错误!!!!!!")
guesses += 1
guess = input("> ")
if guess == code :
print("你迅速抱着炸弹跑向飞船的指挥室")
return "The_Bridge"
else:
print("狗熊撞开了门,你被干死了")
return 'death'
class TheBridge(Scene):
def enter(self):
print("跑到指挥室后,狗熊也跟了过来,这时你抱着炸弹")
action = input("> ")
if action == '扔向狗熊':
print("炸弹在空中爆炸,你也被炸死了")
return 'death'
elif action == '把炸弹放在地上':
print("狗熊好奇的抱起来,然后被炸死")
print("飞船也无法继续飞行了,你必须坐救生仓离开")
return "EscapePod"
class EscapePod(Scene):
def enter(self):
print ("go home!!!")
class Map(object):
senes = {
'Central_Corridor':CentralCorridor(),
'Lasser_WeaponArmory':LasserWeaponArmory(),
'The_Bridge':TheBridge(),
'EscapePod':EscapePod(),
'death':Deth()
}
def __init__(self,start_sence):
self.start_sence = start_sence
def next_sence(self,scene_name):
return Map.senes.get(scene_name)
def open_sence(self):
return self.next_sence(self.start_sence)
a_map = Map("Central_Corridor")
a_game = Engine(a_map)
a_game.play()
#a_test = CentralCorridor()
#a_test.enter()
| true |
ebb1a3b00d867a76ed510032a2ba42dcc160a2ca | Python | elijahmolloy/RedditScraper | /RedditScript.py | UTF-8 | 4,360 | 3.046875 | 3 | [] | no_license | import praw
from psaw import PushshiftAPI
from datetime import datetime
import csv
import time
#########################################################################
# Use pip to install the following two libraries :
# $ pip install psaw
# $ pip install praw
# In order for this script to run, you will have to obtain an ID and a SECRET key from the following website
# <https://www.reddit.com/prefs/apps>
# Scroll to the bottom of this screen and click the button that says :
# "are you a developer? create an app..."
# For the name, please enter "Comment Scraper"
# Please ensure that "script" is selected for the application category
# For the description, please enter "Search RedditSearch.io for comments that contain a specific string"
# For the redirect uri, please enter "http://localhost:8080"
# Click the "create app" button and look for the following two sections on the following screen
# At the top of the screen, you'll see a section with the following text :
# personal use script
# a346ovYDiTKG-h
# Take this random id and copy and paste into the "client_id" property on line 34 of this .py file
# You will also see a line that looks like the following :
# secret A-8351aJ2_P9e1Bk69lvgpLxpgk
# Take this random secret and copy and paste into the "client_secret" property on line 35 of this .py file
client_id = "a346ovYDiTKG-h"
client_secret = "A-8351aJ2_P9e1Bk69lvgpLxpgk"
user_agent = "Comment Scraper"
sub_reddit_string = "nyc"
string_to_search_for = "climate change"
#########################################################################
# Create Reddit client
reddit_client = praw.Reddit(client_id=client_id,
client_secret=client_secret,
user_agent=user_agent)
# Create Pushshift client and obtain comment id's
pushshift_client = PushshiftAPI(reddit_client)
gen_comments = pushshift_client.search_comments(subreddit=sub_reddit_string,
q=string_to_search_for,
limit=None)
# Start timer
start = time.time()
print("\nGathering comments from Pushshift API")
# Create dictionary of all comments retrieved from Pushshift
comments_dict = {}
for comment in gen_comments:
if comment.id not in comments_dict:
comments_dict[comment.id] = comment
# Display info via terminal
print("\n{} comments found in r/{} containing the text : {}".format(len(comments_dict), sub_reddit_string,
string_to_search_for))
hours, rem = divmod(time.time()-start, 3600)
minutes, seconds = divmod(rem, 60)
print("Time to gather comments: {:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds))
file_name = "{}-{}-{}.csv".format(sub_reddit_string,
string_to_search_for,
datetime.now().strftime("%d_%m_%Y-%H_%M_%S"))
# Initialize and open .csv file for data to be written to
with open(file_name, mode='w') as csv_file:
print("\nGathering comment and post information from Reddit API")
csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
search_index = 1
csv_index = 0
# Attempt to add comment's info to .csv file
for comment in comments_dict.values():
print("\t{} of {}".format(search_index, len(comments_dict)))
search_index += 1
try:
csv_writer.writerow([
str(datetime.fromtimestamp(comment.submission.created_utc).strftime('%Y-%m-%d %H:%M:%S')),
str(comment.submission.score),
str(comment.submission.title),
str(comment.submission.permalink),
str(datetime.fromtimestamp(comment.created_utc).strftime('%Y-%m-%d %H:%M:%S')),
str(comment.score),
str(comment.body),
str(comment.permalink)
])
csv_index += 1
except:
print("Error writing info to .csv")
# Display info via terminal
print("\nFile complete : {}".format(file_name))
print("\t{} objects in .csv".format(str(csv_index)))
# Display info via terminal
hours, rem = divmod(time.time()-start, 3600)
minutes, seconds = divmod(rem, 60)
print("\nTotal Time : {:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds))
| true |
c3a60c2d15a22007056cc1fe97735accc344d84b | Python | ivanbabaiev/py_dev_ib | /students/models.py | UTF-8 | 1,103 | 2.65625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from django.db import models
class Student(models.Model):
class Meta:
db_table = 'students'
verbose_name = 'Student'
verbose_name_plural = 'Students'
name = models.CharField(verbose_name='Имя', max_length=50) # Имя
surname = models.CharField(verbose_name='Фамилия', max_length=50) # Фамилия
father_name = models.CharField(verbose_name='Отчество', blank=True, max_length=50) # Отчество
date_of_birth = models.DateField(verbose_name='День рождения', default=0) # День рождения
student_card = models.CharField(verbose_name='Студенческий билет', max_length=50) # Студенческий билет
group = models.ForeignKey('group.Group', null=True, blank=True, verbose_name='Группа студента') # Группа студента
def get_name(self):
return "%s %s %s" % (self.surname, self.name, self.father_name)
def __str__(self):
return u"{0} {1} {2}".format(self.surname, self.name, self.father_name, ) | true |
ba56ed0a34b02cdf4464d8c5e3e67f4868a64057 | Python | k1ngk0sm0/timesheet | /app.py | UTF-8 | 3,571 | 2.921875 | 3 | [] | no_license | from flask import Flask, render_template, request, flash
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from helpers import usd, f_format
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///payroll.db'
app.secret_key = 'hello'
# Initialize db
db = SQLAlchemy(app)
# Create table to store timesheets
class Timesheet(db.Model):
id = db.Column(db.Integer, primary_key=True)
pay_period = db.Column(db.Text)
time_in = db.Column(db.DateTime)
time_out = db.Column(db.DateTime, default=datetime.now())
hours = db.Column(db.Float, default=0.0)
# Custom filters
app.jinja_env.filters["usd"] = usd
app.jinja_env.filters["f_format"] = f_format
# Initialize clocked in variable from .txt file(0|1 bool)
with open('clocked_in', 'r') as F:
clocked_in = bool(int(F.read()))
@app.route('/')
def index():
return render_template("index.html")
@app.route('/clock_in')
def clock_in():
"""Clock in and add row to Timesheet table"""
global clocked_in
if not clocked_in:
row = Timesheet(time_in=datetime.now(), pay_period=datetime.now().strftime('%b %y'))
db.session.add(row)
db.session.commit()
# Reset clocked_in variable
clocked_in = True
with open('clocked_in', 'w') as F:
F.write('1')
# Return success message to user
time_in = row.time_in.strftime("%c")
return render_template('message.html', time=time_in, status="In")
else:
flash('You are arleady clocked in', 'info')
return render_template('index.html')
@app.route('/clock_out')
def clock_out():
"""Clock in and update current row of Timesheet table"""
try:
row = Timesheet.query.filter_by(hours=0.0).first()
row.time_out = datetime.now()
row.hours = ((row.time_out - row.time_in).total_seconds()) / 60 / 60
db.session.commit()
# Change clocked_in status to False
global clocked_in
clocked_in = False
with open('clocked_in', 'w') as F:
F.write('0')
# Return success message to user
time_out = row.time_out.strftime("%c")
return render_template('message.html', time=time_out, status="Out")
except AttributeError:
flash('You are already clocked out!', 'info')
return render_template('index.html')
@app.route('/history', methods=["GET", "POST"])
def history():
"""Choose and display selected timesheet"""
if request.method == 'GET':
pay_periods = ['Apr 20']
for row in Timesheet.query.all():
if row.pay_period not in pay_periods:
pay_periods.append(row.pay_period)
return render_template('history.html', pay_periods=pay_periods)
else:
# Initialize total hours, rate and pay period
pay_period = Timesheet.query.filter_by(pay_period=request.form.get('pay_period'))
total_hours = 0.0
rate = 12.0
# Format pay period data for display and store in list of dicts
formatted = []
for row in pay_period:
total_hours += row.hours
d = {}
d['date'] = row.time_in.strftime('%m/%d/%y')
d['time_in'] = row.time_in.strftime('%I:%M %p')
d['time_out'] = row.time_out.strftime('%I:%M %p')
d['hours'] = row.hours
formatted.append(d)
return render_template('pay_period.html', pay_period=formatted, total_hours=total_hours, rate=rate, pay=total_hours * rate)
if __name__ == "__main__":
app.run() | true |
373b80da959b4ffe1fd57eac99a7abf9d3a1004e | Python | hamletv/web_scraper | /scraper.py | UTF-8 | 742 | 3.25 | 3 | [] | no_license | # import libraries
import urllib2
from bs4 import BeautifulSoup
import csv
from datetime import datetime
# get url
getpage = "http://www.bloomberg.com/quote/SPX:IND"
# get HTML of variable getpage/url
page = urllib2.urlopen(getpage)
# parse html w/bs and store in var
soup = BeautifulSoup(page, 'html.parser')
# take out the <div> of name and get its value
name_box = soup.find("h1", attrs = {"class": "name"})
name = name_box.text.strip()
print name
# get index price
price_box = soup.find("div", attrs = {"class":"price"})
price = price_box.text
print price
# open csv file with append, old data not erased
with open("index.csv", "a") as csv_file:
writer = csv.writer(csv_file)
writer.writerow([name, price, datetime.now()])
| true |
69f1daa7c28129f8d635d5d714d24f83dc441d1c | Python | PetteriPulkkinen/RLibPy | /rlibpy/agent/q_learning.py | UTF-8 | 4,625 | 3.109375 | 3 | [] | no_license | from rlibpy.agent.base_agent import BaseAgent
from rlibpy.policy.base_policy import BasePolicy
import pickle
import gym
import numpy as np
import os
class QLearningAgent(BaseAgent):
def __init__(self, environment: gym.Env, policy: BasePolicy, gamma: float, alpha=None, omega=None, debug=False):
"""Q-learning algorithm with various different enhancements.
Enhancement 1:
By defining omega in [0, 1] the adaptivity of the alpha parameter is enabled. The adaptivity is based on
calculating empirical mean (when omega=1) of the rewards for each state-action pair. To prevent unwanted
behaviour alpha should be None to explicitly tell to use adaptive alpha.
Enhancement 2:
This class supports at the moment two different exploration strategies. Those strategies are
* Epsilon greedy exploration, and
* Upper Confidence bounds
The latter strategy should be used only when the algorithm is myopic (gamma=0, omega=1).
:param environment: OpenAI gym environment
:param policy: Exploration policy
:param gamma: Discount rate
:param alpha: Learning rate (default None)
:param omega: Decay factor for learning rate (1:='calculate empirical mean', 0:='alpha=1') (default None)
:param debug: Set True if convergence data need to be saved, otherwise False (default False)
"""
assert (alpha is not None) is not (omega is not None), "Either alpha or omega should be defined, define " \
"at most one of them, not both"
super().__init__(environment, policy, debug)
self.environment = environment
self.policy = policy
self.alpha = alpha
self.omega = omega
self.gamma = gamma
shape = (environment.observation_space.n, environment.action_space.n)
self.table = np.zeros(shape=shape, dtype=float)
self.n_table = np.zeros(shape=shape, dtype=int)
self.q_hd = np.empty(shape=shape, dtype=object) # Historical data of Q-values
self.t_hd = np.empty(shape=(
environment.observation_space.n,
environment.observation_space.n,
environment.action_space.n), dtype=object)
self._initialize_covergence_analytics()
self._initialize_transition_analytics()
def act(self, observation, evaluate=False):
values = self.table[observation]
return self.policy.choose(values, observation, evaluate=evaluate)
def update(self, action, observation, next_observation, reward):
next_act = self.act(next_observation, evaluate=True)
next_q = self.table[next_observation, next_act]
current_q = self.table[observation, action]
if self.omega is None:
alpha = self.alpha
else:
alpha = 1/((1+self.n_table[observation, action])**self.omega)
self.table[observation, action] = current_q + alpha * (reward + self.gamma * next_q - current_q)
self.n_table[observation, action] += 1 # count the updates
if self.debug:
self.q_hd[observation, action].append(self.table[observation, action])
self.t_hd[observation, next_observation, action].append(reward)
self.policy.update(observation=observation, action=action)
def reset(self):
self.table.fill(0)
self._initialize_covergence_analytics()
self._initialize_transition_analytics()
self.n_table.fill(0)
self.policy.reset()
def _initialize_covergence_analytics(self):
for i in range(self.environment.observation_space.n):
for j in range(self.environment.action_space.n):
self.q_hd[i, j] = [0]
def _initialize_transition_analytics(self):
for i in range(self.environment.observation_space.n):
for j in range(self.environment.observation_space.n):
for k in range(self.environment.action_space.n):
self.t_hd[i, j, k] = list()
def save(self, filename):
obj = {
'table': self.table,
'n_table': self.n_table,
'q_hd': self.q_hd,
't_hd': self.t_hd
}
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, 'wb') as out_file:
pickle.dump(obj, out_file)
def load(self, filename):
with open(filename, 'rb') as in_file:
obj = pickle.load(in_file)
for key, value in obj.items():
setattr(self, key, value)
| true |
cefb6bc815e9c4f4462b307ca8d5ad93fbf038d1 | Python | reihaa/Neuroscience | /phase5/dog_ex.py | UTF-8 | 3,484 | 3.203125 | 3 | [] | no_license | import math
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
def convolution2d(image, kernel):
m, n = kernel.shape
y, x = image.shape
y = y - m + 1
x = x - m + 1
new_image = np.zeros((y, x))
for i in range(y):
for j in range(x):
new_image[i][j] = np.sum(image[i:i+m, j:j+m]*kernel)
return new_image
def get_dog_kernel(sigma1, sigma2, kernel_size):
if kernel_size % 2 == 0:
raise ValueError('kernel_size should be an odd number like 3, 5 and ...')
result = np.zeros((kernel_size, kernel_size))
for i in range(kernel_size):
for j in range(kernel_size):
x, y = i - kernel_size // 2, j - kernel_size // 2
g1 = (1 / sigma1) * math.exp(-(x * x + y * y) / (2 * sigma1 * sigma1))
g2 = (1 / sigma2) * math.exp(-(x * x + y * y) / (2 * sigma2 * sigma2))
result[i][j] = (1 / (math.sqrt(2 * math.pi)) * (g1 - g2))
return result
def get_gabor_kernel(landa, theta, sigma, gamma, kernel_size):
if kernel_size % 2 == 0:
raise ValueError('kernel_size should be an odd number like 3, 5 and ...')
result = np.zeros((kernel_size, kernel_size))
for i in range(kernel_size):
for j in range(kernel_size):
x, y = i - kernel_size // 2, j - kernel_size // 2
X = x * math.cos(theta) + y * math.sin(theta)
Y = - x * math.sin(theta) + y * math.cos(theta)
result[i][j] = math.exp(-(X*X + gamma * gamma * Y * Y) / (2 * sigma * sigma)) * \
math.cos(2 * math.pi * X / landa)
return result # - np.mean(result)
def show_images(image, kernels, filtered_images, parts=4):
fig, axes = plt.subplots(len(kernels), 2 + parts, figsize=(10, 8))
for i in range(len(kernels)):
axes[i][0].imshow(kernels[i], "gray")
axes[i][1].imshow(filtered_images[i], "gray")
min_element, max_element = np.min(filtered_images[i]), np.max(filtered_images[i])
for j in range(parts):
min_thresh = min_element + (max_element - min_element) * j / parts
max_thresh = min_element + (max_element - min_element) * (j + 1) / parts
axes[i][2 + j].imshow(
(min_thresh <= filtered_images[i]) * (filtered_images[i] < max_thresh) * filtered_images[i], "gray")
plt.show()
def show_images_gabor(image, kernels, filtered_images):
fig, axes = plt.subplots(len(kernels) // 4, 4, figsize=(10, 8))
fig1, axes1 = plt.subplots(len(kernels) // 4, 4, figsize=(10, 8))
for i in range(0, len(kernels), 4):
row = (i // 4)
for j in range(4):
axes[row][j].imshow(kernels[i + j], "gray")
axes1[row][j].imshow(filtered_images[i + j], "gray")
plt.show()
# if __name__ == "__main__":
# gray = np.asarray(Image.open("data/gorill.png").convert('L'))
# dog_kernels = [get_dog_kernel(size / 3.2, size / 2, size) for size in [5, 13, 21, 29]]
# outputs = [convolution2d(gray, kernel) for kernel in dog_kernels]
# show_images(gray, dog_kernels, outputs)
if __name__ == "__main__":
gray = np.asarray(Image.open("data/gorill.png").convert('L'))
gabor_kernels = [get_gabor_kernel(10, math.pi * theta / 4, 5, 0.5, size)
for size in [7, 13, 19, 25, 31, 37, 43, 49]
for theta in range(4)]
outputs = [convolution2d(gray, kernel) for kernel in gabor_kernels]
show_images_gabor(gray, gabor_kernels, outputs)
| true |
849f8470d746f019b05696bd1a7f59e77e105f50 | Python | luoyh15/forked-pencil-code | /python/pencilnew/math/is_int.py | UTF-8 | 184 | 3.703125 | 4 | [] | no_license |
def is_int(s):
""" Checks if string s is an int. """
try:
a = float(s)
b = int(s)
except ValueError:
return False
else:
return a == b
| true |
1afab628378e5fb7e053a283c981a70c51cc71eb | Python | tlondero/LABO | /TP2/Ejercicio_1(Germo)/Grafico/Gráficos_L.py | UTF-8 | 4,939 | 2.890625 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.patches as mpatches
def not_num(content):
if content == "0":
return 0
if content == "1":
return 0
if content == "2":
return 0
if content == "3":
return 0
if content == "4":
return 0
if content == "5":
return 0
if content == "6":
return 0
if content == "7":
return 0
if content == "8":
return 0
if content == "9":
return 0
if content == "-":
return 0
return 1
def read_file_spice(filename):
file = open(filename, 'r')
lines = file.readlines()
data = dict()
data["f"] = []
data["abs"] = []
data["pha"] = []
print(lines)
for i in range(1,len(lines)):
pnt = 0
c1 = ""
c2 = ""
c3 = ""
while lines[i][pnt] != '\t':
c1 += lines[i][pnt]
pnt += 1
while not_num(lines[i][pnt]):
pnt += 1
while lines[i][pnt] != 'd':
c2 += lines[i][pnt]
pnt += 1
pnt += 1
while not_num(lines[i][pnt]):
pnt += 1
while lines[i][pnt] != '°':
c3 += lines[i][pnt]
pnt += 1
c1 = float(c1)
c2 = float(c2)
c3 = float(c3)
data["f"].append(c1)
data["abs"].append(c2)
data["pha"].append(c3)
return data
data = read_file_spice("Ejercicio 1 - Pasabajo.txt")
frecuencia_med=[10,100,1*10**3,5*10**3,10*10**3,20*10**3,30*10**3,50*10**3,75*10**3,100*10**3,200*10**3,400*10**3,450*10**3,500*10**3,550*10**3,600*10**3,650*10**3,700*10**3,725*10**3,750*10**3,775*10**3,800*10**3,825*10**3,850*10**3,855*10**3,862.5*10**3,870*10**3,875*10**3,900*10**3,925*10**3,950*10**3,1*10**6,1.1*10**6,1.2*10**6,1.3*10**6,1.4*10**6,2*10**6,4*10**6,10*10**6]
z_med=[0.96,0.32,3.02,15.23,30.32,60.11,89.35,146.7,217.8,289.2,589.5,1368,1635,1954,2344,2829,3442,4217,4664,5147,5633,6089,6456,6672,6698,6715,6718,6705,6563,6282,5921,5146,3884,3068,2531,2159,1179,498.4,181.9]
fase_med=[18.7,72,86,87.76,87.78,87.58,87.38,87.04,86.55,86.01,83.40,76.44,74.05,71.16,67.60,63.06,57.10,49.05,43.99,37.96,30.99,22.93,13.96,4.38,2.45,-0.46,-3.40,-5.28,-14.43,-22.89,-30.30,-42.08,-56.67,-64.80,-69.82,-73.18,-81.50,-86.56,-87.87]
R_s_medida=[0.91,0.1,0.18,0.59,1.16,2.52,4.04,7.50,13.00,20.00,67.70,322,450,632,893,1281,1868,2763,3356,4060,4831,5608,6264,6653,6692,6715,6706,6677,6356,5787,5114,3820,2132,1306,874,626,175,29.60,6.70]
Q_medida=[0.0,3.0,16.6,25.8,26.0,23.8,22.1,19.5,16.7,14.4,8.6,4.1,3.5,2.9,2.4,2.0,1.5,1.2,1.0,0.8,0.6,0.4,0.2,0.1,0.0,0.0,0.1,0.1,0.3,0.4,0.6,0.9,1.5,2.1,2.7,3.3,6.7,16.8,27.3]
Ls_medida=[0.49,0.480,0.480,0.485,0.482,0.4781,0.4736,0.467,0.4616,0.4593,0.4661,0.529,0.556,0.589,0.627,0.669,0.708,0.7243,0.7110,0.6713,0.5949,0.4718,0.3012,0.0940,0.0527,-0.100,-0.719,-0.1114,-0.2898,-0.4204,-0.500,-0.5488,-0.4697,-0.3682,-0.2908,-0.2349,-0.0928, -19.79*10**(-6), -2.893*10**(-6)]
fig, ax1 = plt.subplots()
ax1.set_xlabel('Frecuencia [Hz]')
ax1.set_ylabel('|Z| [\u03A9]')
ax1.plot(frecuencia_med, z_med, "blue", linestyle='-', label='Módulo de la Transferencia (Empírico)')
#ax1.plot(data["f"], data["abs"], "red", linestyle='-', label='Módulo de la Transferencia (Simulado)')
ax1.set_xscale("log", basex=10,subsx=[1,2,3,4,5,6])
ax1.tick_params(axis='y')
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.set_ylabel('Fase [°]') # we already handled the x-label with ax1
ax2.plot(frecuencia_med, fase_med, "blue", linestyle=':', label='Fase(Empírica)')
#ax2.plot(data["f"], data["pha"], "red", linestyle=':', label='Fase (Simulada)')
ax2.tick_params(axis='y')
ax1.set_yticks([0,1000,2000,3000,4000,5000,6000,7000,8000])
ax2.set_yticks([-90,-75,-60,-45,-30,-15,0,15,30,45,60,75,90])
fig.tight_layout() # otherwise the right y-label is slightly clipped
#plt.show()
#plt.yscale("linear")
#plt.title('Diagrama de Bode - Filtro Pasa-bajos')
# agregamos patches
patches = [
mpatches.Patch(color="blue", linestyle=':', label='Fase (Medida)'),
mpatches.Patch(color="blue", linestyle='-', label='Módulo de la Transferencia (Medido)'),
mpatches.Patch(color="red", linestyle=':', label='Fase (Simulada)'),
mpatches.Patch(color="red", linestyle='-', label='Módulo de la Transferencia (Simulada)'),
]
# agregamos leyenda
plt.legend(handles=patches)
#plt.ylabel('|H($)| [dB]')
#plt.xlabel('Frecuencia[Hz]')
#plt.plot(fmed, hmed, "blue", label='Módulo de la Transferencia (Empírico)')
#plt.plot(fmed, fase, "blue", linestyle=':', label='Fase')
# pongo una grilla
plt.minorticks_on()
ax1.xaxis.grid(True)
plt.grid(which='major', axis='both', linestyle='-', linewidth=0.3, color='black')
plt.grid(which='minor', axis='both', linestyle=':', linewidth=0.1, color='black')
plt.grid(True, which="both")
plt.show()
| true |
53b07c5d60769d9e745e164f81fae6ca599d47cc | Python | tbrodbeck/VRP-solver | /ikw_final_scheduler.py | UTF-8 | 364 | 2.65625 | 3 | [] | no_license | import os
import sys
"""
Final search to be deployed on the ikw grid.
It is designed for 20 parallel runs.
"""
print('cwd', os.getcwd())
run = int(sys.argv[1])
command = 'python3 search.py '
command2 = 'python3 plotting.py '
# choose scenario
if run <= 10:
input = '1 ' + str(run)
elif run <= 20:
input = '2 ' + str(run)
os.system(command + input)
| true |
d62c81d19d99e5b60ecc5a22002e9b68bada3ffd | Python | Federic04/integrador3 | /clasemanejadorexceptuados.py | UTF-8 | 1,300 | 2.625 | 3 | [] | no_license | import csv
from claseexceptuados import exceptuado
class manejadorexceptuados:
__listaexceptuados=[]
def __init__(self):
self.__listaexceptuados=[]
def cargarexceptuados(self):
band=True
archivo=open('Personal-exceptuado.csv')
reader=csv.reader(archivo,delimiter=';')
for fila in reader:
if(band==True):
band=False
else:
ap=fila[0].lower()
nm=fila[1].lower()
dnei=fila[2].lower()
ed=int(fila[3])
dr=fila[4].lower()
tl=fila[5].lower()
fac=fila[6].lower()
org=fila[7].lower()
unexceptuado=exceptuado(ap,nm,dnei,ed,dr,tl,fac,org)
self.__listaexceptuados.append(unexceptuado)
archivo.close()
def getexceptuados(self):
return self.__listaexceptuados
def ordenar(self):
self.__listaexceptuados.sort()
def mostrarexceptuados(self,nom_org):
for i in range(len(self.__listaexceptuados)):
if self.__listaexceptuados[i].getorganismo()==nom_org:
if self.__listaexceptuados[i].getedad()<60:
self.__listaexceptuados[i].mostrardatos()
| true |
41322247928f1a84043c1934241cc723bc57f383 | Python | klaspettersson/FrRe1 | /frre/FrRe.py | UTF-8 | 3,757 | 2.875 | 3 | [] | no_license | # Frequency response for a finite cylinder
from dolfin import *
set_log_level(40) # fenics log level
from mshr import *
import numpy as np
import time
def psi(mesh, ga, lambda_min, lambda_max, N=200, dN=50, Nfactor=20):
"""
Frequency response of a finite cylinder. It computes the
average over a frequency interval of the volume average
of the frequency response p to the Helmholz equation
with constant Dirichlet harmonic load a part of the boundary
which is of positive (d-1)-dimensional measure.
The algorithm is described in arXiv: 2012.02276.
Pre: The Fredholm alternative holds for the parameters.
Input: Mesh mesh.
Boundary descriptor ga.
Spectral interval [lambda_min, lambda_max]
N, dN, Nfactor parameters for what eigenvalues
and eigenvalues to compute.
Output: (\lambda_{\max}-\lambda_{\min})^{-1}\int_{\lambda_{\min}}^{\lambda_{\max}} <p_\lambda> d\lambda
"""
# compute eigenvalues and eigenfunctions
dx = Measure('dx', domain=mesh)
nu_max = 0.0
V = FunctionSpace(mesh, "CG", 1)
u = TrialFunction(V)
v = TestFunction(V)
a = dot(grad(u), grad(v))*dx
m = u*v*dx
bc = DirichletBC(V, Constant(0.0), ga)
C = PETScMatrix()
M = PETScMatrix()
assemble(a, tensor=C)
bc.apply(C)
assemble(m, tensor=M)
eigensolver = SLEPcEigenSolver(C, M)
eigensolver.parameters["spectrum"] = "smallest real"
while (nu_max < Nfactor*lambda_max):
eigensolver.solve(N)
nconv = eigensolver.get_number_converged()
nu_max, _, _, _ = eigensolver.get_eigenpair(nconv-1)
N = N + dN
# compute psi
phi_i = Function(V)
area = assemble(Constant(1.0)*dx)
avg_of_mean_p = 1.0
for i in range(nconv):
nu_i, _, phi_i.vector()[:], _ = eigensolver.get_eigenpair(i)
phi_i_L2_squared = assemble(phi_i*phi_i*dx)
factor_i = (area*phi_i_L2_squared)**-1
int_phi_i = assemble(phi_i*dx)
avg_of_mean_p = avg_of_mean_p + factor_i*int_phi_i**2*((lambda_max-lambda_min)**-1*nu_i*np.log(np.abs((nu_i-lambda_min)/(lambda_max-nu_i)))-1.0)
return avg_of_mean_p
def Cylinder2d(x, y, mesh_density=32):
"""
Mesh of finite symmetric cylinder.
Pre: x is ordered. y > 0.
Input: Radius y at x1-coordinates x.
Output: Dolfin mesh.
Example: Cylinder2d([0,1], [1,1])
"""
upper_points = [Point(x[i], y[i]) for i in reversed(range(len(x)))]
lower_points = [Point(x[i], -y[i]) for i in range(len(x))]
points = lower_points + upper_points
domain = Polygon(points)
return generate_mesh(domain, mesh_density)
class RandomCylinder2d():
"""
Generator for finite cylinders.
Pre: x ordered, 0 < min_radius < max_radius, mesh_density > 0.
Input: Ordered x coordinates.
Stop at max_n if max_n > 0.
Minimum radius min_radius and maximal radius max_radius.
Output: Dolfin mesh with uniformly distributed random radius in
[min_radius, max_radius] at coordinates x.
Mesh density mesh_density.
Outputs radii if export_radius.
Example:
for cyl in RandomCylinder2d(x=np.linspace(0.0, 1.0, 2)):
plot(cyl)
plt.show()
"""
def __init__(self, x=[0.0, 1.0], max_n=0, min_radius=0.1, max_radius=0.5, mesh_density=32, export_radius=False):
self.max_n = max_n
self.n = 0
self.min_radius = min_radius
self.max_radius = max_radius
self.mesh_density = mesh_density
self.export_radius = export_radius
self.x = x
np.random.seed(np.uint32(time.time()*1e7%1e4))
def __iter__(self):
return self
def __next__(self):
self.n = self.n + 1
if self.max_n > 0 and self.n > self.max_n:
raise StopIteration
self.radius = np.random.uniform(self.min_radius, self.max_radius, len(self.x))
self.mesh = Cylinder2d(self.x, self.radius, self.mesh_density)
if self.export_radius:
return self.mesh, self.radius
else:
return self.mesh
| true |
eee140329a7869d914098af76c4f5e08b3719a9b | Python | EqbalS/super-crawler | /main.py | UTF-8 | 3,572 | 2.75 | 3 | [] | no_license | import os
import re
import sys
import yaml
from bs4 import BeautifulSoup
def read_conf(conf_path):
return yaml.load(open(conf_path))
def find_domain_name(path):
protocol = 'http'
if path.startswith('http://'):
path = path[7:]
if path.startswith('https://'):
protocol = 'https'
path = path[8:]
if path.find('/') == -1:
return path, protocol
else:
return path[:path.find('/')], protocol
def get_value(element, conf):
if 'attribute' in conf:
return element[conf['attribute']]
else:
return element.contents[0].strip()
def select(soup, conf, select_one=False):
if select_one:
selected_element = soup.select_one(conf['css-selector'])
return get_value(selected_element, conf)
selected_elements = soup.select(conf['css-selector'])
values = []
for element in selected_elements:
value = get_value(element, conf)
if 'regex-exclude' in conf:
pattern = re.compile(conf['regex-exclude'])
if pattern.match(value) is not None:
continue
if 'regex-filter' in conf:
pattern = re.compile(conf['regex-filter'])
if pattern.match(value) is None:
continue
values.append(value)
return values
def get_full_url(address, item, domain_name, protocol):
if item.startswith('//'):
return protocol + ':' + item
if item.startswith('/'):
return protocol + '://' + domain_name + item
if item.startswith('http://') or item.startswith('https://'):
return item
else:
if not address.endswith('/'):
address += '/'
return address + item
def do_action(conf, name, wget_extra_args, address, item, domain_name, protocol):
if 'download' in conf and conf['download']:
full_url = get_full_url(address, item, domain_name, protocol)
print 'Downloading %s -> %s' % (full_url, name)
os.system('wget %s "%s" -P "%s" 2> /dev/null' % (wget_extra_args, full_url, name))
if 'print' in conf and conf['print']:
print item
if 'follow' in conf:
process_page(conf['follow'], name, address=get_full_url(address, item, domain_name, protocol))
if 'recurse-condition-regex' in conf:
full_url = get_full_url(address, item, domain_name, protocol)
pattern = re.compile(conf['recurse-condition-regex'])
if pattern.match(full_url) is None:
do_action(conf['recurse-final'], name, wget_extra_args, address, item, domain_name, protocol)
else:
process_page(conf, name, address=full_url)
def process_page(conf, name='.', address=None):
if address is None:
address = conf['address']
wget_extra_args = ''
if 'wget-extra-args' in conf:
wget_extra_args = conf['wget-extra-args']
domain_name, protocol = find_domain_name(address)
print 'Getting %s' % address
os.system('wget %s "%s" -O tmp 2> /dev/null' % (wget_extra_args, address))
soup = BeautifulSoup(open('tmp').read(), 'html.parser')
os.system('rm -f tmp')
os.system('mkdir -p "%s"' % name)
if 'name' in conf:
if isinstance(conf['name'], dict):
name += '/' + select(soup, conf['name'], select_one=True)
else:
name += '/' + conf['name']
for item in select(soup, conf['item']):
do_action(conf, name, wget_extra_args, address, item, domain_name, protocol)
def main():
conf = read_conf(sys.argv[1])
for page in conf:
process_page(conf[page])
| true |
1e6821f3f4d93117f2c46c5dfdfe2a8092d0b0cc | Python | yfeng75/learntocode | /python/conditions.py | UTF-8 | 414 | 3.84375 | 4 | [] | no_license | name=input("What is your name? ")
age = int(input("How old are you?"))
#if age >= 16 and age <= 65:
# if 18<= age <=30 and name !="":
if age in range(16,66) and name != "":
print("Welcome to the holiday, {}".format(name))
else:
print("Sorry, you are not in the right age")
# print("-" * 80)
# if age <16 or age >65:
# print("Enjoy your free time")
# else:
# print("Have a good day at work")
| true |
8386ccdae95c153797443065a0aa9e7b324d2ed6 | Python | cliodhnaharrison/interview-prep | /leetcode/most_common_word.py | UTF-8 | 320 | 3.234375 | 3 | [] | no_license | from collections import defaultdict
import re
def most_common_word(paragraph, banned):
freq = defaultdict(int)
paragraph = re.findall(r"[\w]+", paragraph.lower())
print (paragraph)
for word in paragraph:
if word not in banned:
freq[word] += 1
return max(freq, key=freq.get)
| true |
f58121b64677c2cf8af3098bbb033a5d92511389 | Python | zzz0069/Navigation-positioning | /softwareprocess/dispatch.py | UTF-8 | 11,348 | 2.90625 | 3 | [] | no_license | import math
import re
import datetime
def dispatch(values=None):
if(values == None):
return {'error': 'parameter is missing'}
if(not(isinstance(values,dict))):
return {'error': 'parameter is not a dictionary'}
if (not('op' in values)):
values['error'] = 'no op is specified'
return values
if(values['op'] == 'adjust'):
return adjust(values)
elif(values['op'] == 'predict'):
return predict(values)
elif(values['op'] == 'correct'):
return correct(values)
elif(values['op'] == 'locate'):
return locate(values)
else:
values['error'] = 'op is not a legal operation'
return values
#adjust
def adjust(values):
if 'altitude' in values:
values['error'] = 'altitude has already exists'
return values
if 'observation' not in values:
values['error'] = 'mandatory information is missing'
return values
try:
degreesMinutes = values['observation'].split('d')
degrees = int(degreesMinutes[0])
minutesStringType = degreesMinutes[1]
minutes = float(minutesStringType)
except:
values['error'] = 'observation is invalid'
return values
if degrees < 0 or degrees >= 90:
values['error'] = 'observation is invalid'
return values
if minutesStringType[::-1].find('.') is not 1:
values['error'] = 'observation is invalid'
return values
if minutes < 0.0 or minutes >= 60.0:
values['error'] = 'observation is invalid'
return values
if degrees == 0 and minutes == 0.1:
values['error'] = 'observation is invalid'
return values
observation = degrees + minutes / 60.0
# print observation
height = 0
if 'height' in values:
try:
height = float(values['height'])
except ValueError:
values['error'] = 'height is invalid'
return values
if values['height'] < 0:
values['error'] = 'height is invalid'
return values
# print height
temperature = 72
if 'temperature' in values:
try:
temperature = int(values['temperature'])
except ValueError:
values['error'] = 'temperature is invalid'
return values
if temperature < -20 or temperature > 120:
values['error'] = 'temperature is invalid'
return values
# print temperature
pressure = 1010
if 'pressure' in values:
try:
pressure = int(values['pressure'])
except ValueError:
values['error'] = 'pressure is invalid'
return values
if pressure < 100 or pressure > 1100:
values['error'] = 'pressure is invalid'
return values
# print pressure
horizon = 'natural'
if 'horizon' in values:
horizon = values['horizon']
if horizon != 'artificial' and horizon != 'natural':
values['error'] = 'horizon is invalid'
return values
# print horizon
dip = 0
if horizon == 'natural':
dip = (-0.97 * math.sqrt(height)) / 60
# print dip
refraction=(-0.00452*pressure) / (273+convertToCelsius(temperature))/math.tan(math.radians(observation))
# print refraction
altitude = observation + dip + refraction
if altitude < 0 or altitude > 90:
values['error'] = 'altitude is invalid'
return values
values['altitude'] = correctedAltitude(altitude)
return values
def correctedAltitude(alt):
x = ((alt - math.floor(alt)) * 60.0)
arcmin = round(x,1)
return str(int(math.floor(alt))) + 'd' + str(arcmin)
def convertToCelsius(f):
c = (f - 32) * 5.0/9.0
return c
# predict
def predict(values):
key = 'body'
if key not in dict.keys(values):
values['error'] = 'mandatory information is missing'
return values
key = 'lat'
if key in dict.keys(values):
values['error'] = 'input contains key : lat'
return values
key = 'long'
if key in dict.keys(values):
values['error'] = 'input contains key : long'
return values
data = open('Stars.txt')
starsDict = {}
for line in data:
word = line.split()
starsDict[word[0]] = str(word[1]) + ' ' + str(word[2])
data.close()
starName = values['body']
if (word[0].lower() == starName.lower()):
return word
if starName not in starsDict:
values['error'] = 'star not in catalog'
return values
keys = ['long','lat']
for key in dict.keys(values):
keys.append(key)
key = 'date'
if key not in dict.keys(values):
values[key] = '2001-01-01'
else:
dateValid = dateTest(values['date'])
if dateValid == False:
values['error'] = 'invalid date'
return values
key = 'time'
if key not in dict.keys(values):
values[key] = '00:00:00'
else:
timeValid = timeTest(values)
if timeValid == False:
values['error'] = 'invalid time'
return values
elementInStar = starsDict[starName]
elementInStar = elementInStar.split()
SHA = elementInStar[0]
latitude = elementInStar[1]
timePara = {'date' : values['date'], 'time' : values['time']}
GHAEarth = getGHA(timePara)
GHAStar = degreeToFloat(GHAEarth) + degreeToFloat(SHA)
GHAStar = GHAStar - math.floor(GHAStar / 360) * 360
GHAStar = degreeToString(GHAStar)
values['long'] = GHAStar
values['lat'] = latitude
for key in dict.keys(values):
if key not in keys:
del values[key]
return values
def dateTest(value):
if not re.match('\d\d\d\d-\d\d-\d\d$', value):
return False
value = value.split('-')
if int(value[0]) < 2001 or int(value[1]) < 1 or int(value[1]) > 12:
return False
year = int(value[0])
month = int(value[1])
date = int(value[2])
if month in [1, 3, 5, 7, 8, 10, 12]:
if date > 31:
return False
if month in [4, 6, 9, 11]:
if date > 30:
return False
if month == 2 and year % 4 != 0:
if date > 28:
return False
if month == 2 and year % 4 == 0:
if date > 29:
return False
def timeTest(values):
time = values['time']
if not re.match("^\d\d:\d\d:\d\d", time):
return False
time = time.split(':')
if (int(time[0]) > 24 or int(time[0]) < 0) or (int(time[1]) > 60 or int(time[1]) < 0) or (int(time[2]) > 60 or int(time[2]) <0):
return False
def getGHA(timePara):
originalGHA = '100d42.6' # GHA in 2001-01-01
originalGHA = degreeToFloat(originalGHA)
date = timePara['date']
time = timePara['time']
year = int(date.split('-')[0])
month = int(date.split('-')[1])
day = int(date.split('-')[2])
yearGap = year - 2001
cumProgression = yearGap * degreeToFloat('-0d14.31667')
leapYears = int(yearGap / 4)
dailyRotation = degreeToFloat('0d59.0')
leapProgression = dailyRotation * leapYears
firstDayOfTheYear = datetime.date(year,1,1)
currentDate = datetime.date(year,month,day)
dayDiff = currentDate - firstDayOfTheYear
dayGap = int(dayDiff.days)
time = time.split(':')
secGap = dayGap * 86400 + int(time[0]) * 3600 + int(time[1]) * 60 + int(time[2])
rotationInObsYear = (secGap - int(secGap / 86164.1) * 86164.1) / 86164.1 * degreeToFloat('360d0.0')
GHA = originalGHA + cumProgression + leapProgression + rotationInObsYear
GHA = degreeToString(GHA)
return GHA
def degreeToFloat(degree):
degree = degree.split('d')
minute = float(degree[1])
if int(degree[0]) != 0:
if int(degree[0]) < 0:
degree = int(degree[0]) - minute / 60
else:
degree = int(degree[0]) + minute / 60
else:
if degree[0][0] == '-':
degree = - minute / 60
else:
degree = minute / 60
return degree
def degreeToString(degree):
minute = str("{:.1f}".format((degree - math.floor(degree)) * 60))
if '-' in minute:
minute = minute.replace('-', '')
minute = minute.split('.')
min1 = minute[0].zfill(2) #pads string on the left with zeros to fill width
min2 = minute[1]
minute = min1 + '.' + min2
degree = str(int(degree)) + 'd' + minute
return degree
#correct
def correct(values):
floatValueOfDegree = {}
keys = ['lat', 'long', 'altitude', 'assumedLat', 'assumedLong']
for key in keys:
if key not in dict.keys(values):
values['error'] = 'mandatory information is missing'
return values
value = values[key]
if values[key][0] == '-':
value = value.replace('-','')
if not re.match("^\d*d\d*\.\d*$", value):
values['error'] = 'invalid ' + key
return values
value = '-' + value
else:
if not re.match("^\d*d\d*\.\d*$", value):
values['error'] = 'invalid ' + key
return values
boolVar = rangeCheck(key,value)
if boolVar == False:
values['error'] = 'invalid ' + key
return values
floatValueOfDegree[key] = degreeToFloat(value)
LHA = floatValueOfDegree['long'] + floatValueOfDegree['assumedLong']
#print LHA
for key in dict.keys(floatValueOfDegree):
floatValueOfDegree[key] = math.radians(floatValueOfDegree[key])
intermediateDistance = (math.sin(floatValueOfDegree['lat']) * math.sin(floatValueOfDegree['assumedLat'])) + ((math.cos(floatValueOfDegree['lat'])
* math.cos(floatValueOfDegree['assumedLat']) * math.cos(math.radians(LHA))))
#print intermediateDistance
correctedAltitude = math.asin(intermediateDistance)
correctedDistance = (floatValueOfDegree['altitude'] - correctedAltitude)
numeratorOfCalcorrectedAzimuth = (math.sin(floatValueOfDegree['lat']) - (math.sin(floatValueOfDegree['assumedLat']) * intermediateDistance))
denominatorOfCalcorrectedAzimuth = math.cos(floatValueOfDegree['assumedLat']) * math.cos(math.asin(intermediateDistance))
correctedAzimuth = (math.acos(numeratorOfCalcorrectedAzimuth / denominatorOfCalcorrectedAzimuth)) * 180 / math.pi
correctedDistance = int(correctedDistance * 180 / math.pi * 60)
values['correctedDistance'] = str(correctedDistance)
values['correctedAzimuth'] = degreeToString(correctedAzimuth)
return values
def rangeCheck(name,value):
if name == 'long' or name == 'assumedLong':
valueRange = [0,360]
if name == 'lat' or name == 'assumedLat':
valueRange = [-90,90]
if name == 'altitude':
valueRange = [0,90]
List = value.split('d')
degree = int(List[0])
minute = float(List[1])
if not (valueRange[0] < degree < valueRange[1]) and (0 < minute < 60):
return False
return True
def locate(values):
return values
| true |
8186b52af985f3646dfe9bb9ffcc24f3f9393175 | Python | meistalampe/MTEC | /WorkingFolder/MTEC/merge_csv_files.py | UTF-8 | 3,076 | 3.015625 | 3 | [] | no_license | import os
import csv
import collections
from empatica_data_extraction import *
# Initialize named tuple Sample
Sample = collections.namedtuple('Sample',
'tag, time, value')
def main():
verbose = False
# print header
label = 'MERGE CSV'
print_header(program_label=label)
# ----------------- DATA EXTRACTION ----------------- #
# # Get user input: folder name
# folder = input('Where is your data file located? [Press <enter> to use default path]: ')
# # check if input is empty, if so return default path
# folder_path = ''
# if not folder or not folder.strip():
# print('Using default path.')
# print()
# default_folder = 'MergeRepository'
# folder_path = os.path.abspath(os.path.join('.', 'MTEC', default_folder))
#
# # check if input path is a directory
# elif not os.path.isdir(folder):
# print('Input is not a valid folder path.')
# pass
# # if input path is a directory return it
# else:
# folder_path = os.path.abspath(folder)
# Get user input
folder = get_folder_from_user(default_folder_name='MergeRepository')
if not folder:
print("We can't search file in this location.")
return
else:
print(folder)
# Get user input: subject name
subject = input('Please enter subject initials.')
# create merge file
file_name = 'merged_raw_data_' + subject + '.txt'
file_path = os.path.abspath(os.path.join(folder, file_name))
if os.path.isfile(file_path):
# clear and then write
print('file found')
file = open(file_path, 'w')
file.truncate()
print('file cleared')
file.close()
else:
file = open(file_path, 'w')
print('new file created')
file.close()
# find all raw data files
# list holding all filenames in folder
all_files = []
# search folder for files with names matching search_text
search_text = 'recording'
for entry in os.scandir(folder):
if entry.name.startswith(search_text) and entry.is_file():
# file_size = str(os.path.getsize(entry))
# print(entry.name + ' size: ' + file_size + 'Bytes ')
all_files.append(entry)
# merge all files
stream = []
for f in all_files:
raw_data_file = os.path.abspath(os.path.join(folder, f))
print(raw_data_file)
with open(raw_data_file, 'r', encoding='utf-8') as fin:
all_samples = [Sample(*(line.split(' '))) for line in fin]
for s in all_samples:
stream.append(s)
all_samples.clear()
with open(file_path, 'w') as fout:
for i in stream:
fout.write(i.tag + ' ' + i.time + ' ' + i.value)
print('Files merged! Data stored to ' + file_name)
# ----------------- Info Segment ----------------- #
if verbose:
print(folder)
print(file_name)
print(file_path)
print(all_files)
if __name__ == '__main__':
main()
| true |
b79269c4036f5309d463db40789afe75c543bdf0 | Python | TramsWang/StatisticalAnomalyDetection | /OldStory/Synthetic/tmp.py | UTF-8 | 949 | 2.546875 | 3 | [] | no_license | import csv
import Divergence
import statistics
import random
import scipy.stats as stats
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import math
import sys
reader = csv.reader(open("Correct/92.csv", 'r'))
data = list(int(row[2]) for row in reader)
reader = csv.reader(open("Centralized/92.csv", 'r'))
data_cen = list(int(row[2]) for row in reader)
step = 1403
dropped, dist = Divergence.histogram(data, step)
dropped, dist_cen = Divergence.histogram(data_cen, step)
figure = plt.figure(figsize=(1500/300, 900/300), dpi=300)
acc = 0
x = []
ecdf = []
for i in range(60):
if i in dist:
acc += dist[i]
x += [i, i+1]
ecdf += [acc, acc]
plt.plot(x, ecdf, 'k', label="Correct")
acc = 0
x = []
ecdf = []
for i in range(60):
if i in dist_cen:
acc += dist_cen[i]
x += [i, i+1]
ecdf += [acc, acc]
plt.plot(x, ecdf, 'r', label="Cheated")
plt.legend()
plt.grid()
figure.savefig("ECDF.png") | true |
0fa06257563300917c5c5e67ba59a01bc9400eed | Python | peeush-the-developer/computer-vision-learning | /OpenCV-101/03.opencv-drawing/image_drawing.py | UTF-8 | 686 | 3.5 | 4 | [] | no_license | # Usage
# python image_drawing.py -i ../../Data/Input/Dog.jpg
# Load libraries cv2, argparse
import cv2
import argparse
# Add arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", type=str, help="Input image", required=True)
args = vars(ap.parse_args())
# Load original image
image = cv2.imread(args["image"])
print('Shape of image: ', image.shape)
cv2.imshow("Original", image)
# Draw rectangle, circle around face, eyes respectively
green = (0, 255, 0)
cv2.rectangle(image, (2200, 350), (2700, 900), green, 5)
red = (0, 0, 255)
cv2.circle(image, (2300, 600), 40, red, -1)
cv2.circle(image, (2600, 600), 40, red, -1)
cv2.imshow("Update", image)
cv2.waitKey(0)
| true |
32318c1eed503f7d9524ac9ba0a174bb589c0124 | Python | PooPooPidoo/Water_Meter | /newKekman.py | UTF-8 | 1,085 | 3.046875 | 3 | [] | no_license | from PIL import Image, ImageDraw
image = Image.open('image.jpg') # Открываем изображение
draw = ImageDraw.Draw(image) # Создаем инструмент для рисования
width = image.size[0] # Определяем ширину
height = image.size[1]
pix = image.load()
for x in range(width):
for y in range(height):
r = pix[x, y][0] #узнаём значение красного цвета пикселя
g = pix[x, y][1] #зелёного
b = pix[x, y][2] #синего
sr = (r + g + b) // 3 #среднее значение
draw.point((x, y), (sr, sr, sr))
for x in range(width):
for y in range(height):
r = pix[x, y][0]
g = pix[x, y][1]
b = pix[x, y][2]
if r > 100:
r = 255
draw.point((x, y), (r, g, b))
if g > 100:
g = 255
draw.point((x, y), (r, g, b))
if b > 100:
b = 255
draw.point((x, y), (r, g, b))
image.save("result.jpg", "JPEG")
| true |
09875be6bcad0369851cc8c2e6de27d2311ea547 | Python | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc98_validate_bst.py | UTF-8 | 760 | 3.390625 | 3 | [] | no_license | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
lowerLim = -float('inf')
upperLim = float('inf')
validBst = self.validateBst(root, lowerLim, upperLim)
return validBst
def validateBst(self, root, lowerLim, upperLim):
if root == None:
return True
if root.val <= lowerLim or root.val >= upperLim:
return False
isLeftValid = self.validateBst(root.left, lowerLim, root.val)
isRightValid = self.validateBst(root.right, root.val, upperLim)
return isLeftValid & isRightValid
| true |
0cc09e4aec960f30d0121f64a80a08d00fc20389 | Python | justhonor/Data-Structures | /String/Transform.py | UTF-8 | 1,238 | 3.609375 | 4 | [] | no_license | #!/usr/bin/python
# coding:utf-8
##
# Filename: Transform.py
# Author : aiapple
# Date : 2017-07-10
# Describe: 变形词判断
# 对于两个字符串A和B,如果A和B中出现的字符种类相同且
# 每种字符出现的次数相同,则A和B互为变形词
## 给定两个字符串A和B及他们的长度,判断他们是否为变形词
##################################################################
def chkTansform(A,B):
if len(A) != len(B):
return False
length = len(A)
dicA={}
dicB={}
# 用字典统计个字符的个数
for i in range(length):
if dicA.has_key(A[i]):
dicA[A[i]]=dicA[A[i]]+1
else:
dicA[A[i]]=1
if dicB.has_key(B[i]):
dicB[B[i]]=dicB[B[i]]+1
else:
dicB[B[i]]=1
# A字典中的key B字典中没有 则false,有值不等 也是false
for key in dicA.iterkeys():
if dicB.has_key(key):
if dicA[key] == dicB[key]:
continue
else:
return False
else:
return False
return True
if __name__=='__main__':
A = "abce"
B = "ebac"
print chkTansform(A,B)
| true |
f631fb57c68ee0872d0ccd0346b44f999709bfaf | Python | dhirendradhiru37/LetsUpgrade-Python-3 | /D3A1.py | UTF-8 | 341 | 4.09375 | 4 | [] | no_license | #Assignment-1 Day3
Altitude=int(input("Enter the input as Altitude(in ft)= "))
if Altitude>=0 and Altitude<=1000:
print("Altitude is ",Altitude,",Safe to land")
elif Altitude>1000 and Altitude<5000:
print("Altitude is ",Altitude,",Bring down to 1000")
else:
print("Altitude is ",Altitude,",Turn around and try later") | true |
012e47d1bf600afc192e6748eec4cf250fdae032 | Python | rohan-varma/scripts | /sink.py | UTF-8 | 1,227 | 3.140625 | 3 | [] | no_license | import torch
import torch.nn as nn
from torch.autograd import Function
class PassThrough(Function):
@staticmethod
def forward(ctx, *inputs):
return inputs
@staticmethod
def backward(ctx, *grad_outputs):
print(f"grad_outputs {grad_outputs}")
print(f"type is {type(grad_outputs)}")
# Use gradients to search through the graph as in
# https://gist.github.com/rohan-varma/7c8dab3635193c04c607e67c4951f519
return grad_outputs
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.a = nn.Linear(1, 1, bias=False)
self.b = nn.Linear(1, 1, bias=False)
def forward(self, x):
a, b = self.a(x), self.b(x)
# Get tensors from tuple. This would be a more general call to
# _find_tensors.
ret = a, b
new_a, new_b = PassThrough.apply(a, b)
# Reconstruct tuple from output tensors. This would require a more general
# function that repacks the tensor(s) into the data structure.
ret = new_a, new_b
return ret
model = MyModel()
inp = torch.ones(1)
out = model(inp)
loss = out[0].sum()
print("Calling backward...")
loss.backward()
print("Done with bwd")
| true |
d6b4243d6c5b455544cd38adb6012ad960971c4a | Python | AmrutaBirar/Python_Assignments | /ex4.py | UTF-8 | 563 | 3.890625 | 4 | [] | no_license | #This is an exercise of Variables and operations on it Example 4
total_buses = 100
space_in_bus = 25.00
drivers = 30
passangers = 90
bus_not_driven = total_buses - drivers
buses_driven = drivers
bus_capacity = buses_driven * space_in_bus
avg_passangers_per_bus = passangers / buses_driven
print "Total number of cars are :",total_buses
print "There are only",drivers,"available"
print "There are ",bus_not_driven,"empty buses due to only few drivers"
print "We can transport",bus_capacity,"passangers"
print "Passangers in each bus",avg_passangers_per_bus
| true |
ff9e6f355bb8536b7c6fdeca721a13c08b031693 | Python | adonis-lau/LeetCode-Python | /project/56.merge-intervals.py | UTF-8 | 1,132 | 3.9375 | 4 | [] | no_license | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
56. Merge Intervals
https://leetcode.com/problems/merge-intervals/
解题思路:
对内部数组按照第一个数字进行排序
判断每个数组的最后一个数字是否在下一个数组的两个数字中间
"""
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) <= 1:
return intervals
intervals.sort(key=lambda x: x[0])
# 从第二个数组开始循环
index = 1
while index < len(intervals):
# 如果前一个数组与当前数组有交集
if intervals[index][0] <= intervals[index - 1][1]:
# 那么将当前数组与前一个数组‘合并’
intervals[index - 1][1] = max(intervals[index][1], intervals[index - 1][1])
# 移除当前数组
intervals.pop(index)
else:
index += 1
return intervals
solution = Solution()
print(solution.merge([[1, 3], [8, 10], [2, 6], [15, 18]]))
print(solution.merge([[1, 4], [4, 5]]))
| true |
65a7ae1bbf29161043422cec8e88c92a2038fa40 | Python | Sushmitha2708/Python | /Variables and DataTypes/Lists.py | UTF-8 | 970 | 4.6875 | 5 | [] | no_license | #List
#Example1
courses=['History','Math','Biology','English']
print(len(courses))
print(courses[0])
print(courses[-1]) #prints the last one
courses[2]='Science' # to replace
print(courses)
courses.append('Art') # Append is to add in the last
print(courses)
courses.insert(0,'Chemistry') # To add in a particular location
print(courses)
courses_2=['Economics','French']
courses.append(courses_2)
print(courses)
courses.remove('Art')
print(courses)
courses.pop() # Another way to delete thr last one
print(courses)
courses.reverse()
print(courses)
courses.sort() # sorts letters in alpabetical order
print(courses)
#Example2
nums=[1,2,3,4,5,6,7,8,9,10]
nums.sort()# ASC
print(nums)
nums.sort(reverse=True)#DESC
print(nums)
my_list=[]
for n in nums:
my_list.append(n)
print (my_list)
#COMPREHENSION
my_list=[n for n in nums]
print(my_list)
#LIST FUNCTIONS
print(min(nums))
print(max(nums))
print(sum(nums))
| true |
a34391b257cf4fb60ff353c27e54adc6ce41bf52 | Python | ryubidragonfire/face | /playvideofromcam.py | UTF-8 | 408 | 2.671875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 20 17:44:41 2016
@author: chyam
"""
import cv2
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if vc.isOpened(): # try to get the first frame
rval, frame = vc.read()
else:
rval = False
while rval:
cv2.imshow("preview", frame)
rval, frame = vc.read()
if cv2.waitKey(20) == 27: # exit on ESC
break
cv2.destroyWindow("preview") | true |
fe81e2e705a0637297d7818739ba86eea53181d3 | Python | RahulSinghDhek/ScrapURLForWordCount | /scrap.py | UTF-8 | 1,933 | 3.25 | 3 | [] | no_license | from bs4 import BeautifulSoup
import requests
import re
from constants import limit,skip_words
import optparse
def parse_arguments():
parser = optparse.OptionParser()
parser.add_option('-u', '--url', dest="url",help="Valid URL string", default='https://hiverhq.com/')
parser.add_option('-l', '--limit', dest="limit", help="Limit of top words",default=limit)
return parser.parse_args()
def fetch_top_words(url,limit=limit):
#Request the given URL
try:
home_page_html_data=requests.get(url)
except requests.exceptions.RequestException as error_message:
print (error_message)
exit(1)
#Soup the output response
soup = BeautifulSoup(home_page_html_data.content,'html.parser')
#remove the script tag. Removing all the Javascript content
[script_tag.extract() for script_tag in soup.findAll('script')]
#Extract text out of the remaing HTML content
text_data=soup.get_text()
#Remove all the new line charcaters
text_data=text_data.replace('\n',' ')
#Remove special characters. More characters can be added to the existing list
text_data=re.sub(r'[0-9|+|-|,|*|?|(|)|/]',r'',text_data)
word_list=text_data.split()
word_hash_map={}
for word in word_list:
word=word.strip()
#Ignore the words with length 1 and pre-defined set of "skip words"
if len(word)>1 and word not in skip_words:
word_hash_map.setdefault(word,0)
word_hash_map[word]= word_hash_map[word]+1
#Sort the hash_map
sorted_word_list = sorted(word_hash_map.items(), key=lambda kv: kv[1],reverse=True)
for i in range(limit):
print ("{} : {}".format(sorted_word_list[i][0],sorted_word_list[i][1]))
if __name__ == '__main__':
options, args = parse_arguments()
print("Please wait. Listing the top {} most occuring words".format(options.limit))
fetch_top_words(options.url,int(options.limit))
| true |
b2c90cb3d818ce0d8cf8b4e32ac2a3b7a85492e8 | Python | ngkhang/py4e | /Chapter02/ch02_ex02.py | UTF-8 | 275 | 4.3125 | 4 | [] | no_license | '''
Exercise 2:
Write a program that uses input to prompt a user\
for their name and then welcomes them.
----Example:
Enter your name: Chuck
Hello Chuck
'''
# the code below almost works
name = input('Enter your name: ')
print('Hello',name)
| true |
98d563954f685cd0de069e821676fb0f1c4124ae | Python | RManish76/python2_hactoberfest | /pallindrom.py | UTF-8 | 465 | 3.265625 | 3 | [] | no_license | # def pallindrom(line):
# line=list(line)
# low = 0
# high = len(line)-1
# while(low<high):
# temp=line[low]
# line[low]=line[high]
# line[high]=temp
# low+=1
# high-=1
# line = '' . join(line)
# return(line)
# # Driver code
# if __name__ == '__main__' :
# s = input()
# print(1) if(s==pallindrom(s)) else print(0)
s=input()
s=list(s)
temp=s.copy()
s.reverse()
print(1) if(s==temp) else print(0) | true |
b87058d82108bdc8656e8cf1b24368e55a89d04a | Python | benranderson/run | /tests/test_models.py | UTF-8 | 810 | 2.734375 | 3 | [
"MIT"
] | permissive | # import pytest
# from datetime import date
# from app.models import Event, Plan, FiveK
# def test_event():
# e = Event(name='EMF', distance='5k', date=date(2018, 1, 1))
# assert '5k' in repr(e)
# def test_plan():
# p = Plan(level='Beginner')
# assert 'Beginner' in repr(p)
# def test_plan_weeks_between_dates():
# p = Plan()
# assert p.weeks_between_dates(date(2018, 1, 1), date(2018, 2, 1)) == 4
# @pytest.fixture()
# def event():
# return Event(name='EMF', distance='5k', date=date(2018, 1, 1))
# def test_plan_length(event):
# p = Plan(level='Beginner', event=event, start_date=date(2017, 12, 1))
# assert p.length == 5
# def test_plan_create(event):
# p = Plan(level='Beginner', event=event, start_date=date(2017, 12, 1))
# p.create(days=[0, 1, 2])
| true |
c2beb9e3beeb12a3e91f5189ea70fde4e4a07c87 | Python | SHETU-GUHA/1st | /1st chapter.py | UTF-8 | 1,128 | 4.625 | 5 | [] | no_license | print('Hellow World!')
print ('What is your name?')
myName = input()
print ('it is good to meet you ' + myName)
print('The length of our name is :')
print (len(myName))
print ('what is your age?')
myAge = input ()
print ('You will be ' + str (int(myAge)+1) + 'in a year.')
#1. operator (*, -, / , +) values ('hello', -88.8, 5)
# variable (spam), string ('spam')
# int,floating point ,string
# after running the code bacon value is 21
# 'spam' + 'spamspam' = spamspamspam
'spam' * 3 =
spam
spam
spam
#Why is eggs a valid variable name while 100 is invalid?
Because variable names cannot begin with a number.
# What three functions can be used to get the integer, floating-point number, or string version of a value?
str()
int()
float()
#Why does this expression cause an error? How can you fix it?
'I have eaten ' + 99 + ' burritos.'
This expression causes an error because here'I have eaten' and 'burritos' are strings, while 99 is treated as integer. In order to fix the error and print 'I have eaten 99 burritos.', 99 needs '' around it to treat it as a string.
| true |
983136d87f1b7da5d58b00b93fa624558ad3339e | Python | aakankshamudgal/ML | /first.py | UTF-8 | 90 | 3.328125 | 3 | [] | no_license | x=int(input())
if(x%2==0):
print("no is divisible by 2")
else:
print("not divisible")
| true |
642fcf870494b9a3d49d660610f258903f26c6bb | Python | brennan-macaig/AdventOfCode2019 | /intcode.py | UTF-8 | 10,245 | 3.5 | 4 | [] | no_license | """
OPCODE SPEC:
MODE_OPCODE,OP1,OP2,TARG
MODE_OPCODE: starts with 3 digits, either 0 or 1, to specify modes
of commands. Then, the final two digits, are the opcode. Ex:
MMMOP, or 00102 would be evauluated as 0-0-1-MULT
OP1: First operand
OP2: Second operand
TARG: Store to this target
VALID COMMANDS:
1: add op1, op2, targ --> adds op1 and op2, stores in targ
2: mul op1, op2, targ --> multiplies op1 and op2, stores in targ
3: inp targ --> input a single digit, store to targ
4: out targ --> display single digit from targ.
5: jmp op1, targ --> jump to instruction at targ if op1 != 0
6: jmp op1, targ --> jump to instruction at targ if op1 == 0
7: les op1, op2, targ --> if op1 is less than op2, store 1 to targ. Else store 0
8: eql op1, op2, targ --> if op1 equals op2 store 1 to targ, else store 0
EXECUTE SPEC:
Execute takes in a processed list of opcode, and a list of valid inputs. It will
run the opcode, and using the list of inputs, provide any input to the function.
If it runs out of inputs, it will prompt the user.
RETURN VAL:
"""
def execute(intcode, args):
i = 0
in_num = 0
for _ in range(0, intcode.__len__()):
mode = str(intcode[i])
leng = mode.__len__()
pos = 0
while leng < 5:
# left-pad with 0's
mode = "0" + mode
leng = mode.__len__()
p3m, p2m, p1m, op2, op1 = str(mode)
p3m = int(p3m)
p2m = int(p2m)
p1m = int(p1m)
opcode = int(op2 + op1)
if opcode == 1:
# add
p1 = 0
p2 = 0
p3 = 0
if p1m == 1:
p1 = intcode[i+1]
if p2m == 1:
p2 = intcode[i+2]
if p3m == 1:
p3 = intcode[i+3]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p2m == 0:
p2 = intcode[intcode[i+2]]
if p3m == 0:
p3 = intcode[intcode[i+3]]
opr = p1 + p2
intcode[intcode[i+3]] = opr
i = i+4
elif opcode == 2:
# mult
p1 = 0
p2 = 0
p3 = 0
if p1m == 1:
# immediate mode
p1 = intcode[i+1]
if p2m == 1:
p2 = intcode[i+2]
if p3m == 1:
p3 = intcode[i+3]
if p3m == 0:
p3 = intcode[intcode[i+3]]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p2m == 0:
p2 = intcode[intcode[i+2]]
opr = p1 * p2
intcode[intcode[i+3]] = opr
i = i+4
elif opcode == 3:
# input
p1 = 0
p2 = 0
text_in = ""
if p1m == 1:
p1 = intcode[i+1]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if args.__len__() > 0:
if in_num <= args.__len__():
text_in = int(args[in_num])
else:
text_in = int(input(">: "))
else:
text_in = int(input(">: "))
intcode[intcode[i+1]] = text_in
i = i + 2
elif opcode == 4:
# output
p1 = 0
p2 = 0
if p1m == 1:
p1 = intcode[i+1]
if p1m == 0:
p1 = intcode[intcode[i+1]]
text_out = str(p1)
print("sys.out: " + text_out + "\n")
i = i + 2
elif opcode == 5:
if p1m == 1:
p1 = intcode[i+1]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p1 != 0:
if p2m == 1:
i = intcode[i+2]
if p2m == 0:
i = intcode[intcode[i+2]]
else:
i = i + 3
elif opcode == 6:
if p1m == 1:
p1 = intcode[i+1]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p1 == 0:
if p2m == 1:
i = intcode[i+2]
if p2m == 0:
i = intcode[intcode[i+2]]
else:
i = i + 3
elif opcode == 7:
p1 = 0
p2 = 0
if p1m == 1:
p1 = intcode[i+1]
if p2m == 1:
p2 = intcode[i+2]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p2m == 0:
p2 = intcode[intcode[i+2]]
if p1 < p2:
intcode[intcode[i+3]] = 1
else:
intcode[intcode[i+3]] = 0
i = i + 4
elif opcode == 8:
p1 = 0
p2 = 0
if p1m == 1:
p1 = intcode[i+1]
if p2m == 1:
p2 = intcode[i+2]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p2m == 0:
p2 = intcode[intcode[i+2]]
if p1 == p2:
intcode[intcode[i+3]] = 1
else:
intcode[intcode[i+3]] = 0
i = i + 4
elif opcode == 99:
print("**sys halt**\n[diagnostics]")
print("mem[0]: " + str(intcode[0]))
return intcode
else:
print("**sys crash**")
print("error reading intcode")
print("[diagnostics]")
print("opcode: " + str(opcode) + " @ mem index: " + str(i))
return 0
def execute_ret_output(intcode, args):
i = 0
in_num = 0
for _ in range(0, intcode.__len__()):
mode = str(intcode[i])
leng = mode.__len__()
while leng < 5:
# left-pad with 0's
mode = "0" + mode
leng = mode.__len__()
p3m, p2m, p1m, op2, op1 = str(mode)
p3m = int(p3m)
p2m = int(p2m)
p1m = int(p1m)
opcode = int(op2 + op1)
if opcode == 1:
# add
p1 = 0
p2 = 0
if p1m == 1:
p1 = intcode[i+1]
if p2m == 1:
p2 = intcode[i+2]
if p3m == 1:
p3 = intcode[i+3]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p2m == 0:
p2 = intcode[intcode[i+2]]
if p3m == 0:
p3 = intcode[intcode[i+3]]
opr = p1 + p2
intcode[intcode[i+3]] = opr
i = i+4
elif opcode == 2:
# mult
p1 = 0
p2 = 0
if p1m == 1:
# immediate mode
p1 = intcode[i+1]
if p2m == 1:
p2 = intcode[i+2]
if p3m == 1:
p3 = intcode[i+3]
if p3m == 0:
p3 = intcode[intcode[i+3]]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p2m == 0:
p2 = intcode[intcode[i+2]]
opr = p1 * p2
intcode[intcode[i+3]] = opr
i = i+4
elif opcode == 3:
# input
p1 = 0
p2 = 0
text_in = ""
if p1m == 1:
p1 = intcode[i+1]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if args.__len__() > 0:
if in_num <= args.__len__():
text_in = int(args[in_num])
in_num += 1
else:
text_in = int(input(">: "))
else:
text_in = int(input(">: "))
intcode[intcode[i+1]] = text_in
i = i + 2
elif opcode == 4:
# output
p1 = 0
p2 = 0
if p1m == 1:
p1 = intcode[i+1]
if p1m == 0:
p1 = intcode[intcode[i+1]]
return p1
elif opcode == 5:
if p1m == 1:
p1 = intcode[i+1]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p1 != 0:
if p2m == 1:
i = intcode[i+2]
if p2m == 0:
i = intcode[intcode[i+2]]
else:
i = i + 3
elif opcode == 6:
if p1m == 1:
p1 = intcode[i+1]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p1 == 0:
if p2m == 1:
i = intcode[i+2]
if p2m == 0:
i = intcode[intcode[i+2]]
else:
i = i + 3
elif opcode == 7:
p1 = 0
p2 = 0
if p1m == 1:
p1 = intcode[i+1]
if p2m == 1:
p2 = intcode[i+2]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p2m == 0:
p2 = intcode[intcode[i+2]]
if p1 < p2:
intcode[intcode[i+3]] = 1
else:
intcode[intcode[i+3]] = 0
i = i + 4
elif opcode == 8:
p1 = 0
p2 = 0
if p1m == 1:
p1 = intcode[i+1]
if p2m == 1:
p2 = intcode[i+2]
if p1m == 0:
p1 = intcode[intcode[i+1]]
if p2m == 0:
p2 = intcode[intcode[i+2]]
if p1 == p2:
intcode[intcode[i+3]] = 1
else:
intcode[intcode[i+3]] = 0
i = i + 4
elif opcode == 99:
print("**sys halt**\n[diagnostics]")
print("mem[0]: " + str(intcode[0]))
return intcode
else:
print("**sys crash**")
print("error reading intcode")
print("[diagnostics]")
print("opcode: " + str(opcode) + " @ mem index: " + str(i))
return 0
"""
Given a string to pre-process, this processes it and returns executable
intcode, for use in other functions.
"""
def process(intcode_string):
y = map(int, intcode_string.split(","))
return list(y)
| true |
c36d7e3ed6fbdcaea8dba187305190ad7edf17f7 | Python | JohnEaganFS/CSCI-154-Simulation-Projects | /Blackjack/main.py | UTF-8 | 1,106 | 3.3125 | 3 | [] | no_license | import time
import random
import customGame
# Driver function
# _______
# // ||\ \
# _____//___||_\ \___
# ) _ _ \
# |_/ \________/ \___|
#___\_/________\_/______ Art Credit: Colin Douthwaite (some internet person)
if __name__ == "__main__":
random.seed(time.time())
print("Player Policies: 0 - Stick >= 17 1 - Stick >= Hard 17 2 - Always Stick 3 - Hit < 21 4 - Hit Soft 17 or Dealer Has 4/5/6 5 - Hit on Soft 17 6 - Random Stick/Hit 7 - Basic Strategy")
inputPolicy = int(input("Enter player policy: "))
print("Deck Type: 0 - Infinite Deck 1 - Single Deck")
inputDeck = int(input("Enter deck type: "))
inputIterations = int(input("Enter number of games: "))
start = time.time()
wins, losses, ties, avg = customGame.customGame(inputPolicy, inputDeck, inputIterations)
elapsed = time.time() - start
print()
print("Input:", inputPolicy, inputDeck, inputIterations)
print("Wins:", wins)
print("Losses:", losses)
print("Ties:", ties)
print("Average Win%:", avg)
print("Time:", elapsed) | true |
861131ea51ea60de82bdd23ed27c7ce0ba323f4a | Python | abhinandanpatni/MTG-Deck-Starter | /Classifiers/TFIDF.py | UTF-8 | 1,066 | 3.25 | 3 | [] | no_license | from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
colorList = ["White", "Green", "Blue", "Black", "Red"]
corpus = list()
for index, color in enumerate(colorList):
string = ""
with open("../" + color + ".txt", "r") as inputFile:
for line in inputFile:
string += line
string.replace("\n", " ")
corpus.append(string)
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
print X.shape
transformer = TfidfTransformer()
tfidf_transformer = transformer.fit_transform(X)
print tfidf_transformer.shape
clf = MultinomialNB().fit(tfidf_transformer, corpus)
toPredict = ["Return creatures from graveyard", "Deal damage to opponent", "Gain life"]
new_counts = vectorizer.transform(toPredict)
new_tfidf = transformer.transform(new_counts)
predicted = clf.predict(new_tfidf)
for ability, color in zip(toPredict, predicted):
print('%r => %s' %(ability, colorList[corpus.index(color)]))
# analyze = vectorizer.build_analyser() | true |
f2ff35030a97b723f95aab525b193d3676f5df61 | Python | mveselov/CodeWars | /katas/beta/resistor_color_codes.py | UTF-8 | 831 | 2.96875 | 3 | [
"MIT"
] | permissive | from operator import truediv
def decode_resistor_colors(bands):
color_codes = {'black': 0, 'brown': 1, 'red': 2, 'orange': 3, 'yellow': 4,
'green': 5, 'blue': 6, 'violet': 7, 'gray': 8, 'white': 9}
tolerances = {'gold': 5, 'silver': 10}
try:
band_1, band_2, band_3, tolerance = (
color_codes.get(a, tolerances.get(a)) for a in bands.split())
except ValueError:
band_1, band_2, band_3 = (color_codes[b] for b in bands.split())
tolerance = 20
ohms = int(str(band_1) + str(band_2)) * (10 ** band_3)
if ohms < 1000:
ohms_output = ohms
elif ohms < 1000000:
ohms_output = '{:g}k'.format(truediv(ohms, 1000))
else:
ohms_output = '{:g}M'.format(truediv(ohms, 1000000))
return '{} ohms, {}%'.format(ohms_output, tolerance)
| true |
e441e0e4fa599fefe6f3f49f32477c68dd46e29a | Python | jtannas/intermediate_python | /caching.py | UTF-8 | 1,368 | 4.09375 | 4 | [] | no_license | """
24. Function caching
Function caching allows us to cache the return values of a function
depending on the arguments. It can save time when an I/O bound function
is periodically called with the same arguments. Before Python 3.2 we
had to write a custom implementation. In Python 3.2+ there is an
lru_cache decorator which allows us to quickly cache and uncache the
return values of a function.
Let’s see how we can use it in Python 3.2+ and the versions before it.
"""
### PYTHON 3.2+ ###############################################################
from functools import lru_cache
@lru_cache(maxsize=32)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
[n for n in range(16)]
#: The maxsize argument tells lru_cache about how many recent return
#: values to cache.
# It can be inspected via:
fib.cache_info()
# It can be cleared via:
fib.cache_clear()
### PYTHON 2+ #################################################################
from functools import wraps
def memoize(function):
memo = {}
@wraps(function)
def wrapper(*args):
if args in memo:
return memo[args]
else:
rv = function(*args)
memo[args] = rv
return rv
return wrapper
@memoize
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
| true |
bf1abb376c8a5ae9cea50919d5617a798d8d8a88 | Python | servo/saltfs | /tests/util.py | UTF-8 | 1,255 | 2.625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | import os
RED = 31
GREEN = 32
BLUE = 34
MAGENTA = 35
def color(code, string):
return '\033[' + str(code) + 'm' + string + '\033[0m'
def display_path(path):
return color(MAGENTA, path)
def colon():
return color(BLUE, ':')
EXCLUDE_DIRS = ['.git', '.vagrant']
def project_path():
abspath = os.path.realpath(os.path.join(os.getcwd(), __file__))
# One dirname for tests dir, another for project dir
project_dir = os.path.dirname(os.path.dirname(abspath))
return os.path.relpath(project_dir)
def paths():
for root, dirs, files in os.walk(project_path(), topdown=True):
for exclude_dir in EXCLUDE_DIRS:
if exclude_dir in dirs:
dirs.remove(exclude_dir)
for filename in files:
yield os.path.join(root, filename)
class TestResult(object):
pass
class Success(TestResult):
def __init__(self, message):
self.message = message
def is_success(self):
return True
def is_failure(self):
return False
class Failure(TestResult):
def __init__(self, message, output):
self.message = message
self.output = output
def is_success(self):
return False
def is_failure(self):
return True
| true |
49c5bc07ef26e6f8b59781c7c02b443fd41c3c9f | Python | yangboyubyron/DS_Recipes | /Stats_and_Math/MatrixCalculations.py | UTF-8 | 2,912 | 4.25 | 4 | [] | no_license | # MSPA 400 Session #2 Python Module #3
# Reading assignment "Think Python" either 2nd or 3rd edition:
# 2nd Edition Chapter 3 (3.4-3.9) and Chapter 10 (10.1-10.12)
# 3rd Edition Chapter 3 (pages 24-29) and Chapter 10 (pages 105-115)
# Module #3 objective: demonstrate numpy matrix calculations. For
# matrix calculations, arrays must be converted into numpy matrices.
import numpy
from numpy import *
from numpy.linalg import *
# With numpy matrices, you can add, subtract, multiply, find the transpose
# find the inverse, solve systems of linear equations and much more.
# Solve a system of consistent linear equations. Refer to Lial Section 2.5
# Example 7 Cryptography for the calculation
# Right hand side of system of equations has data entered as a list
# and converted to 3x1 matrix and then a 1x3 matrix using the transpose
# function. Similar steps are taken for the matrix A.
rhs= [96, 87, 74]
rhs=matrix(rhs)
rhs=transpose(rhs)
print ('\nRight Hand Side of Equation')
print rhs
A =[[1, 3, 4], [2, 1, 3], [4, 2, 1]]
A= matrix(A)
print ('\nMatrix A')
print A
# Numpy has various functions to perform matrix calculations. The inverse
# function inv() is one of those.
# Find inverse of A.
print ('\nInverse of A')
IA= inv(A)
print IA
# In what follows, I am converting matrices with floating point numbers to
# matrices with integer numbers. This is optional and being done to show
# that it is possible to do so with numpy matrices.
# Note that the function dot() performs matrix multiplication.
# Verify inverse by multiplying matrix A and its inverse IA.
print ('\nIdentity Matrix')
I= dot(IA,A)
I= int_(I) # This converts floating point to integer.
print I
# Solve the system of equations and convert to integer values.
# With numpy it is necessary to use dot() for the product.
result = dot(IA,rhs)
result = int_(result) # This converts floating point to integer.
print ('\nSolution to Problem')
print result
# There is a more efficient way to do this with the linalg.solve() function.
print ('\nIllustration of solution with linalg.solve(,) function')
result2= linalg.solve(A,rhs)
print int_(result2) # This converts floating point to integer.
# Some square matrices do not have inverses. The following example shows
# how this is handled with numpy. Note the magnitude of the elements.
print ('\nExample of an inverse matrix for inconsistent equations')
A= [[1,2,3],[-3,-2,-1], [-1,0,1]]
A= array(A)
IA= inv(A)
print IA
# Exercises:
# Part 1. Refer to Lial Section 2.5 Example 2. Write the code to
# reproduce the results in the example. Form the matrix A, find its inverse
# and verify such by multiplying the two to form the identity matrix.
# Show the code, matrix A, inverse of A and the Identity matrix.
# Part 2. Refer to Lial Section 2.5 page 96 problem #1. Write the code
# which solves the problem. Use linalg.solve(,).
| true |
0c64eba317efe8132ed74e955a0ce29dc6cdbddb | Python | pohsienhsu/6730-Covid-Simulation | /src/Cellular_Automata/SEIRD.py | UTF-8 | 5,274 | 3.125 | 3 | [] | no_license | from .CA import Person, Automata
from .constant import *
import random
import pylab as plt
'''
Model 101 <SEIRD/Automata>
1. State:
-> Susceptible: 0
-> Exposed: 1
-> Infected: 2 (-> Death Rate: 0.05)
-> Recovered: 3
-> Dead: 4
2. Infection Rate:
-> rate = 0.5 (default)
3. Pattern:
How to decide whether a person will have a chance to get infected by neighbors?
-> Top, down, left, right if infected then the person is exposed with a rate of 0.5
4. Analysis:
-> Print Matrix with imshow
-> Print SEIR curve
'''
###############################
class Person_SEIRD(Person):
def __init__(self, chance=INIT_INFECTED):
super().__init__()
if random.random() <= chance:
self.state = 2
self.prevState = 2
else:
self.prevState = 0
self.state = 0
########################################################
class Automata_SEIRD(Automata):
def __init__(self, numcols, numrows):
super().__init__(numcols, numrows)
# Plotting Purposes
self.s_arr = []
self.e_arr = []
self.i_arr = []
self.r_arr = []
self.d_arr = []
self.days = []
def accumulateData(self):
'''
Each Day:
-> getS, getE, getI, getR, getD => return integer S, E, I, R, D in the current day
-> Store integer S E I R D to self.s_arr, self.e_arr, self.i_arr, self.r_arr, self.d_arr
'''
self.s_arr.append(self.getS())
self.e_arr.append(self.getE())
self.i_arr.append(self.getI())
self.r_arr.append(self.getR())
self.d_arr.append(self.getD())
self.days.append(self.day)
self.peopleStates_arr.append(self.getPeopleState())
def plotCurve(self):
fig, axes = plt.subplots(figsize=(4.5, 2.3), dpi=150)
axes.plot(self.days, self.s_arr, '-', marker='.', color="b")
axes.plot(self.days, self.e_arr, '-', marker='.', color=(1.0, 0.7, 0.0))
axes.plot(self.days, self.i_arr, '-', marker='.', color="r")
axes.plot(self.days, self.r_arr, '-', marker='.', color=(0.0,1.0,0.0))
axes.plot(self.days, self.d_arr, '-', marker='.', color=(0.5, 0, 0.5, 1))
axes.set_xlabel("Days")
axes.set_ylabel("Numbers of People")
axes.set_title("SEIRD Curve")
axes.legend(["Susceptible", "Exposed", "Infected", "Recovered", "Dead"])
def nextGeneration(self):
# Move to the "next" generation
for i in range(self.cols):
for j in range(self.rows):
self.people[i][j].copyState()
"""
if Top, down, left, right is infected
-> the center person will be infected by a chance of INFECTION_RATE
"""
for i in range(self.cols):
for j in range(self.rows):
infectedNeighbors = 0
iprev, inext, jprev, jnext = i - 1, i + 1, j - 1, j + 1
# iprevState = self.people[iprev][j].getPrevState()
# inextState = self.people[inext][j].getPrevState()
# jprevState = self.people[i][jprev].getPrevState()
# jnextState = self.people[i][jnext].getPrevState()
if (jprev >= 0 and (self.people[i][jprev].getPrevState() == 1 or self.people[i][jprev].getPrevState() == 2)):
infectedNeighbors += 1
if (jnext < self.rows and ( self.people[i][jnext].getPrevState() == 2 or self.people[i][jnext].getPrevState() == 1)):
infectedNeighbors += 1
if (iprev >= 0 and ( self.people[iprev][j].getPrevState() == 2 or self.people[iprev][j].getPrevState() == 1)):
infectedNeighbors += 1
if (inext < self.cols and ( self.people[inext][j].getPrevState() == 2 or self.people[inext][j].getPrevState() == 1)):
infectedNeighbors += 1
currPerson = self.people[i][j]
self.applyRulesOfInfection(currPerson, infectedNeighbors)
self.accumulateData()
self.day += 1
def applyRulesOfInfection(self, person, infectedNeighbors):
chance = random.random()
# Susceptible: 0
if person.prevState == 0:
if infectedNeighbors >= 1:
if (chance > (1-INFECTION_RATE)**infectedNeighbors):
person.setState(1)
# Exposed: 1
elif person.prevState == 1:
if person.getIncubation() > 0:
person.setIncubation(person.getIncubation() - 1)
elif chance <= EXPOSED_RATE and person.getIncubation() == 0:
person.setState(2)
return
# chanceRecovery = random.random()
# if chanceRecovery <= RECOVERY_RATE:
# person.setState(3)
# Infectious: 2
elif person.prevState == 2:
if chance <= RECOVERY_RATE:
# Recovered: 3
person.setState(3)
else:
chanceDeath = random.random()
if chanceDeath <= DEATH_RATE:
# Dead: 4
person.setState(4)
def getPerson(self):
return Person_SEIRD()
| true |
82ffce2dbf4105d06833958033e16ffd4ca2c493 | Python | ktakanopy/Competitive-Programming | /URI/1397/code.py | UTF-8 | 253 | 3.578125 | 4 | [] | no_license | while True:
n = int(input())
if n == 0: break
pa = pb = 0
for x in range(0,n):
a,b = map(int,input().rstrip().split())
if a > b:
pa += 1
elif a < b:
pb += 1
print("%d %d" % (pa,pb))
| true |
768cdae8a236ced71826723475db89573b4c68a3 | Python | 19leey/tensorflow_playground | /deep_mnist.py | UTF-8 | 1,923 | 3.234375 | 3 | [] | no_license | #MNIST data analysis using deep neural network analysis
# simple analysis did not account for 'image' analysis
# location/position matters in images
# add convolution network layer to handle images - 'moving and filtering (pixel positions)'
# inspects subsets of image
# learn features of image (curves)
# often paired with pool layer
# generalize each digit shape
# back propagation - update based on accuracy/results
#imports
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#use TF helper function to import MNIST data
mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)
#interactive session - don't need to pass sess
sess = tf.InteractiveSession()
#define placeholders for MNIST data
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
#reshape MNIST data back into 28 x 28 pixel x 1 grayscale value cube to be used by convolution NN
# '-1' - used to flatten shape or infer shape
# in our case 'infer shape' - don't know how many images
x_image = tf.reshape(x, [-1, 28, 28, 1], name='x_image')
#define helper functions
#RELU activation function
# if x <= 0, then x = 0
# if x > 0, then x = x
#truncated_normal - random values from a truncated normal distribution
# random positive values (in regards to RELU)
# stddev=0.1 - adds noise so that difference != 0
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(inital)
#constant - some constant (0.1 in this case)
# 0.1 > 0 (in regards to RELU)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
#convolution and pooling
# pooling after convolution to help control overfitting
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
| true |
1e83b39e3bb0532ad7df60e644ca28359f1b034e | Python | aalu1418/data-parsing | /github_data/devAnalysis.py | UTF-8 | 3,105 | 3 | 3 | [
"Unlicense"
] | permissive | import json
import matplotlib.pyplot as plt
import numpy as np
class DevData:
def __init__(self, fileLocation):
self.location = fileLocation
self.ranges = { # define ranges for sorting (metrics per year)
"additions": [1e2, 1e4],
"deletions": [1e2, 1e4],
"commits": [20, 100]
}
def run(self):
self.dataTypes = ["additions", "deletions", "commits"]
self.parse()
print("Metrics for categorization:")
for key in self.dataTypes:
print(key, "low: =<"+str(self.ranges[key][0])+" high: >="+str(self.ranges[key][1]))
self.active = {}
self.total = {}
for topic in self.data:
print("--------------------------------------")
print(topic['topic']+" tagged repos: "+str(topic["repositories"]))
self.yearlyStats(topic)
self.active[topic['topic']] = self.activeDevs(topic)
self.total[topic['topic']] = topic["weekly"]
self.comparisonPlot()
plt.show()
def parse(self):
with open(self.location) as f:
self.data = json.load(f)
def setRanges(self, obj):
self.ranges = obj
def yearlyStats(self, topic):
for key in self.dataTypes:
param = key[0]
parsed = [sum(topic["user"][user][param]) for user in topic["user"]]
low = len([i for i in parsed if i <= self.ranges[key][0]])
high = len([i for i in parsed if i >= self.ranges[key][1]])
print(topic['topic']+" devs - "+key+" ", "low: "+str(low), "medium: "+str(len(parsed)-low-high), "high: "+str(high))
def activeDevs(self, topic):
# committed at least once to a repository tagged with Conflux
return sum([np.array(topic["user"][user]["c"]) > 0 for user in topic["user"]])
def comparisonPlot(self):
fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots(3,1)
ax1.set_title("Weekly Developers")
ax1.set_xlabel("Week Number (past year)")
ax1.set_ylabel("Developers (submitted > 0 commits)")
ax1.set_yscale('log')
ax2[2].set_xlabel("Week Number (past year)")
ax2[0].set_ylabel("Commits per Week")
ax2[1].set_ylabel("Lines Added per Week")
ax2[2].set_ylabel("Lines Deleted per Week")
ax2[0].set_yscale("log")
ax2[1].set_yscale("log")
ax2[2].set_yscale("log")
for topic in self.active:
ax1.plot(self.active[topic], label=topic)
ax2[0].plot(self.total[topic]["c"], label=topic)
ax2[1].plot(self.total[topic]["a"], label=topic)
ax2[2].plot(self.total[topic]["d"], label=topic)
ax1.legend(loc='center left', bbox_to_anchor=(1, 0.5))
ax2[1].legend(loc='center left', bbox_to_anchor=(1, 0.5))
fig1.subplots_adjust(right=0.75)
fig2.subplots_adjust(right=0.75)
if __name__=='__main__':
# data = DevData("./data/devs_2020-12-02T12:15:41-05:00.json")
data = DevData("./data/devs_2020-12-07T17:14:59-05:00.json")
data.run()
| true |
549576b3b61aa99dd166632c6fa962f94a0fe3be | Python | FilipeMSoares/GameQualityAssessment | /code_pac/diceGame/model/game.py | UTF-8 | 1,826 | 2.75 | 3 | [] | no_license | '''
Created on 05/07/2015
@author: mangeli
'''
from collections import namedtuple
import os
import configparser
import json
from GameQualityAssessment.code_pac.configReader import ConfigReader
from GameQualityAssessment.code_pac.desafio.aux_old.modelo_old import Player
import csv
from operator import itemgetter
ItemTuple = namedtuple("ItemTuple", ['player', 'totalScore'])
class Game:
def __init__(self, gameNumber, gameRounds, fileName):
self.gameNumber = gameNumber
self.gameRounds = gameRounds
self.fileName = fileName
@classmethod
def retrieveList(cls):
games = []
i = 0
for gameFile in ConfigReader().listDiceGames():
with open(gameFile, 'rb') as csvfile:
statFile = csv.reader(csvfile, delimiter=';', quotechar='|')
statList = []
for line in statFile:
statList.append([int(line[0]), line[1], int(line[2])])
statList.sort(key=itemgetter(2), reverse=True)
statList.sort(key=itemgetter(0))
roundNumber = -1
preGame =[]
gameRound = []
for index,row in enumerate(statList):
if(roundNumber != row[0]):
if(index != 0):
preGame.append(gameRound)
roundNumber = row[0]
gameRound = []
gameRound.append(ItemTuple(player=row[1], totalScore=int(row[2])))
preGame.append(gameRound)
games.append(cls(i, preGame, gameFile))
i += 1
return sorted(games, key=lambda g: g.gameNumber)
if __name__ == '__main__':
lista = Game.retrieveList()
print (lista) | true |
a84d647f1c9d0bc1d0f726ad92d7bf359e80f345 | Python | xiaohe10/deepTR | /deprecated/DeepTR_run.py | UTF-8 | 1,802 | 2.765625 | 3 | [] | no_license | import gensim
import json
import math
def loadStopWords(file):
f = open(file)
stpw = []
for w in f.readlines():
stpw.append(w.replace('\r\n',''))
f.close()
return stpw
def loadDeepTRModel(file):
with open(file) as data_file:
data = json.load(data_file)
return data
return None
def sigmoid(x):
return 1 / (1 + math.exp(-x))
if __name__ == "__main__":
stopwords = loadStopWords('input/stopword.in')
model = gensim.models.Word2Vec.load_word2vec_format('input/GoogleNews-vectors-negative300.bin',binary=True)
feature_weights = loadDeepTRModel("output/1000000_alphais_0.in")
print feature_weights
while(True):
query = raw_input("query:")
if(query == "exit"): break
items = query.split(" ")
terms = []
w = []
for item in items:
try:
if(item in stopwords):
continue
w.append(model[item])
terms.append(item)
except KeyError:
# print "key Error", term, wordInAnswer
pass
if (len(w) > 0):
num = len(w)
p = len(w[0])
w_avarage = [0 for n in range(p)]
for wi in w:
for j in range(p):
w_avarage[j] += wi[j] / num
for j in range(len(w)):
for k in range(p):
w[j][k] -= w_avarage[k]
# get term weighthow many cigarettes per pack
for i in range(len(w)):
p = len(w[0])
weight = 0
for j in range(p):
weight += w[i][j] * feature_weights[j]
print terms[i], ":", sigmoid(weight)
else:
print "no valid term" | true |
f4e2fdf78ab2181bbb07a76884021d4c8c4ccd5b | Python | TNtube/basic-collide-system | /player.py | UTF-8 | 604 | 3.359375 | 3 | [] | no_license | import pygame
from pygame.locals import *
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((50, 50))
self.image.fill((255, 0, 0))
self.rect = self.image.get_rect()
self.rect.x = 250
self.rect.y = 150
self.velocity = 5
def blit(self, screen):
screen.blit(self.image, self.rect)
def move(self):
keys = pygame.key.get_pressed()
self.rect.x += (keys[K_RIGHT] - keys[K_LEFT]) * self.velocity
self.rect.y += (keys[K_DOWN] - keys[K_UP]) * self.velocity
| true |
6fe4e5f6803864b33a442c836c763b8babacf0ad | Python | zeinabmostafavi/img_process10 | /microsoft.py | UTF-8 | 453 | 2.515625 | 3 | [] | no_license | import cv2
import numpy as np
h = 300
w = h*2
img = np.full((h, w, 3), 80, dtype="uint8")
img[100:145, 100:145] = [0, 60, 255]
img[100:145, 155:200] = [0, 255, 0]
img[155:200, 100:145] = [255, 150, 0]
img[155:200, 155:200] = [0, 200, 255]
img = cv2.putText(img, 'Microsoft', (210, 170),
cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 5, cv2.LINE_AA)
cv2.imshow('out', img)
cv2.imwrite('Microsof.png', img)
cv2.waitKey()
| true |
ffa7f83e0b7a6d9890e735a04ae8f1705b491111 | Python | marcusfreire0504/API-Nomes | /main.py | UTF-8 | 1,120 | 3.3125 | 3 | [] | no_license | #https://servicodados.ibge.gov.br/api/docs/censos/nomes?versao=2
# Coletados pela primeira vez no Censo 2010, informa a frequência dos nomes por década de nascimento
#$ python3 main.py
import requests
import json
def main():
print("################################")
print("####Popularidade dos Nomes######")
print("################################")
print()
nome_input = input('Digite o nome a ser pesquisado: ')
if len(nome_input) < 3:
print("Quantidade de dígitos inválida!")
exit()
request = requests.get('https://servicodados.ibge.gov.br/api/v2/censos/nomes/{}'.format(nome_input))
print(request.json())
nome_data = request.json()
if 'erro' not in nome_data:
print('==> Nome Encontrado <==')
else:
print("{}: Nome invalido.".format(nome_input))
print("---------------------------------------")
option = int(input('Deseja realizar uma nova consulta ?\n1. Sim\n2. Não\n'))
if option == 1:
main()
else:
print('Saindo da consulta...')
if __name__ == "__main__":
main()
| true |
2590d869dd1de18b6d3d754ab74616a37093d555 | Python | fireconey/bigdata-learson | /class11.py | UTF-8 | 1,316 | 3.015625 | 3 | [] | no_license |
#一元非线性y=ax^n+a1x^n-1.....
#变成y=ax1+a1x1.......
import numpy as np
import pandas as mp
from sklearn.linear_model import LinearRegression as ln
import matplotlib as plt
data=mp.read_csv("D:\\bigdata\\4.3\\data.csv",encoding="utf-8")
x=data[["等级"]]
y=data[["资源"]]
font={"family":"SimHei"}
plt.rc("font",**font)
plt.rcParams['axes.unicode_minus'] = False
from pandas.plotting import scatter_matrix as mtr
#mtr(data[["等级","资源"]],alpha=0.8,figsize=(10,10),diagonal="kde")
resul=[]
ip=[]
sco=[]
from sklearn.preprocessing import PolynomialFeatures as pl
#找到最佳的n值
for i in range(225):
pf=pl(degree=i)
ip.append(i)
x1=pf.fit_transform(x)
lr=ln()
lr.fit(x1,y)
score=lr.score(x1,y)
sco.append(score)
data=mp.DataFrame({
"i":ip,
"s":sco
})
yu=data.sort_values(by=["s"],ascending=False).reset_index(drop=True)["i"][0]#删除原来的index
pf=pl(degree=10)
x1=pf.fit_transform(x)
lr=ln()
lr.fit(x1,y)
score=lr.score(x1,y)
#由于多元非线性的输入数变成了一元的数来计数的,所以预测的也要转换
for i in range(0,20):
tr=pf.fit_transform([[i]])
result=lr.predict(tr)
resul.append(result[0][0])
from matplotlib.pylab import plot,show,draw
plot(x,y)
plot(x,resul)
show()
| true |
2bef540d8b2ff44384a1278636bfb1a07a71f611 | Python | soultreemk/Coding-Test | /heap.py | UTF-8 | 1,902 | 3.8125 | 4 | [] | no_license | # 더 맵게
## (내가 짠거)
import heapq
def solution(scoville,K):
solution = 0
heapq.heapify(scoville)
while len(scoville) > 1:
a = heapq.heappop(scoville)
b = heapq.heappop(scoville)
solution += 1
heapq.heappush(scoville, a+2*b)
if scoville[0] >= K:
return solution
# while문을 다 돌고 난 후에도 (즉 a,b를 heap에 계속 넣어주는 작업을 scoville에 원소가 남아있을 때 까지 무한 반복) 했음에도
# 첫번째 요소가 k보다 값이 작으면 답을 찾을 수 없는 경우임
if scoville[0] < K:
return -1
#################################### 힙(heap) 완벽 이해 ###########################################
# 힙은 정렬되지 않은 리스트에서 최소 값을 먼저 추출해주는 구조
# 정렬되지 않은 배열에서 k번째로 큰 요소 추출
nums = [4,1,7,3,8,5]
k = 3
heap = list()
for n in nums:
heapq.heappush(heap, n)
print(heap)
>>> [1, 3, 5, 4, 8, 7]
for _ in range(len(nums)-k): # 0,1,2 차례로 pop
heapq.heappop(heap)
print(heap)
>>> [5,7,8]
print(heapq.heappop(heap))
>>> 5
## heapiy 이용
heapq.heapify(nums)
for _ in range(len(nums)-k):
heapq.heappop(nums)
print(heapq.heappop(nums))
>>> 5
## 최대 힙
# 힙에 튜플(tuple)를 원소로 추가하거나 삭제하면, 튜플 내에서 맨 앞에 있는 값을 기준으로 최소 힙이 구성되는 원리를 이용
nums = [4, 1, 7, 3, 8, 5]
heap = []
for num in nums:
heapq.heappush(heap, (-num, num)) # (우선 순위, 값)
print(heap)
>>> [(-8, 8), (-7, 7), (-5, 5), (-1, 1), (-3, 3), (-4, 4)]
while heap:
print(heapq.heappop(heap)[1]) # 값을 읽어올 때는 각 튜플에서 인덱스 1에 있는 값을 취하면 됨 (우선순위에는 관심 x)
print(heap)
>>> 8 7 5 1 3 4
| true |
11ebca8bae7e687c157af1929ab2da011c99db7a | Python | ronjacobvarghese/Stock-Market-Prediction | /models/svr_regressor.py | UTF-8 | 1,038 | 3.109375 | 3 | [] | no_license | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
class SvrRegressor:
def __init__(self, train, test):
self.train = train
self.test = test
self.sc = StandardScaler()
def fit_standize(self, x):
x = self.sc.fit_transform(x)
return x
def standize(self, x):
x = self.sc.transform(x)
return x
def predict(self):
x_train = self.train.drop('Close', axis=1)
y_train = self.train['Close']
x_test = self.test.drop('Close', axis=1)
x_train = self.fit_standize(x_train)
x_test = self.standize(x_test)
regressor = SVR(kernel='rbf')
regressor.fit(x_train, y_train)
pred = regressor(x_test)
return pred
def Visualize(self, preds):
self.test['Predictions'] = preds
plt.figure(figsize=(16, 8))
plt.plot(self.train['Close'])
plt.plot(self.test[['Close', 'Predictions']])
| true |
cd31a70358380708741f6eecd2967d82cfb2849c | Python | tsukudamayo/kanjiconv | /test_preprocess_web_recipe.py | UTF-8 | 6,983 | 2.609375 | 3 | [] | no_license | import json
from collections import OrderedDict
from preprocess_web_recipe import Dish
from preprocess_web_recipe import Instruction
from preprocess_web_recipe import load_json
# from preprocess_web_recipe import fetch_ingredients
# from preprocess_web_recipe import fetch_instruction
# from preprocess_web_recipe import fetch_title
# from preprocess_web_recipe import build_dishes
# from preprocess_web_recipe import fetch_unit
def test_load_json():
expected = {
"a": "あ",
"b": "い",
"c": {
"d": "う",
"e": "え",
},
}
test_data = './test_data/sample_test_json.json'
result = load_json(test_data)
assert result == expected
def test_fetch_ingredients():
expected = [
OrderedDict([
("description", "しゅんぎく"),
("quantityText", "200g"),
("ingredientId", 0),
("classificationId", 0),
("intermediateId", 0)
]),
OrderedDict([
("description", "菊の花(食用)"),
("quantityText", "50g"),
("ingredientId", 0),
("classificationId", 0),
("intermediateId", 0)
]),
OrderedDict([
("description", "酢"),
("quantityText", "大さじ1"),
("ingredientId", 0),
("classificationId", 0),
("intermediateId", 0)
]),
OrderedDict([
("description", "しょうゆ"),
("quantityText", "大さじ1/2"),
("ingredientId", 0),
("classificationId", 0),
("intermediateId", 0)
]),
OrderedDict([
("description", "だし"),
("quantityText", "大さじ1"),
("ingredientId", 0),
("classificationId", 0),
("intermediateId", 0)
]),
]
test_data = './test_data/10100006.json'
data = load_json(test_data)
dish = Dish(data)
# instance = dish.build()
result = dish.fetch_ingredients(data)
assert result == expected
def test_fetch_instruction():
expected = [
{
"steps": 1,
"description": "しゅんぎくは、茎のかたいところはとり除き、洗います。",
},
{
"steps": 2,
"description": "熱湯で30秒ほどゆで、すぐ水にとってさまし、手早く水気をしぼって、4cm長さに切ります。",
},
{
"steps": 3,
"description": "菊の花は、花びらをむしります。",
},
{
"steps": 4,
"description": "水カップ3をわかして酢を入れ、菊の花びらを約20秒ゆでます。水にとってさらし、水気をしっかりしぼります。",
},
{
"steps": 5,
"description": "しょうゆとだしを合わせます(割りじょうゆ)。",
},
{
"steps": 6,
"description": "しゅんぎくと菊の花をほぐして混ぜ、割りじょうゆをかけます。",
},
]
test_data = './test_data/10100006.json'
data = load_json(test_data)
result = Instruction.fetch_instruction(data)
assert result == expected
def test_fetch_title():
expected = "しゅんぎくと菊の花のおひたし"
test_data = './test_data/10100006.json'
data = load_json(test_data)
result = Dish.fetch_title(data)
assert result == expected
def test_build_dishes():
expected = {
"title": "しゅんぎくと菊の花のおひたし",
"cookingTool": "",
"nutrition": [
{"note": ""},
{"salt": 0.0},
{"protein": 0.0},
{"calory": 15},
{"lipid": 0.0},
{"carbohydrate": 0.0},
],
"ingredients": [
OrderedDict([
("description", "しゅんぎく"),
("quantityText", "200g"),
("ingredientId", 0),
("classificationId", 0),
("intermediateId", 0)
]),
OrderedDict([
("description", "菊の花(食用)"),
("quantityText", "50g"),
("ingredientId", 0),
("classificationId", 0),
("intermediateId", 0)
]),
OrderedDict([
("description", "酢"),
("quantityText", "大さじ1"),
("ingredientId", 0),
("classificationId", 0),
("intermediateId", 0)
]),
OrderedDict([
("description", "しょうゆ"),
("quantityText", "大さじ1/2"),
("ingredientId", 0),
("classificationId", 0),
("intermediateId", 0)
]),
OrderedDict([
("description", "だし"),
("quantityText", "大さじ1"),
("ingredientId", 0),
("classificationId", 0),
("intermediateId", 0)
]),
],
}
test_data = './test_data/10100006.json'
data = load_json(test_data)
title = Dish.fetch_title(data)
ingredients = Dish.fetch_ingredients(data)
result = Dish.build_dishes(title, ingredients)
assert result == expected
def test_fetch_units():
expected = "4人分"
test_data = './test_data/10100006.json'
data = load_json(test_data)
result = Dish.fetch_unit(data)
assert result == expected
| true |
fbf62f39e443261b8ddda27e410aee37c345590a | Python | NishKoder/Python-Repo | /Chapter 2/string.py | UTF-8 | 293 | 4.25 | 4 | [] | no_license | # String Concatnet - its only work on String to String
first_name = "Adam"
second_name = "Eve"
full_name = first_name + " " + second_name
print(full_name + str(4)) # str() - convert to string
# Can use multiply * with string - string will print with multiplyer time
print(full_name * 5)
| true |
863f03503ca3feb324fa6a9f2fdf9a0f842501f2 | Python | daor174/valken | /string problemas/PROBLEMA 1.py | UTF-8 | 2,670 | 4.34375 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 3 02:42:11 2021
@author: Omen 15
"""
'''
Se pide realizar un programa en Python que lea dos Strings compuestos por palabras separadas por un espacio en blanco y ya ordenadas alfabéticamente, y que genere un tercer string (resultado) que contenga todas las palabras ordenadas.
Ejemplo:
String 1: BANANA CASA LUNA MARQUESINA TORRE ZAPATO.
String 2: ARENA FLOR GONDOLA LAPIZ NARANJA PLATANO VIVIENDA.
Resultado: ARENA BANANA CASA FLOR GONDOLA LAPIZ LUNA MARQUESINA NARANJA PLATANO TORRE VIVIENDA ZAPATO.
Observaciones:
- Cada string está terminado en un punto y el string resultante debe terminar en punto (uno solo).
- Las palabras tienen solo letras mayúsculas y no existen tildes (vocales acentuadas) ni la letra Ñ.
- No es necesario utilizar arreglos (PERO PUEDEN USARSE).
- Ayuda: El computador sabe que “LAPIZ” es menor que “LUNA”.
- No utilizar función sort del Python.
'''
string1 = 'BANANA CASA LUNA MARQUESINA TORRE ZAPATO.'
string2 = 'ARENA FLOR GONDOLA LAPIZ NARANJA PLATANO VIVIENDA.'
string3 = ''
sw = True
#string1 = input('')
#string2 = input('')
while sw == True:
stringIndice1 = string1.find(' ')
stringIndice2 = string2.find(' ')
if stringIndice1 == -1:
if string1.find('.') != -1:
palabra1 = string1[0: ]
else:
palabra1 = string1[0:stringIndice1]
if stringIndice2 == -1:
if string2.find('.') != -1:
palabra2 = string2[0: ]
else:
palabra2 = string2[0:stringIndice2]
if palabra1.find('.') == -1 and palabra2.find('.') == -1:
if palabra1 < palabra2:
string3 = string3 + palabra1 + ' '
string1 = string1[stringIndice1 + 1: ]
else:
string3 = string3 + palabra2 + ' '
string2 = string2[stringIndice2 + 1: ]
else:
if palabra1.find('.') == -1:
if palabra1 < palabra2:
string3 = string3 + palabra1+ ' '
string1 = string1[stringIndice1 + 1: ]
else:
string3 = string3 + palabra2[0:len(palabra2)-1] + ' '
string2 = 'á.'
else:
if palabra2 < palabra1:
string3 = string3 + palabra2 + ' '
string2 = string2[stringIndice2 + 1: ]
else:
string3 = string3 + palabra1[0:len(palabra1)-1] + ' '
string1 = 'á.'
if palabra1.find('.') != -1 and palabra2.find('.') != -1:
sw = False
print(string3)
input() | true |
104ea5809f0e7acddfab58e1407010dd729ca90c | Python | nomizo-iox/Python-Flask | /flaskblog.py | UTF-8 | 1,834 | 2.609375 | 3 | [] | no_license | from flask import Flask, render_template, url_for, flash, redirect
from flask_wtf import form
from forms import RegistrationForm, LoginForm
app = Flask(__name__)
# Protects modifying cookies and crossight forgeries
app.config['SECRET_KEY'] = '649d7e67a5dfae7697963b041705565d'
posts = [
{
'author': 'Samuel Ademola',
'title': 'Blog Post',
'content': 'First post content',
'date_posted': 'April 20, 2019'
},
{
'author': 'Jordan Dockery',
'title': 'Blog Post 2',
'content': 'Second post content',
'date_posted': 'April 20, 2020'
}
]
@app.route('/')
@app.route('/home')
def home():
return render_template('home.htm', posts=posts)
@app.route('/about')
def about():
return render_template('about.htm', title='About')
@app.route('/register', methods=['GET', 'POST'])
def register():
register_form = RegistrationForm()
# Use 'Flash' message when user has registered sucessfully
if register_form.validate():
flash(f'Account created for {register_form.username.data}!', 'success')
# The arguement inside 'URL_FOR', is the name of the function, and not html page
return redirect(url_for('home'))
return render_template('register.htm', title='Register', form=register_form)
@app.route('/login', methods=['GET', 'POST'])
def login():
login_form = LoginForm()
if login_form.validate_on_submit():
if login_form.email.data == 'ademola1@gmail.com' and login_form.password.data == 'password':
flash('You have been logged in!', 'success')
return redirect(url_for('home'))
else:
flash('Login Unsuccessful. Please check username and passowrd', 'danger')
return render_template('login.htm', title='Login', form=login_form)
if __name__ == "__main__":
app.run(debug=True)
| true |
2f53a07c6aa09dce404ee0398b0706ea79f7ff1a | Python | Cgalvispadilla/reto_sofka | /Carro.py | UTF-8 | 297 | 2.671875 | 3 | [] | no_license | class Carro:
def __init__(self, conductor):
self.__conductor = conductor
def get_conductor(self):
return self.__conductor
def set_conductor(self, value):
self.__conductor = value
conductor = property(get_conductor, set_conductor, None, None)
| true |
503bc8a87dbc0f15cff43d9c8c23bb68344fc7af | Python | qsjhyy/Dormitory-Management-System | /DormitoryManagementSystem.py | UTF-8 | 14,717 | 3.625 | 4 | [] | no_license | """
学生信息包括
学号(唯一) 姓名 性别 年龄 寝室(一间寝室最多安排4人)
寝室编号 男生(100 101 102) 女生(200 201 202)
功能包括:
1. 可以录入学生信息
2. 录入过程中可以为其分配寝室(可选自动分配或手动分配,手动分配的话如果选择的寝室人员已满,提示重新分配)
3. 可以打印各寝室人员列表(做到表格打印是加分项)
4. 可以用学号索引打印特定学生信息,可以打印所有学生信息(做到表格打印是加分项)
5. 可以为学生调整寝室(一人调整到其他寝室,两人交换寝室等,自由发挥)
6. 可以将所有信息存入文件(json格式)
7. 程序启动时,将文件中的学生信息自动导入系统
"""
# -*- coding: UTF-8 -*-
import json
# 系统主菜单选项宏
RECORD_INFO = '1'
DELETE_INFO = '2'
FIND_INFO = '3'
SHOW_INFO = '4'
CHANGE_ROOM = '5'
QUIT_SYSTEM = '0'
# query_student_id函数mode宏
ID_EXISTS = 1
DELETE_ID = 2
INFO_RETURN = 3
# 学生信息打印的统一开头
print_info = '''
============================================================
学号\t\t姓名\t\t性别\t\t年龄\t\t寝室号
------------------------------------------------------------'''
# 加载json文件中的学生信息
def load_json_file():
with open("information.json", "r", encoding='utf-8') as file: # 加载保存json文件的编码都为utf-8
return json.load(file) # 将导入的学生信息返回到全局变量student_info_dict(字典类型)
# 将学生信息保存在json文件
def save_json_file():
with open("information.json", "w", encoding='utf-8') as file:
json.dump(room_info_dict, file, ensure_ascii=False) # 传入文件描述符,和dumps一样的结果,关闭默认以ASCII码存入json
# 根据学号遍历、调整学生信息
def query_student_id(query_id, mode):
for room in room_info_dict.values():
for stu_info in room["student"]:
if query_id == stu_info["student_id"]:
if mode == ID_EXISTS:
return True
elif mode == DELETE_ID:
room["student"].pop(room["student"].index(stu_info)) # 删除寝室字典里面的该生信息
room["count"] -= 1
return True
else:
return room["student"][room["student"].index(stu_info)] # 按学号搜索学生的学生信息
return False
# 录入学生信息
def record_student_info():
new_student_info = {"student_id": "", "name": "", "sex": "", "age": 0, "room": ""} # 新增学生的个人信息集
# 判断输入学号是否合法
while True: # 由于学号格式为整型,所以加了异常和格式转换,阻止了输入为1.1和1、1之类的情况
try:
new_student_info["student_id"] = str(int(input("请输入要录入学生的学号:\n")))
if query_student_id(new_student_info["student_id"], 1): # 学号是否唯一
print("您输入的学号已存在(提示:有效数字之前的零无效),请重新输入")
elif new_student_info["student_id"] == '0':
print("抱歉,学号不能为零,请重新输入")
else:
break
except ValueError:
print("您输入学生学号格式有误,请重新输入")
# 判断输入姓名是否合法
while not new_student_info["name"]: # 姓名仅做了输入为空判断
new_student_info["name"] = input("请输入学生姓名(不能为空哦):\n")
# 判断输入性别是否合法
while new_student_info["sex"] not in ("男", "女"): # 判断性别输入是否为(男/女)
new_student_info["sex"] = input("请输入性别(男/女):\n")
# 判断年龄输入是否合法
while True: # 由于输入格式为整型,所以加了异常和格式转换,阻止了输入为.和、之类的情况
try:
new_student_info["age"] = int(input("请输入年龄,范围(6-48):\n"))
if int(new_student_info["age"]) not in range(6, 48): # 判断年龄输入是否合法
print("您输入的年龄范围不符合规定,请重新输入")
else:
break
except ValueError:
print("您输入的年龄格式有误,请重新输入")
k = 1 # k = 1,默认为女生
if new_student_info["sex"] == "男": # 提前用k值标识性别,方便后面为其分配对应的寝室
k = 0 # k = 0为男生
while True:
info = """========================寝室分配============================
1.自动分配
2.手动分配
"""
print(info)
choice1 = input("请选择你需要进行的操作:\n")
if choice1 == "1": # 自动分配
for i in (100 + 100*k, 101 + 100*k, 102 + 100*k): # 顺序遍历每一间寝室
i = str(i)
if concreteness_allot_step(room_info_dict[i], new_student_info, i): # 寝室分配函数,寝室已满会分配失败,返回False
break
if i >= str(102 + 100*k):
print("抱歉,所有符合规定的寝室已住满")
break
break
elif choice1 == "2": # 手动分配
while True:
room_id = input("请输入要分配的寝室号:\n")
if int(room_id) not in (100 + 100*k, 101 + 100*k, 102 + 100*k):
print("您输入的寝室号不符合规定,请重新输入:")
elif not concreteness_allot_step(room_info_dict[room_id], new_student_info, room_id):
print("您输入的寝室号对应的寝室已住满,请重新输入:")
else:
break
break
else:
print("请按照提示输入选项对应的数字:\n")
save_json_file()
print("新增学生信息录入成功")
# 删除学生信息
def delete_student_info():
delete_id = '0'
while not query_student_id(delete_id, ID_EXISTS): # 判断输入的学号是否存在
delete_id = input("请输入要删除学生的学号(要确保学生信息存在哦):\n") # 输入要删除学生的学号
query_student_id(delete_id, DELETE_ID) # 删除寝室字典里面的该生信息
save_json_file()
print("已删除学号{}的学生信息".format(delete_id))
# 显示寝室信息
def show_room_info():
print("按寝室显示学生信息:", end="")
print(print_info)
for room_id in room_info_dict:
print("{}号寝室,人员如下:".format(room_id))
for stu_info in room_info_dict[room_id]["student"]:
print("{}\t\t{}\t\t{}\t\t{}\t\t{}"
.format(stu_info["student_id"], stu_info["name"], stu_info["sex"], stu_info["age"], stu_info["room"]))
# 按学号搜索并显示学生信息
def show_student_info():
find_id = input("请你输入想要查找的学号:\n")
find_info = query_student_id(find_id, INFO_RETURN)
if find_info:
print("{}号学生信息如下:".format(find_id), end="")
print(print_info)
print("{}\t\t{}\t\t{}\t\t{}\t\t{}".format(
find_info["student_id"], find_info["name"], find_info["sex"], find_info["age"], find_info["room"]))
else:
print("系统未录入此学号的学生")
# 具体分配步骤
def concreteness_allot_step(room_info, student_info, room_id):
if student_info["room"] == room_id: # 在学生个人信息中备注其寝室号
print("该生已在此寝室")
room_info["student"].append(student_info) # 将学生信息添加到寝室信息字典中,抵消后续的删除操作
room_info["count"] += 1
return True
if room_info["count"] < 4: # 判断寝室是否未住满
student_info["room"] = room_id # 在学生个人信息中备注其寝室号
room_info["student"].append(student_info) # 将学生信息添加到寝室信息字典中
room_info["count"] += 1
print("分配成功")
return True
else:
return False
# 调整学生宿舍
def change_student_room(): # 可将学生调整到空余寝室,或者和其他学生互换寝室
while True:
info = """========================调整寝室============================
1.一人调整寝室
2.两人互换寝室
"""
print(info)
choice1 = input("请选择你需要进行的操作:\n")
if choice1 == "1": # 一人调整寝室
change_id = '0'
while not query_student_id(change_id, ID_EXISTS): # 判断输入的学号是否存在
change_id = input("请输入要调整学生的学号(要确保学生信息存在哦):\n") # 输入调整学生的学号
change_info = query_student_id(change_id, INFO_RETURN)
k = 1 # k = 1,默认为女生
if change_info["sex"] == "男": # 用k值标识性别,方便后面为其分配对应的寝室
k = 0 # k = 0为男
change_room = 0
# 判断输入寝室号是否合法
while True: # 由于寝室号格式转换为整型,所以加了异常和格式转换,阻止了输入为1.1和1、1之类的情况
try:
if change_room not in (100 + 100 * k, 101 + 100 * k, 102 + 100 * k): # 寝室号是否合法
change_room = int(input("请输入要调整的寝室号(男女生要分配到与其对应的寝室哦):\n"))
else:
break
except ValueError:
print("您输入的寝室号格式有误,请重新输入")
change_room = str(change_room)
if not concreteness_allot_step(room_info_dict[change_room], change_info, change_room):
print("{}号寝室已满,人员如下:".format(change_room))
print(print_info)
for stu_info in room_info_dict[change_room]["student"]:
print("{}\t\t{}\t\t{}\t\t{}\t\t{}".format(
stu_info["student_id"], stu_info["name"], stu_info["sex"], stu_info["age"], stu_info["room"]))
if 'y' == input("是否与其中一人交换宿舍(y/n)"):
another_change_id = input("请输入与之交换寝室的学生学号") # 输入被交换学生的学号
another_change_info = query_student_id(another_change_id, INFO_RETURN) # 获取被交换学生的信息
another_change_room = change_info["room"] # 获取交换学生原有宿舍
# 删除学生原来的宿舍信息
query_student_id(change_id, DELETE_ID)
query_student_id(another_change_id, DELETE_ID)
# 更新被交换学生宿舍信息
concreteness_allot_step(room_info_dict[another_change_room], another_change_info,
another_change_room)
# 更新交换学生宿舍信息
concreteness_allot_step(room_info_dict[change_room], change_info, change_room)
break
else:
query_student_id(change_id, DELETE_ID)
break
elif choice1 == "2": # 两人互换寝室
one_change_id = '0'
while not query_student_id(one_change_id, ID_EXISTS): # 判断输入的学号是否存在
one_change_id = input("请输入第一个要交换学生的学号(要确保学生信息存在哦):\n") # 输入第一个交换学生的学号
one_change_info = query_student_id(one_change_id, INFO_RETURN) # 获取第一个交换学生的信息
one_change_room = one_change_info["room"] # 获取第一个交换学生原有宿舍
two_change_id = '0'
while not query_student_id(two_change_id, ID_EXISTS): # 判断输入的学号是否存在
two_change_id = input("请输入另一个要交换学生的学号(要确保学生信息存在哦):\n") # 输入另一个交换学生的学号
two_change_info = query_student_id(two_change_id, INFO_RETURN) # 获取另一个交换学生的信息
two_change_room = two_change_info["room"] # 获取第一个交换学生原有宿舍
# 删除学生原来的宿舍信息
query_student_id(one_change_id, DELETE_ID)
query_student_id(two_change_id, DELETE_ID)
# 更新第一个交换学生宿舍信息
concreteness_allot_step(room_info_dict[two_change_room], one_change_info, two_change_room)
# 更新另一个交换学生宿舍信息
concreteness_allot_step(room_info_dict[one_change_room], two_change_info, one_change_room)
break
else:
print("请按照提示输入选项对应的数字:\n")
save_json_file()
print("调整学生寝室成功")
# 系统功能菜单
def show_menu():
while True:
info = """
欢迎使用[寝室管理系统]:
1.录入学生信息
2.删除学生信息
3.搜索学生信息
4.显示学生信息
5.调整学生宿舍
0.退出管理系统
"""
print(info)
choice = input("请输入你想进行的操作是:\n")
if choice == RECORD_INFO: # 1.录入学生信息
record_student_info()
elif choice == DELETE_INFO: # 2.删除学生信息
delete_student_info()
elif choice == FIND_INFO: # 3.搜索学生信息
show_student_info()
elif choice == SHOW_INFO: # 4.显示学生信息
show_room_info()
elif choice == CHANGE_ROOM: # 5.调整学生宿舍
change_student_room()
elif choice == QUIT_SYSTEM: # 0.退出管理系统
print("欢迎再次使用学生管理系统!")
break
else:
print("您的输入有误,请您输入操作相对应的数字:")
print("按enter键继续...")
input()
if __name__ == "__main__":
room_info_dict = load_json_file() # 加载json文件的学生信息到字典中
show_menu() # 显示系统主菜单,并在其中循环
save_json_file() # 将学生信息保存在json文件
| true |
f3c72f955293fd4ca0c48b1a7bf40c9d08e7e37c | Python | 5l1v3r1/RayTracing | /camera.py | UTF-8 | 509 | 3.25 | 3 | [] | no_license | from ray import Ray
from vector import Vector
class Camera:
def __init__(self):
self.lowerLeftCorner = Vector(-2.0, -1.0, -1.0)
self.horizontal = Vector(4.0, 0.0, 0.0)
self.vertical = Vector(0.0, 2.0, 0.0)
self.origin = Vector(0.0, 0.0, 0.0)
def getRay(self, u, v):
direction = self.lowerLeftCorner + self.horizontal.multiply_scalar(u)
direction = direction + self.vertical.multiply_scalar(v) - self.origin
return Ray(self.origin, direction)
| true |
5ee1308a72c45f609db6db205a40b968290b1c5d | Python | Paletimeena/Prac_data | /Meena (copy)/python/programs/8-02/rt1.py | UTF-8 | 292 | 3.671875 | 4 | [] | no_license |
def square(num1=1,num2=100):
list1=[]
global x
for index in range(100+1):
sqr=index**2
if((sqr>=num1) and (sqr<=num2)):
list1.append(sqr)
x+=1
if sqr>num2:
break
print list1
num1=input("enter the num1")
num2=input("enter the num2")
x=0
square(num1,num2)
#print list1
| true |
d501c92b2099a458daad30b093303a16083e54f1 | Python | gleiss/rapid | /examples/relational/hamming-weight/1-hw-equal-arrays.spec | UTF-8 | 560 | 3.484375 | 3 | [] | no_license | // Variation 1: The Hamming weight of two identical arrays is the same.
(set-traces 2)
func main()
{
const Int alength;
const Int[] a;
Int i = 0;
Int hammingWeight = 0;
while (i < alength)
{
if (a[i] != 0)
{
hammingWeight = hammingWeight + 1;
}
else
{
skip;
}
i = i + 1;
}
}
(axiom
(<= 0 (alength t1))
)
(axiom
(<= 0 (alength t2))
)
(conjecture
(=>
(and
(= (alength t1) (alength t2))
(forall ((posA Int))
(= (a posA t1) (a posA t2))
)
)
(= (hammingWeight main_end t1) (hammingWeight main_end t2))
)
)
| true |
12e891d3c16a38a82be60582ba8552c46271574b | Python | EsaikaniL/python | /hcf.py | UTF-8 | 237 | 3.265625 | 3 | [] | no_license | # your code goes here
def HCF(x, y):
c=1
k=0
if(x>y):
s=x
else:
s=y
while(c<=s):
if(x%c==0 and y%c==0):
k=c
c+=1
print(k)
s=str(input())
l=s.split(" ")
num1 = int(l[0])
num2 = int(l[1])
HCF(num1, num2)
| true |
d818c127055de6825c3f893daee303dc088966dc | Python | RicLee0124/spider_demo | /spider/firstspider/FansLocation.py | UTF-8 | 3,259 | 3.21875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/10/15 15:01
# @Author : RicLee
# @Site :
# @File : FansLocation.py
# @Software: PyCharm
from collections import Counter
from pyecharts import Geo
import json
from pyecharts import Bar
def render():
# 获取所有城市信息
cities = []
with open('comments.txt', mode='r', encoding='utf-8') as f:
rows = f.readlines()
for row in rows:
rowsplits = row.split(',')
if len(rowsplits)>3:
city = rowsplits[2]
if city != '':
cities.append(city)
# 对城市数据和坐标文件中的地名进行处理
handle(cities)
# 统计每个城市出现的次数
# data = [] # [('南京',25),('北京',59)]
# for city in set(cities):
# data.append((city, cities.count(city)))
data = Counter(cities).most_common()
# 根据城市数据生成地理坐标图
geo = Geo(
"《一出好戏》粉丝位置分布",
"数据来源:猫眼",
title_color="#fff",
title_pos="center",
width=1200,
height=600,
background_color="#404a59",
)
attr, value = geo.cast(data)
geo.add(
"",
attr,
value,
visual_range=[0, 3500],
visual_text_color="#fff",
symbol_size=15,
is_visualmap=True,
)
geo.render('粉丝位置分布.html')
# 根据城市数据生成柱状图
cities_top20 = Counter(cities).most_common(20) # 返回出现次数最多的20条
bar = Bar("《一出好戏》粉丝来源排行榜TOP20", '数据来源:猫眼', title_pos='center', width=1200, height=600)
attr, value = bar.cast(cities_top20)
bar.add("", attr, value)
bar.render('粉丝来源排行榜-柱状图.html')
# 处理地名数据,解析坐标文件中找不到地名的问题
def handle(cities):
with open(
'D:\\python3 workspace\\spider\\venv\\Lib\\site-packages\\pyecharts\\datasets\\city_coordinates.json',
mode='r', encoding='utf-8') as f:
data = json.loads(f.read()) # 将str转换为dict
# 循环判断处理
data_new = data.copy() # 复制一份地名数据
for city in set(cities):
count = 0
for k in data:
count += 1
if k == city:
break
if k.startswith(city): # 处理简写的地名,如南京市 简写为 南京
data_new[city] = data[k]
break
if k.startswith(city[0:-1]) and len(city) >= 3: # 处理行政变更的地名,如溧水县 改为 溧水区
data_new[city] = data[k]
break
# 处理不存在的情况
if count == len(data):
while city in cities:
cities.remove(city)
# print(len(data), len(data_new))
# 写入覆盖坐标文件
with open(
'D:\\python3 workspace\\spider\\venv\\Lib\\site-packages\\pyecharts\\datasets\\city_coordinates.json',
mode='w', encoding='utf-8') as f:
f.write(json.dumps(data_new, ensure_ascii=False)) # 将dict转换为str,指定ensure_ascii=False支持中文
if __name__ == '__main__':
render() | true |
a96be8f29f2078a15b4464bdb977399ecd314afd | Python | SalingerMa/Spider | /Scrapy/mySpider/test1.py | UTF-8 | 274 | 2.984375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
def dtes():
q = 1
for each in [1,2,3,4,5]:
yield {"rank":"the %s test1" % each,
"desc":"the %s test2" % each,
}
print(q)
q+=1
if q ==5:
print(q)
for i in dtes():
print(i)
| true |
3925a0d1bb4f4daa2c02cf50d76f1a9ae3c07bf5 | Python | HardPlant/CryptoTransfer | /encrypted_chat.py | UTF-8 | 1,362 | 3.0625 | 3 | [] | no_license | import server
import client
def get_input(text):
return input(text)
if __name__ == '__main__':
try:
print("서버 모드로 ECB 모드 대신 CTR 모드를 사용합니까? (Y/N)")
resp = input()
if resp == 'Y':
mode = 'CTR'
else:
mode = 'ECB'
print("메시지를 들을 서버 포트: ")
server_port = int(input())
server = server.EchoServer(port=server_port, mode=mode)
server.start()
while True:
print("메시지 모드로 ECB 모드 대신 CTR 모드를 사용합니까? (Y/N)")
resp = input()
if resp == 'Y':
client_mode = 'CTR'
else:
client_mode = 'ECB'
print("메시지를 보낼 서버 주소:")
client_host = input()
print("메시지를 보낼 서버 포트:")
client_port = int(input())
client = client.Client(host=client_host, port = client_port, mode = client_mode)
while True:
print("메시지를 입력하세요. (종료: X)")
msg = input()
if msg == 'X':
break
client.send(msg)
print("메시지를 잘 보냈습니다.")
finally:
if server:
server.stop()
| true |
b9b974b0e2ab1bbbe152934514019176a51c3b24 | Python | Shaar68/grab-screen | /grab_screen/storages/base.py | UTF-8 | 291 | 2.578125 | 3 | [
"MIT"
] | permissive | class File(object):
IMAGE = 'image'
GIF = 'gif'
VIDEO = 'video'
def __init__(self, file_type, path):
self.file_type = file_type
self.path = path
class BaseStorage(object):
def upload_image(self, stream, fmt='png'):
raise NotImplementedError()
| true |
640ac588197570ac8b8aa3a331412bd5ba345073 | Python | pacificland68/Engineer-coding-challenge-2 | /exam.py | UTF-8 | 2,897 | 3.25 | 3 | [] | no_license | import csv
import json
import re
from collections import OrderedDict
#quickSort
def quickSort(arr, left, right):
i = left
j = right
if i <= j:
temp = arr[left]
while i != j:
while i < j and float(arr[j]['PPG']) <= float(temp['PPG']):
j -= 1
arr[i] = arr[j]
while i < j and float(arr[i]['PPG']) >= float(temp['PPG']):
i += 1
arr[j] = arr[i]
arr[j] = temp
quickSort(arr, left, i-1)
quickSort(arr, i+1, right)
#find the gold, silver and bronze player
def calculate(players):
quickSort(players, 0, len(players)-1)
#find the gold, silver and bronze player
def award(result):
leaders = []
num = ["Gold", "Silver", "Bronze"]
for i in range(3):
leader = OrderedDict()
leader[num[i]] = players[i]["Name"]
leader["PPG"] = players[i]["PPG"]
leaders.append(leader)
result['Leaders'] = leaders
def category(result):
position = OrderedDict()
po = [0,0,0,0,0]
po_name = ["PG", "C", "PF", "SG", "SF"]
for row in result["Players"]:
if row["Position"] == po_name[0]:
po[0] += 1
elif row["Position"] == po_name[1]:
po[1] += 1
elif row["Position"] == po_name[2]:
po[2] += 1
elif row["Position"] == po_name[3]:
po[3] += 1
elif row["Position"] == po_name[4]:
po[4] += 1
for i in range(5):
position[po_name[i]] = po[i]
result[""] = position
def average_height(result):
sum = 0.0
for row in result["Players"]:
temp = row["Height"].replace(' ','').replace("ft", ',').replace("in",',')
feet = float(temp.split(',')[0])
inn = float(temp.split(',')[1])*0.0833
sum = sum + (feet + inn)*30.48
average = sum / float(14)
# print(average)
result['AverageHeight'] = round(average,2)
with open('chicago-bulls.csv') as csv_file:
csv_reader = csv.reader(csv_file)
result = OrderedDict()
#calculate average
total_PPG = 0.0
next(csv_reader, None)
players = []
for row in csv_reader:
players_info = OrderedDict()
players_info["Id"] = row[0]
players_info["Position"] = row[1]
players_info["Number"] = row[2]
players_info["Country"] = row[3]
players_info["Name"] = row[4]
players_info["Height"] = row[5]
players_info["Weight"] = row[6]
players_info["University"] = row[7]
players_info["PPG"] = row[8]
total_PPG += float(row[8])
players.append(players_info)
result['Players'] = players
quickSort(players, 0, len(players)-1)
result['AveragePPG'] = round(total_PPG/14, 2)
award(result)
category(result)
average_height(result)
print(json.dumps(result, indent=4))
| true |
75c4d3d8c55d3869e29349d8c4ac963563473772 | Python | HuangeHei/hcwy | /hc_django/common/UserAuth.py | UTF-8 | 2,447 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | from user.models import User,Root
from django.shortcuts import HttpResponse
class UserAuth():
def __init__(self):
pass
@staticmethod
def is_login(req): # 是否登录
if req.session.get('is_login',False) and req.session.get('user_name',False):
return True
else:
return False
@staticmethod
def out_login(req): # 用户登出
req.session.delete()
return True
@staticmethod
def login(req,user_name): # 用户登录
req.session['is_login'] = True
req.session['user_name'] = user_name
return True
@staticmethod
def get_login(req): #获取用户登录状态
if req.session.get('is_login', None):
if req.session['is_login'] == True:
retUser = {
'is_login': True,
'username': req.session['user_name']
}
return retUser
else:
return False
else:
return False
def auth(root):
def outer_wrapper(func):
def wap(*args, **kwargs):
try:
root_obj = Root.objects.get(root_name = root) # 这一步主要怕蠢萌程序员
print(root_obj)
except Exception as E:
print('程序内部') #内部报错信息 以后写入到日志系统中
return HttpResponse('程序内部发生问题')
if UserAuth.is_login(args[1]):
try:
obj = User.objects.get(user_name = args[1].session['user_name'])
try:
is_ok = obj.user_root.filter(root_name = root_obj.root_name)
except Exception as e:
return HttpResponse('用户权限获取失败')
except Exception as e:
return HttpResponse('not,用户不存在')
if is_ok:
return func(*args, **kwargs) #执行函数
else:
return HttpResponse('not,无权限')
else:
return HttpResponse('not,没有登录')
return wap
return outer_wrapper
| true |
7f663704ecd14e739a08ca444625000e2dc14e8d | Python | KilHwanKim/programmers | /Programmers/level1/자릿수더하기.py | UTF-8 | 100 | 2.75 | 3 | [] | no_license | def solution(n):
answer = 0
for i in list(str(n)):
answer+=int(i)
return answer
| true |
4d93ccd7fea7e79019029d20d6c3aa9b8c3184ce | Python | jagusgon/rs-active-learning | /plot_nym_stat.py | UTF-8 | 3,161 | 2.765625 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mplc
import argparse
from datareader import DataReader as Data
from myutils import msg
thresh_default = 50
stat_options = {1: 'mean', 2: 'variance', 3:'stddev'}
stat_option_default = 2
outfile_default = Data.figure_dir + "nym_stat_plot.png"
parser = argparse.ArgumentParser(description="Plot the mean or variance of each group by item number. The size of each bubble corresponds to the square root of the number of ratings for that distribution. Only bubbles with at least the threshold number of ratings are plotted.")
parser.add_argument("-o", help=f"1 to plot mean, 2 to plot variance, 3 to plot stddev (default {stat_option_default})", type=int, default=stat_option_default)
parser.add_argument("-b", help="index of the item to begin plotting from", default=None, type=int)
parser.add_argument("-n", help="number of items to plot", default=None, type=int)
parser.add_argument("-t", help=f"only plot distributions with at least threshold number of ratings (defualt {thresh_default})", default=thresh_default, type=int)
parser.add_argument("-i", help="plot inverse of chosen stat instead", action="store_true")
parser.add_argument("--savefig", help="save the figure to file rather than displaying the figure", action="store_true")
parser.add_argument("--outfile", help=f'file to save the figure to (default "{outfile_default}")', default=outfile_default)
def plot_nym_stat(thresh=thresh_default, inv=False, savefig=False, outfile=outfile_default, begin=None, num=None, stat_option=stat_option_default):
stat_name = stat_options[stat_option]
if inv: stat_name = f'inverse {stat_name}'
fig, ax = plt.subplots()
ax.set(
# ylim=(0, None),
title=f'{stat_name} of each group by item number (thresh no. ratings >= {thresh})',
xlabel='item number',
ylabel=stat_name)
cm = plt.get_cmap('gist_rainbow')
colors = [cm(1.*i/Data.nym_count()) for i in range(Data.nym_count())]
begin = 0 if begin is None else begin
end = None if num is None else begin + num
nym_stats = Data.get_nym_stats()[:, begin : (None if num is None else begin+num),:]
for nym_n in range(Data.nym_count()):
nym_n_stats = nym_stats[nym_n]
with msg(f'plotting nym #{nym_n} {stat_name}'):
valids = (nym_n_stats[:,3] >= thresh)
print(f'{valids.sum()} of {len(valids)} valid (thresh = {thresh})')
x = nym_n_stats[:,0][valids]
if stat_option is 1:
y = nym_n_stats[:,1][valids]
elif stat_option is 2:
y = nym_n_stats[:,2][valids]
elif stat_option is 3:
y = np.sqrt(nym_n_stats[:,2][valids])
if inv: y[y > 0] = 1 / y[y > 0]
s = np.sqrt(nym_n_stats[:,3][valids])
ax.scatter(x, y, s=s, facecolors='none', edgecolors=colors[nym_n], label=f'group {nym_n}')
ax.legend()
if savefig:
with msg('Saving "{}" to "{}"'.format(ax.title.get_text(), outfile)):
ax.get_figure().savefig(outfile, dpi=150)
plt.clf()
else:
plt.show()
if __name__ == "__main__":
args = parser.parse_args()
stat_option = args.o if args.o in stat_options.keys() else stat_option_default
plot_nym_stat(args.t, args.i, args.savefig, args.outfile, args.b, args.n, stat_option) | true |
4476506c69b54262e53cf44fb004291692b9a77d | Python | Michellie/HW1 | /prob1.py | UTF-8 | 2,040 | 3.9375 | 4 | [] | no_license |
import sys
def primeFactorisation (k):
outputList = []
primeList = [2]
primeCounter = 2
for i in range(2,k + 1):
factorString = ""
for j in range(2, i+1):
if (i % j) == 0:
if i == j:
if i not in primeList: # identifies prime numbers
primeList += [i]
primeCounter += 1 # increase the number of prime number
factorString += str(primeCounter)
#factorString += str(i) + " p: " + str(primeCounter) + " a "
else:
factorString += str(primeList.index(i)+ 2) # 1: number 2 is already found, 2: index + 1 = number found
#factorString += " " + str(int(i)) + " p: " + str(primeList.index(i)+ 2) + " b "
else:
count = 0
while (i % j) == 0:
i = i / j
count += 1
if j not in primeList:
stringValue = str(j)
else:
stringValue = str(primeList.index(j)+ 2)
factorString += stringValue
if count > 1:
factorString += "^" + str(count) # only prints power that is greater than 1
if i > 1:
factorString += "*"
outputList.append(factorString)
return outputList
def main():
k = int(sys.stdin.readline()) # problem
print(" k pfe(k) ")
print(" 1 1")
if k > 1:
factorList = primeFactorisation(k) # returns a list of prime factorisation strings
for i in range (len(factorList)):
if int(i) < 8:
print(" " + str(i + 2) + " " + factorList[i])
elif int(i) < 98:
print(" " + str(i + 2) + " " + factorList[i])
else:
print(str(i + 2) + " " + factorList[i])
main() | true |
1f72333a75190433863e3383a4bcd3e901a998a5 | Python | aplot249/mypratice | /xuexi/lei/ceshi5.py | UTF-8 | 400 | 3.390625 | 3 | [] | no_license | #@author: sareeliu
#@date: 2021/6/4 20:57
class A:
def __init__(self,name):
self.name = name
def say(self):
print(self.name)
class B(A):
def say(self):
print('B')
print(self,self.name)
super(B, self).say()
class C(B):
def say(self):
print('C')
super(C, self).say()
c = C('saree')
print(C.__mro__)
c.say() | true |
8f1d934c10baab66fb9ae3ca57c959b9e77dbf79 | Python | MehulAgarwal10/line-counter | /getdirectory.py | UTF-8 | 1,665 | 3.0625 | 3 | [] | no_license | import os
import checkDir
def count_lines(exfiles):
count = 0
total_count = 0
for item in exfiles:
print('File ' + str(item) + ' : ')
count = count+1
total_count = total_count + checkDir.countLines(item)
return total_count
def walk_and_count(path, ex):
global total_line_count
print('Current Path : ' + str(path))
exfiles = checkDir.getexFile(path, ex)
if exfiles:
line_count = count_lines(exfiles)
total_line_count += line_count
print('\nCompleted all files in this directory. Moving on.. ')
dirlist = next(os.walk(path))[1]
if not dirlist:
return
else:
for item in dirlist:
print('Reading sub-directory : ' + str(item) + '-- ')
if(str(item).startswith('.')):
continue
elif (str(item).startswith(('sys'))):
continue
else:
new_path = path + "/" + str(item)
os.chdir(new_path)
walk_and_count(new_path, ex)
print('Line-Counter!')
total_line_count = 0
my_path = os.getcwd()
print('Current working directory : ')
print(my_path)
# os.chdir('/home/mehulagarwal/Code/python')
# targetPath = '/home/mehulagarwal/Code/python'
targetPath = input('Specify path to start walking : ')
# targetPath = input('Enter path to start walking : ')
# dirlist = next(os.walk(targetPath))[1]
# if len(dirlist) > 0:
# print(dirlist)
os.chdir(targetPath)
# start_list = next(os.walk(targetPath))[1]
ex = input('Enter file extension along with the . : ')
walk_and_count(targetPath, ex)
print('Total number of lines : ' + str(total_line_count))
| true |
01be3009a10fbd74c5cf2355f285f0155f8bc675 | Python | YannickBouty/projetcnt | /metiers/metierfilrouge.py | UTF-8 | 3,331 | 3.140625 | 3 | [] | no_license | """
Script métier du projet.
"""
import base64
from flask import jsonify
from werkzeug.utils import secure_filename
from datetime import datetime
# pylint: disable=too-many-arguments
def contruire_retour(precision, nom_fichier, extension, mime_type, taille, contenu):
"""
Construit un retour Json avec les métadata du fichier uploadé.
Parameters
----------
precision : string
nom_fichier : string
extension : string
mime_type : string
taille : int
contenu : string
Returns
-------
json
"""
return {'Précision':precision, 'Nom du fichier':nom_fichier, \
'Extension':extension, 'Mime type':mime_type, \
'Taille en octets':taille, 'Contenu':contenu}
def generer_json_data_brutes(request):
"""
Cette fonction génère un JSON avec les métadonnées et le contenu brute
d'un fichier CSV ou TXT ou MD passé dans la requête.
Returns
-------
{
'Précision': '',
'Type mime': '',
'Taille en octets': '',
'Nom de fichier': '',
'Extension': '',
'Contenu': ''
}
"""
precision = 'Format de fichier où les données sont affichées en brute !'
contenu = request.files['monFichier'].read()
mime_type = request.files['monFichier'].mimetype
taille = request.headers.get('Content-Length')
nom_fichier = secure_filename(request.files['monFichier'].filename)
extension = nom_fichier.split(".")[-1].lower()
return jsonify(contruire_retour(precision, nom_fichier, extension, mime_type, taille, contenu))
def generer_json_data_basesoixantequatre(request):
"""
Cette fonction génère un JSON avec les métadonnées et le contenu encodé en base 64
d'un fichier GIF ou JPEG ou JPG ou PNG ou PDF passé dans la requête.
Returns
-------
{
'Précision': '',
'Type mime': '',
'Taille en octets': '',
'Nom de fichier': '',
'Extension': '',
'Contenu': ''
}
"""
precision = 'Format de fichier où les données sont affichées en base64 !'
contenu = request.files['monFichier'].read()
contenu_base_soixantequatre = base64.b64encode(contenu)
mime_type = request.files['monFichier'].mimetype
taille = request.headers.get('Content-Length')
nom_fichier = secure_filename(request.files['monFichier'].filename)
extension = nom_fichier.split(".")[-1].lower()
return jsonify(contruire_retour(precision, nom_fichier, extension, \
mime_type, taille, contenu_base_soixantequatre))
def generer_json_vierge(request):
"""
Cette fonction génère un JSON avec les métadonnées
sans le contenu d'un fichier passé dans la requête.
Returns
-------
{
'Précision': '',
'Type mime': '',
'Taille en octets': '',
'Nom de fichier': '',
'Extension': '',
'Contenu': ''
}
"""
precision = 'Format de fichier non pris en compte !'
mime_type = request.files['monFichier'].mimetype
taille = request.headers.get('Content-Length')
nom_fichier = secure_filename(request.files['monFichier'].filename)
extension = nom_fichier.split(".")[-1].lower()
contenu = ''
return jsonify(contruire_retour(precision, nom_fichier, extension, mime_type, taille, contenu))
| true |
c328ac08ed20dc8a3bf7e4fff6afd0938520d531 | Python | AndreaCensi/boot_agents | /src/boot_agents/simple_stats/cmd_stats.py | UTF-8 | 1,503 | 2.921875 | 3 | [] | no_license | from .exp_switcher import ExpSwitcher
from collections import defaultdict
__all__ = ['CmdStats']
def zero():
return 0
class CommandStatistics(object):
def __init__(self):
self.commands2count = defaultdict(zero)
def update(self, commands):
commands = tuple(commands)
self.commands2count[commands] += 1
def display(self, report):
report.text('summary', self.get_summary())
def get_summary(self):
return "\n".join('%6d %s' % (count, command) for command, count
in self.commands2count.items())
class CmdStats(ExpSwitcher):
'''
A simple agent that estimates various statistics
of the commands.
'''
def init(self, boot_spec):
ExpSwitcher.init(self, boot_spec)
# if len(boot_spec.get_observations().shape()) != 1:
# raise UnsupportedSpec('I assume 1D signals.')
self.episodes = defaultdict(CommandStatistics)
def process_observations(self, obs):
id_episode = obs['id_episode'].item()
assert isinstance(id_episode, str)
self.episodes[id_episode].update(obs['commands'])
def merge(self, other):
self.episodes.update(other.episodes)
def publish(self, pub):
self.display(pub)
def display(self, report):
for id_episode, stats in self.episodes.items():
with report.subsection(id_episode) as sub:
stats.display(sub)
| true |
43a86bebb21771c012175dd9917f153b0d1c4ca0 | Python | eberdeed/machinetrans | /machinetrans/dataentry/declentry.py | UTF-8 | 30,731 | 2.515625 | 3 | [] | no_license | #!/usr/bin/python3
"""
DeclEntry: Machine Translation Data Entry -- Russian Noun Declension.
Created By Edward Charles Eberle <eberdeed@eberdeed.net>
August 1, 2016, San Diego California United States of America
"""
import os, sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from machinetrans.userinterfaces.ui_declentry import Ui_DeclEntry
from machinetrans.data.wordmorph import WordMorph
from machinetrans.dataentry.decltable import DeclTable
from machinetrans.dataentry.wordparsesmall import WordParseSmall
from machinetrans.helpview import HelpView
from machinetrans.dataentry.noundeclsel import NounDeclSel
class DeclEntry(QDialog, Ui_DeclEntry):
""" A GUI to enter Russian noun declensions.
Uses data from the WordMorph class and uses
the WordParse class to determine noun gender
from the given noun.
"""
helpfile = "/usr/share/machinetrans/resources/declentry.html"
parent = None
labeltext = ""
winx = 0
winy = 0
width1 = 0
height1 = 0
geometry = list()
morphs = None
tableobj = list()
decllist = list()
gencheck = False
singgender = None
numeric = False
instrumental = ""
oblique = ""
rustr = ""
stem = ""
ending = ""
penul = ""
enstr = ""
decltype = 0
declnum = 0
otherdecl = -1
parser = None
buttonstart = 5
animated = False
plural = False
numbers = ("один", "два", "три", "четыре")
def __init__(self, parent=None):
""" Initialize the GUI and determine the gender of the noun
using the WordParse class. The drawtable method uses
the gender found to determine what to display and also
uses the DeclTable class to create the HTML code for
the table displayed.
"""
super(DeclEntry, self).__init__(parent)
self.setupUi(self)
self.parent = parent
self.morphs = self.parent.morphs
self.parser = WordParseSmall(self)
self.rustr = self.parent.rustr
self.animated = self.parent.sqldict["animate"] == "animate"
self.singgender = self.parser.parse(self.rustr)
if self.singgender == "masculine":
self.decltype = 0
elif self.singgender == "nueter":
self.decltype = 1
elif self.singgender == "feminine":
self.decltype = 2
elif self.singgender == "plural":
self.decltype = 3
self.singgender = "masculine"
else:
self.decltype = 0
self.singgender = "masculine"
self.ending = self.rustr[-1]
self.penul = self.rustr[-2]
if self.ending in self.morphs.vowels:
self.stem = self.rustr[:-1]
elif self.ending == 'ь':
self.stem = self.rustr[:-1]
else:
self.stem = self.rustr
self.enstr = self.parent.sqldict["name"].strip("\'")
del(self.parent.sqldict["name"])
self.enEdit.setText(self.enstr)
# Initialize the outgoing data list.
self.parent.declension = list()
self.setGeometry(self.parent.geometry[0], self.parent.geometry[1], self.parent.geometry[2], self.parent.geometry[3])
# This adjusts the postions of the buttons,
# so you cannot double click and select
# the wrong button when the GUI changes.
self.buttonstart = 5
cursize = self.size()
sizeevent = QResizeEvent(cursize, cursize)
self.resizeEvent(sizeevent)
# Connect the signals to the methods.
self.acceptBttn.clicked.connect(self.accept)
self.declBttn.clicked.connect(self.finddecl)
self.rejectBttn.clicked.connect(self.cancel)
self.helpBttn.clicked.connect(self.displayhelp)
self.stemEdit.firereturn.triggered.connect(self.updatestem)
self.stemEdit.firefocus.triggered.connect(self.updatestem)
self.wordlogic()
self.createobj()
def singulartitle(self):
""" Display a title for a singular noun.
"""
tmpstr = self.singgender.capitalize() + " Russian Noun Declension"
self.titleLbl.setText(tmpstr)
def pluraltitle(self):
""" Display a title for a plural noun.
"""
tmpstr = "Russian Plural Noun Declension"
self.titleLbl.setText(tmpstr)
def resizeEvent(self, event):
""" Resize the GUI and store sizing information.
"""
dim = event.size()
self.height1 = dim.height()
self.width1 = dim.width()
hscale = self.height1 /600
wscale = self.width1 / 800
tmpy = 10
tmpx = self.width1 - 160
self.helpBttn.setGeometry(tmpx, tmpy, 150, 50)
tmpwidth = self.width1 - 20
self.titleLbl.setGeometry(10, 20, tmpwidth, 30)
tmpheight = hscale * 180
self.tableView.setGeometry(10, 60, tmpwidth, tmpheight)
tmpint = tmpwidth / 6
tmpy = 250 * hscale
tmpint = 30 * hscale
tmpx = (self.width1 - 740) / 2
self.engLbl.setGeometry(tmpx, tmpy, 340, 25)
tmpx = (self.width1 / 2) + 30
self.stemLbl.setGeometry(tmpx, tmpy, 340, 25)
tmpy += 30
tmpx = (self.width1 - 740) / 2
self.enEdit.setGeometry(tmpx, tmpy, 340, 30)
tmpx = (self.width1 / 2) + 30
self.stemEdit.setGeometry(tmpx, tmpy, 340, 30)
tmpx = (self.width1 - 740) / 2
tmpy += 40
self.nomLbl.setGeometry(tmpx, tmpy, 340, 25)
tmpx = (self.width1 / 2) + 30
self.accLbl.setGeometry(tmpx, tmpy, 340, 25)
tmpy += 30
tmpx = (self.width1 - 740) / 2
self.nomEdit.setGeometry(tmpx, tmpy, 340, 30)
tmpx = (self.width1 / 2) + 30
self.accEdit.setGeometry(tmpx, tmpy, 340, 30)
tmpy += 40
tmpx = (self.width1 - 740) / 2
self.genLbl.setGeometry(tmpx, tmpy, 340, 25)
tmpx = (self.width1 / 2) + 30
self.datLbl.setGeometry(tmpx, tmpy, 340, 25)
tmpy += 30
tmpx = (self.width1 - 740) / 2
self.genEdit.setGeometry(tmpx, tmpy, 340, 30)
tmpx = (self.width1 / 2) + 30
self.datEdit.setGeometry(tmpx, tmpy, 340, 30)
tmpy += 40
tmpx = (self.width1 - 740) / 2
self.insLbl.setGeometry(tmpx, tmpy, 340, 25)
tmpx = (self.width1 / 2) + 30
self.prpLbl.setGeometry(tmpx, tmpy, 340, 25)
tmpy += 30
tmpx = (self.width1 - 740) / 2
self.insEdit.setGeometry(tmpx, tmpy, 340, 30)
tmpx = (self.width1 / 2) + 30
self.prpEdit.setGeometry(tmpx, tmpy, 340, 30)
tmpy = self.height1 - 70
tmpx = 130 * wscale
self.rejectBttn.setGeometry(tmpx, tmpy, 150, 50)
tmpx = 330 * wscale
self.declBttn.setGeometry(tmpx, tmpy, 150, 50)
tmpx = ((self.width1 / 2) + (130 * wscale))
self.acceptBttn.setGeometry(tmpx, tmpy, 150, 50)
tmpos = self.pos()
self.winx = tmpos.x()
self.winy = tmpos.y()
self.geometry = list([self.winx, self.winy, self.width1, self.height1])
def wordlogic(self):
""" Set up the HTML table of the currently selected declension.
Do some checking on the ending so the right one is selected
and displayed in the line editors below.
Fill out the GUI with the declension information.
"""
self.rustr = self.parent.rustr
self.instrumental = ""
self.oblique = ""
if self.rustr[-2:] == "ие" and not self.gencheck:
answer = QMessageBox.question(self, "Ambiguous Ending", "Is the ending \"ие\" an adjectival noun?", QMessageBox.Yes, QMessageBox.No)
if answer == QMessageBox.No:
self.singgender = "nueter"
self.decltype = 1
self.stem = self.rustr[:-2]
self.declnum = 2
self.gencheck = True
self.stemEdit.setText(self.stem)
else:
self.decltype = 6
self.stem = self.rustr[:-2]
if self.rustr[-3] in self.morphs.reqi:
if self.animated:
self.declnum = 18
else:
self.declnum = 19
else:
if self.animated:
self.declnum = 16
else:
self.declnum = 17
self.gencheck = True
self.stemEdit.setText(self.stem)
elif self.decltype < 3:
if self.singgender == "masculine":
if self.rustr[-2:] == "ий":
answer = QMessageBox.question(self, "Ambiguous Ending in Masculine", "Is the ending \"ий\" an adjectival noun?", QMessageBox.Yes, QMessageBox.No)
if answer == QMessageBox.Yes:
self.stem = self.rustr[:-2]
testchar = self.stem[-1]
if testchar in self.morphs.reqi:
if self.animated:
self.declnum = 18
else:
self.declnum = 19
elif self.animated:
self.declnum = 16
else:
self.declnum = 17
else:
self.stem = self.rustr[:-2]
if self.animated:
self.declnum = 10
else:
self.declnum = 11
elif self.rustr[-2:] == "ец":
self.stem = self.rustr[:-2] + "ц"
if self.animated:
self.declnum = 0
else:
self.declnum = 1
elif self.ending == "ь":
self.stem = self.rustr[:-1]
if self.animated:
self.declnum = 2
else:
self.declnum = 3
elif self.rustr[-2:] == "ый":
self.stem = self.rustr[:-2]
if self.animated:
self.declnum = 14
else:
self.declnum = 15
elif self.rustr[-2:] == "ой":
self.stem = self.rustr[:-2]
if self.animated:
self.declnum = 20
else:
self.declnum = 21
elif self.ending == "й":
self.stem = self.rustr[:-1]
if self.animated:
self.declnum = 4
else:
self.declnum = 5
else:
self.stem = self.rustr
if self.animated:
self.declnum = 0
else:
self.declnum = 1
elif self.singgender == "feminine":
if self.ending == "ь":
self.stem =self.rustr[:-1]
self.declnum = 5
elif self.rustr[-2:] == "ая" and self.rustr[-3] in self.morphs.reqi:
self.stem = self.rustr[:-2]
self.declnum = 10
elif self.rustr[-2:] == "ая":
self.stem = self.rustr[:-2]
self.declnum = 8
elif self.rustr[-2:] == "яя":
self.stem = self.rustr[:-2]
self.declnum = 9
elif self.rustr[-2:] == "ья":
self.stem = self.rustr[:-2]
self.declnum = 12
elif self.ending == "я" and self.penul == "и":
self.stem =self.rustr[:-2]
self.declnum = 4
elif self.ending == "а" and self.penul in self.morphs.reqi:
self.stem =self.rustr[:-1]
self.declnum = 2
elif self.ending == "я" and self.penul in self.morphs.reqi:
self.stem =self.rustr[:-1]
self.declnum = 3
elif self.ending == "а":
self.stem =self.rustr[:-1]
self.declnum = 0
elif self.ending == "я":
self.stem =self.rustr[:-1]
self.declnum = 6
else:
self.stem =self.rustr[:-1]
selfdeclnum = 0
elif self.singgender == "nueter":
if self.rustr[-2:] == "ое" and self.rustr[-3] in self.morphs.reqi:
self.stem = self.rustr[:-2]
self.declnum = 7
elif self.rustr[-2:] == "ое":
self.stem = self.rustr[:-2]
self.declnum = 5
elif self.rustr[-2:] == "ее":
self.stem = self.rustr[:-2]
self.declnum = 6
elif self.rustr[-2:] == "ье":
self.stem = self.rustr[:-2]
self.declnum = 9
elif self.ending == "е":
if self.penul == "и":
self.stem =self.rustr[:-2]
self.declnum = 2
else:
self.stem =self.rustr[:-1]
self.declnum = 1
elif self.ending == "о":
self.stem =self.rustr[:-1]
self.declnum = 0
elif self.rustr[-2:] == "мя":
self.stem =self.rustr[:-2]
self.declnum = 3
else:
self.stem =self.rustr[:-1]
self.declnum = 0
elif self.decltype > 2:
if not (self.decltype == 6):
self.enstr = self.enEdit.text()
self.endings = self.enstr[-1]
# Check to make sure the noun is not a collective noun,
# and if not make the English noun plural.
if self.endings != "s" and self.parent.sqldict["variety"] != "\'collective\'":
if self.endings == "y":
self.enEdit.setText(self.enstr[:-1] + "ies")
else:
self.endings = self.enstr[-2:]
if self.endings == "sh":
self.enEdit.setText(self.enstr + "es")
else:
self.enEdit.setText(self.enstr + "s")
if self.decltype == 6:
self.handlenums()
elif self.singgender == "masculine":
# Determine the declension to use.
if self.declnum > 14:
self.declnum += 6
self.stem = self.rustr[:-2]
elif self.rustr[-2:] == "ец":
self.stem = self.rustr[:-2] + "ц"
if self.animated:
self.declnum = 2
else:
self.declnum = 3
elif self.ending in self.morphs.reqi:
if self.animated:
self.declnum = 8
else:
self.declnum = 9
elif self.ending == "й" or self.declnum == 6 or self.declnum == 7:
self.stem =self.rustr[:-1]
if self.animated:
self.declnum = 4
else:
self.declnum = 5
elif self.ending == "ь":
self.stem =self.rustr[:-1]
if self.animated:
self.declnum = 10
else:
self.declnum = 11
elif self.ending == "и" or self.ending == "ы" and self.penul in self.morphs.reqi:
self.stem =self.rustr[:-1]
if self.animated:
self.declnum = 8
else:
self.declnum = 9
elif self.ending == "и" or self.ending == "ы":
self.stem = self.rustr[:-1]
if self.animated:
self.declnum = 0
else:
self.declnum = 1
elif self.rustr[-4:] == "анин" or self.rustr[-4:] == "янин":
self.stem =self.rustr[:-3]
self.declnum = 15
elif self.rustr[-2:] == "ат" or self.rustr[-2:] == "ят":
self.stem =self.rustr[:-1]
self.declnum = 14
else:
if self.ending == "и" or self.ending == "ы":
self.stem = self.rustr[:-1]
if self.animated:
self.declnum = 0
else:
self.delnum = 1
elif self.singgender == "feminine":
# Determine which declension to use.
if self.declnum == 8:
self.stem = self.rustr[:-2]
if self.animated:
self.declnum = 14
else:
self.declnum = 15
elif self.declnum == 9:
self.stem = self.rustr[:-2]
if self.animated:
self.declnum = 16
else:
self.declnum = 17
elif self.declnum == 10:
self.stem = self.rustr[:-2]
if self.animated:
self.declnum = 18
else:
self.declnum = 19
elif self.declnum == 12:
self.stem = self.rustr[:-2]
if self.animated:
self.declnum = 22
else:
self.declnum = 23
elif self.ending == "ь":
if self.animated:
self.declnum = 6
else:
self.declnum = 7
elif self.ending == "а":
if self.penul in self.morphs.reqi:
if self.animated:
self.declnum = 2
else:
self.declnum = 3
else:
if self.animated:
self.declnum = 0
else:
self.declnum = 1
elif self.ending == "я":
tmpstr = self.penul + self.ending
if tmpstr == "ия":
self.stem = self.rustr[:-2]
if self.animated:
self.declnum = 10
else:
self.declnum = 11
else:
if self.animated:
self.declnum = 8
else:
self.declnum = 9
else:
if self.animated:
self.declnum = 0
else:
self.declnum = 1
elif self.singgender == "nueter":
if (self.declnum < 5):
self.stem = self.rustr[:-1]
else:
self.stem = self.rustr[:-2]
# Determine the declension to use.
if self.declnum > 3:
self.stem = self.rustr[:-2]
self.declnum += 1
elif self.ending == "o":
self.stem = self.rustr[:-1]
self.declnum = 0
elif self.ending == "е":
self.stem = self.rustr[:-1]
self.declnum = 1
elif self.rustr[-2:] == "мя":
self.stem = self.rustr[:-2]
self.declnum = 3
self.gencheck = True
self.stemEdit.setText(self.stem)
def handlenums(self):
self.stem = self.rustr
if not self.rustr in self.numbers:
answer = QMessageBox.question(self, "Numeric Test", "Is this word a number?", QMessageBox.Yes, QMessageBox.No)
if answer == QMessageBox.Yes:
self.numeric = True
index = self.stem.find("ь")
if self.rustr[-1] == "ь":
self.stem = self.rustr[:-1]
self.decltype = 5
self.declnum = 12
self.instrumental = self.stem + "ью"
elif index < (len(self.stem) - 1) and index >= 0:
tmpstr = self.stem[:index]
index += 1
tmpstr += "и"
tmpstr += self.stem[index:]
self.oblique = tmpstr
self.instrumental = self.rustr
tmpstr = self.instrumental[:index]
tmpstr += "ю"
tmpstr += self.instrumental[index:]
tmpstr += "ью"
self.instrumental = tmpstr
self.decltype = 5
self.declnum = 12
if self.stem.endswith("сот"):
self.stem = self.stem[:-3]
self.oblique = self.oblique[:-3]
self.instrumental = self.instrumental[:-5] + "стами"
self.decltype = 3
self.declnum = 15
else:
self.stem = self.rustr
self.instrumental = self.stem + "а"
self.decltype = 3
self.declnum = 12
else:
self.declnum = 0
self.decltype = 3
elif self.rustr in self.numbers:
self.stem = self.rustr
self.decltype = 3
self.declnum = 16
def createobj(self):
""" Create an HTML table of noun declensions.
"""
self.tableView.clear()
# A class to draw the HTML table.
if self.numeric and self.rustr[-1] == "ь":
self.stem = self.rustr
self.nomEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][1])
self.accEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][2])
self.stem = self.rustr[:-1]
elif len(self.oblique) > 0:
self.stem = self.rustr
self.nomEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][1])
self.accEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][2])
self.stem = self.oblique
elif self.decltype > 2:
self.nomEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][1])
self.accEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][2])
else:
self.nomEdit.setText(self.rustr)
self.accEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][2])
if (self.stem[-2:] == "нк" or self.stem[-2:] == "тк") and self.decltype == 5:
tmpstem = self.stem
self.stem = self.stem[:-1] + "ок"
if self.animated:
self.accEdit.setText(self.stem)
self.genEdit.setText(self.stem)
else:
self.accEdit.setText(tmpstem + self.morphs.datalist[self.decltype][self.declnum][2])
self.genEdit.setText(self.stem)
self.stem = self.stem[:-2] + "к"
elif self.stem[-3:] == "ньк" and self.decltype == 5:
tmpstem = self.stem
self.stem = self.stem[:-2] + "ек"
if self.animated:
self.accEdit.setText(self.stem)
self.genEdit.setText(self.stem)
else:
self.accEdit.setText(tmpstem + self.morphs.datalist[self.decltype][self.declnum][2])
self.genEdit.setText(self.stem)
self.stem = self.stem[:-2] + "ьк"
else:
self.accEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][2])
self.genEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][3])
self.datEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][4])
if self.numeric:
self.insEdit.setText(self.instrumental)
else:
self.insEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][5])
self.prpEdit.setText(self.stem + self.morphs.datalist[self.decltype][self.declnum][6])
self.numeric = False
tmptable = DeclTable(self.morphs.datalist[self.decltype][self.declnum][0] + " " + self.morphs.datalist[self.decltype][self.declnum][1], self.declnum)
tmptable.addrow(self.morphs.datalist[self.decltype][self.declnum])
tmpstr = tmptable.table()
# Put the table in the GUI.
self.tableView.clear()
self.tableView.setHtml(tmpstr)
def updatestem(self):
self.stem = self.stemEdit.text()
self.penul = self.stem[-1]
self.createobj()
return
def finddecl(self):
""" Open a gui to choose the noun's declension.
"""
chooser = NounDeclSel(self)
chooser.exec()
self.chopend()
if self.decltype == 0:
self.singgender = "masculine"
elif self.decltype == 1:
self.singgender = "nueter"
elif self.decltype == 2:
self.singgender= "feminine"
self.createobj()
сhooser = None
return
def chopend(self):
if self.decltype == 6 or self.decltype < 3:
if self.decltype == 6 or self.morphs.datalist[self.decltype][self.declnum][0] == "Blank" or \
(self.decltype == 0 and self.declnum == 0) or (self.decltype == 0 and self.declnum == 1) or\
(self.decltype == 0 and self.declnum == 4) or (self.decltype == 0 and self.declnum == 5) or\
(self.decltype == 0 and self.declnum == 8):
self.stem = self.rustr
elif (self.decltype == 0 and self.declnum > 12) or (self.decltype == 1 and self.declnum > 4) or \
(self.decltype == 2 and self.declnum > 7) or (self.decltype == 3 and self.declnum > 15) or \
(self.decltype == 4 and self.declnum > 4) or (self.decltype == 5 and self.declnum > 13) or \
(self.decltype == 0 and self.declnum == 10) or (self.decltype == 0 and self.declnum == 11) or \
(self.decltype == 1 and self.declnum == 2) or (self.decltype == 1 and self.declnum == 3) or \
(self.decltype == 2 and self.declnum == 10) or (self.decltype == 2 and self.declnum == 11):
self.stem = self.rustr[:-2]
elif (self.decltype == 0 and self.declnum == 13):
self.stem = self.rustr[:-3]
else:
self.stem = self.rustr[:-1]
self.stemEdit.setText(self.stem)
def accept(self):
""" Gather the data and create an SQL command to insert it into the database.
Close the GUI.
"""
tmpstr = ""
if self.decltype == 6:
self.buttonstart = 105
cursize = self.size()
sizeevent = QResizeEvent(cursize, cursize)
self.resizeEvent(sizeevent)
self.wordlogic()
self.createobj()
return
animation = self.parent.sqldict['animate']
variety = self.parent.sqldict['variety']
typeval = self.parent.sqldict['type']
self.rustr = self.parent.rustr
self.enstr = self.enEdit.text()
x = self.enstr
index = x.find('\'')
while(index >= 0):
tmpstr1 = x[:index]
tmpstr1 += '\''
tmpstr1 += x[index:]
x = tmpstr1
tmpint = index + 2
index = x.find('\'', tmpint)
tmpstr = x
if self.decltype > 2:
genderstr = "plural"
else:
genderstr = self.singgender
self.decllist = list([variety, typeval, self.rustr, tmpstr, genderstr, self.nomEdit.text(), 'nominative', animation])
self.parent.declension.append(self.decllist)
self.decllist = list([variety, typeval, self.rustr, tmpstr, genderstr, self.accEdit.text(), 'accusative', animation])
self.parent.declension.append(self.decllist)
self.decllist = list([variety, typeval, self.rustr, tmpstr, genderstr, self.genEdit.text(), 'genitive', animation])
self.parent.declension.append(self.decllist)
self.decllist = list([variety, typeval, self.rustr, tmpstr, genderstr, self.datEdit.text(), 'dative', animation])
self.parent.declension.append(self.decllist)
self.decllist = list([variety, typeval, self.rustr, tmpstr, genderstr, self.insEdit.text(), 'instrumental', animation])
self.parent.declension.append(self.decllist)
self.decllist = list([variety, typeval, self.rustr, tmpstr, genderstr, self.prpEdit.text(), 'prepositional', animation])
self.parent.declension.append(self.decllist)
self.decllist = list()
if self.decltype > 2:
self.close()
return
self.decltype += 3 # Shifts everything to plural.
self.buttonstart = 105
cursize = self.size()
sizeevent = QResizeEvent(cursize, cursize)
self.resizeEvent(sizeevent)
self.wordlogic()
self.createobj()
return
def displayhelp(self):
""" Display a help file in HTML format.
"""
helper = HelpView(self)
helper.activateWindow()
helper.exec()
self.activateWindow()
def cancel(self):
""" Cancel the event.
"""
self.parent.cancel = True
self.parent.declension = list()
self.close()
def closeEvent(self, event):
""" Close the form and pass along GUI sizing information.
"""
self.parent.setGeometry(self.geometry[0], self.geometry[1], self.geometry[2], self.geometry[3])
event.accept() | true |
b65301823550a5df3208d0718eef33e4e3b62fe3 | Python | sneakyweasel/DNA | /MS/MS.py | UTF-8 | 511 | 2.734375 | 3 | [] | no_license | import os
import sys
from heapq import merge
file = open(os.path.join(os.path.dirname(sys.argv[0]), 'rosalind_ms.txt'))
lines = [line.rstrip('\n') for line in file]
n = lines[0]
arr = [int(x) for x in lines[1].split(" ")]
def merge_sort(m):
if len(m) <= 1:
return m
middle = len(m) // 2
left = m[:middle]
right = m[middle:]
left = merge_sort(left)
right = merge_sort(right)
return list(merge(left, right))
sarr = [str(x) for x in merge_sort(arr)]
print(" ".join(sarr))
| true |
32342fd3e2d9e1303ceabff5f81d25a8b1b102f2 | Python | niuyaning/PythonProctice | /06/06/global_variable.py | UTF-8 | 273 | 2.859375 | 3 | [] | no_license | def a():
local = 1
print(local)
if __name__ == "__main__":
a()
global_b = 123
def b():
print(global_b)
if __name__ == "__main__":
b();
def out():
global_a = 1
def sa():
print(global_a)
return global_a
return sa()
out() | true |
a9967dc91840ae5535876a82af250917daab18fb | Python | Nam1994/Lambda_AutomationTest | /Pages/lambda_app_page.py | UTF-8 | 1,052 | 2.640625 | 3 | [] | no_license | import logging
from Locators.lamda_page_locators import LambdaPageLocators
from Pages.base_page import BasePage
from TestData.testdata import TestData
from Utils.asertion import Assertion
from Locators.integration_page_locators import LocatorsApp
from Objects.app_object import Object
class LambdaAppPage(BasePage):
def __init__(self, driver):
super().__init__(driver)
self.navigate(TestData.BASE_URL_02)
logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
def click_app_in_lambda(self, index):
list_title = []
for index in range(1, 10):
self.click(LocatorsApp.learn_more_app(index))
title = self.get_title()
url = self.get_current_url()
object = Object(title, url)
list_title.append(object)
self.back_browser()
return list_title
def compare_info_app(self, expected, actual):
assertion = Assertion()
assertion.assertEqual(expected.title, actual.title, 'The title not match')
| true |
4406d831ad6a1ae5213c8c918151101d3eea89d8 | Python | tsampi/tsampi-0 | /tsampi/pypy/lib-python/hypothesis/internal/conjecture/minimizer.py | UTF-8 | 4,439 | 2.96875 | 3 | [] | no_license | # coding=utf-8
#
# This file is part of Hypothesis (https://github.com/DRMacIver/hypothesis)
#
# Most of this work is copyright (C) 2013-2015 David R. MacIver
# (david@drmaciver.com), but it contains contributions by others. See
# https://github.com/DRMacIver/hypothesis/blob/master/CONTRIBUTING.rst for a
# full list of people who may hold copyright, and consult the git log if you
# need to determine who owns an individual contribution.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
#
# END HEADER
from __future__ import division, print_function, absolute_import
from hypothesis.internal.compat import hbytes, hrange
"""
This module implements a lexicographic minimizer for blocks of bytearray.
That is, given a block of bytes of size n, and a predicate that accepts such
blocks, it tries to find a lexicographically minimal block of that size
that satisifies the predicate, starting from that initial starting point.
Assuming it is allowed to run to completion (which due to the way we use it it
actually often isn't) it makes the following guarantees, but it usually tries
to do better in practice:
1. The lexicographic predecessor (i.e. the largest block smaller than it) of
the answer is not a solution.
2. No individual byte in the solution may be lowered while holding the others
fixed.
"""
class Minimizer(object):
def __init__(self, initial, condition, random):
self.current = hbytes(initial)
self.size = len(self.current)
self.condition = condition
self.random = random
self.changes = 0
def incorporate(self, buffer):
assert isinstance(buffer, hbytes)
assert len(buffer) == self.size
assert buffer <= self.current
if self.condition(buffer):
self.current = buffer
self.changes += 1
return True
return False
def _shrink_index(self, i, c):
assert isinstance(self.current, hbytes)
assert 0 <= i < self.size
if self.current[i] <= c:
return False
if self.incorporate(
self.current[:i] + hbytes([c]) +
self.current[i + 1:]
):
return True
if i == self.size - 1:
return False
return self.incorporate(
self.current[:i] + hbytes([c, 255]) +
self.current[i + 2:]
) or self.incorporate(
self.current[:i] + hbytes([c]) +
hbytes([255] * (self.size - i - 1))
)
def run(self):
if not any(self.current):
return
if self.incorporate(hbytes(self.size)):
return
for c in hrange(max(self.current)):
if self.incorporate(
hbytes(min(b, c) for b in self.current)
):
break
change_counter = -1
while self.current and change_counter < self.changes:
change_counter = self.changes
for i in hrange(self.size):
t = self.current[i]
if t > 0:
ss = small_shrinks[self.current[i]]
for c in ss:
if self._shrink_index(i, c):
for c in hrange(self.current[i]):
if c in ss:
continue
if self._shrink_index(i, c):
break
break
# Table of useful small shrinks to apply to a number.
# The idea is that we use these first to see if shrinking is likely to work.
# If it is, we try a full shrink. In the best case scenario this speeds us
# up by a factor of about 25. It will occasonally cause us to miss
# shrinks that we could have succeeded with, but oh well. It doesn't fail any
# of our guarantees because we do try to shrink to -1 among other things.
small_shrinks = [
set(range(b)) for b in hrange(10)
]
for b in hrange(10, 256):
result = set()
result.add(0)
result.add(b - 1)
for i in hrange(8):
result.add(b ^ (1 << i))
result.discard(b)
assert len(result) <= 10
small_shrinks.append(sorted(result))
def minimize(initial, condition, random=None):
m = Minimizer(initial, condition, random)
m.run()
return m.current
| true |
c303d356a3c74b759892898683bef520aaa15c6e | Python | BatLancelot/PFund-Jan-Apr-2021-Retake | /02_02_Data _Types_and_Variables_Ex/02-Chars-to-String.py | UTF-8 | 117 | 3.140625 | 3 | [] | no_license | c1 = str(input())
c2 = str(input())
c3 = str(input())
result = c1 + c2 + c3
print(result)
# print(f'{c1}{c2}{c3}')
| true |
9114a6b20900066669c9990132400943aea9e3ba | Python | yuty2009/eeg-python | /emotion/convnet.py | UTF-8 | 11,061 | 2.65625 | 3 | [] | no_license | # -*- coding:utf-8 -*-
import torch
import torch.nn as nn
from common.torchutils import Expression, safe_log, square, log_cov
from common.torchutils import DepthwiseConv2d, SeparableConv2d, Conv2dNormWeight, Swish
class CSPNet(nn.Module):
"""
ConvNet model mimics CSP
"""
def __init__(
self, n_timepoints, n_channels, n_classes, dropout = 0.5,
n_filters_t = 20, filter_size_t = 25,
n_filters_s = 6, filter_size_s = -1,
pool_size_1 = 100, pool_stride_1 = 25,
):
super().__init__()
assert filter_size_t <= n_timepoints, "Temporal filter size error"
if filter_size_s <= 0: filter_size_s = n_channels
self.features = nn.Sequential(
# temporal filtering
nn.Conv2d(1, n_filters_t, (filter_size_t, 1), padding=(filter_size_t//2, 0), bias=False),
nn.BatchNorm2d(n_filters_t),
# spatial filtering
nn.Conv2d(
n_filters_t, n_filters_t*n_filters_s, (1, filter_size_s),
groups=n_filters_t, bias=False
),
nn.BatchNorm2d(n_filters_t*n_filters_s),
Expression(square),
nn.AvgPool2d((pool_size_1, 1), stride=(pool_stride_1, 1)),
Expression(safe_log),
nn.Dropout(dropout),
)
n_features = (n_timepoints - pool_size_1) // pool_stride_1 + 1
n_filters_out = n_filters_t * n_filters_s
self.classifier = nn.Sequential(
Conv2dNormWeight(n_filters_out, n_classes, (n_features, 1), max_norm=0.5),
nn.LogSoftmax(dim=1)
)
self._reset_parameters()
def _reset_parameters(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
# nn.init.xavier_uniform_(m.weight, gain=1)
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.classifier(x)
x = x[:, :, 0, 0]
return x
class EEGNet(nn.Module):
"""
Pytorch Implementation of EEGNet from [1]
code: https://github.com/vlawhern/arl-eegmodels
References
----------
.. [1] V. J. Lawhern, A. J. Solon, N. R. Waytowich, S. M. Gordon, C. P. Hung,
and B. J. Lance, "EEGNet: a compact convolutional neural network for
EEG-based brain-computer interfaces," J Neural Eng, vol. 15, no. 5,
p. 056013, Oct 2018.
Online: http://iopscience.iop.org/article/10.1088/1741-2552/aace8c/meta
Inputs:
filter_size_time_1: length of temporal convolution in first layer. We found
that setting this to be half the sampling rate worked
well in practice. For the SMR dataset in particular
since the data was high-passed at 4Hz we used a kernel
length of 32.
"""
def __init__(
self, n_timepoints, n_channels, n_classes, dropout = 0.5,
n_filters_1 = 8, filter_size_time_1 = 125,
pool_size_time_1 = 4, pool_stride_time_1 = 4,
n_filters_2 = 16, filter_size_time_2 = 22,
pool_size_time_2 = 8, pool_stride_time_2 = 8,
):
super().__init__()
assert filter_size_time_1 <= n_timepoints, "Temporal filter size error"
self.features = nn.Sequential(
# temporal filtering
nn.Conv2d(1, n_filters_1, (filter_size_time_1, 1), padding=(filter_size_time_1//2, 0), bias=False),
nn.BatchNorm2d(n_filters_1),
# spatial filtering
DepthwiseConv2d(n_filters_1, 2, (1, n_channels), bias=False),
# Conv2dNormWeight(n_filters_1, n_filters_1*2, (1, n_channels), max_norm=1, groups=n_filters_1, bias=False),
nn.BatchNorm2d(n_filters_1*2),
nn.ELU(),
nn.AvgPool2d((pool_size_time_1, 1), stride=(pool_stride_time_1, 1)),
nn.Dropout(dropout),
# SeparableConv2d
SeparableConv2d(
n_filters_1*2, n_filters_2, (filter_size_time_2, 1),
padding=(filter_size_time_2//2, 0), bias=False
),
nn.BatchNorm2d(n_filters_2),
nn.ELU(),
nn.AvgPool2d((pool_size_time_2, 1), stride=(pool_stride_time_2, 1)),
nn.Dropout(dropout),
)
n_features_1 = (n_timepoints - pool_size_time_1)//pool_stride_time_1 + 1
n_features_2 = (n_features_1 - pool_size_time_2)//pool_stride_time_2 + 1
n_filters_out = n_filters_2
n_features_out = n_filters_out * n_features_2
self.classifier = nn.Sequential(
# nn.Linear(n_features_out, n_classes),
# nn.Conv2d(n_filters_2, n_classes, (n_features_2, 1)),
Conv2dNormWeight(n_filters_2, n_classes, (n_features_2, 1), max_norm=0.5),
nn.LogSoftmax(dim=1)
)
self._reset_parameters()
def _reset_parameters(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.xavier_uniform_(m.weight, gain=1)
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, x):
x = self.features(x)
# x = x.view(x.size(0), -1)
x = self.classifier(x)
x = x[:, :, 0, 0]
return x
class ShallowConvNet(nn.Module):
"""
Shallow ConvNet model from [1]_.
References
----------
.. [1] Schirrmeister, R. T., Springenberg, J. T., Fiederer, L. D. J.,
Glasstetter, M., Eggensperger, K., Tangermann, M., Hutter, F. & Ball, T. (2017).
Deep learning with convolutional neural networks for EEG decoding and
visualization.
Human Brain Mapping, Aug. 2017. Online: http://dx.doi.org/10.1002/hbm.23730
"""
def __init__(
self, n_timepoints, n_channels, n_classes, dropout = 0.5,
n_filters = 40, filter_size_time = 25,
pool_size_time = 75, pool_stride_time = 15,
):
super().__init__()
assert filter_size_time <= n_timepoints, "Temporal filter size error"
self.features = nn.Sequential(
nn.Conv2d(1, n_filters, (filter_size_time, 1)), # temporal filtering
nn.Conv2d(n_filters, n_filters, (1, n_channels), bias=False), # spatial filtering
nn.BatchNorm2d(n_filters),
Expression(square),
nn.AvgPool2d((pool_size_time, 1), stride=(pool_stride_time, 1)),
Expression(safe_log),
nn.Dropout(dropout),
)
outlen_time = (n_timepoints - filter_size_time) + 1
outlen_time = (outlen_time - pool_size_time)//pool_stride_time + 1
self.classifier = nn.Sequential(
Conv2dNormWeight(n_filters, n_classes, (outlen_time, 1), max_norm=0.5),
# nn.Conv2d(n_filters, n_classes, (outlen_time, 1)),
nn.LogSoftmax(dim=1)
)
self._reset_parameters()
def _reset_parameters(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.xavier_uniform_(m.weight, gain=1)
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.classifier(x)
x = x[:, :, 0, 0]
return x
class DeepConvNet(nn.Module):
"""
Deep ConvNet model from [1]_.
References
----------
.. [1] Schirrmeister, R. T., Springenberg, J. T., Fiederer, L. D. J.,
Glasstetter, M., Eggensperger, K., Tangermann, M., Hutter, F. & Ball, T. (2017).
Deep learning with convolutional neural networks for EEG decoding and
visualization.
Human Brain Mapping, Aug. 2017. Online: http://dx.doi.org/10.1002/hbm.23730
"""
def __init__(
self, n_timepoints, n_channels, n_classes, dropout = 0.5,
n_filters = 25, filter_size_time = 10,
pool_size_time = 3, pool_stride_time = 3,
n_conv_blocks = 4
):
super().__init__()
assert filter_size_time <= n_timepoints, "Temporal filter size error"
conv1 = nn.Sequential(
Conv2dNormWeight(1, n_filters, (filter_size_time, 1), max_norm=2), # temporal filtering
Conv2dNormWeight(n_filters, n_filters, (1, n_channels), max_norm=2, bias=False), # spatial filtering
nn.BatchNorm2d(n_filters),
nn.ELU(),
nn.MaxPool2d((pool_size_time, 1), stride=(pool_stride_time, 1)),
)
n_filters_prev = n_filters
outlen_time = (n_timepoints - filter_size_time) + 1
outlen_time = (outlen_time - pool_size_time)//pool_stride_time + 1
conv_blocks = nn.ModuleList()
for i in range(n_conv_blocks-1):
n_filters_now = 2 * n_filters_prev
conv_blocks.append(self._make_block(
n_filters_prev, n_filters_now, filter_size_time,pool_size_time, pool_stride_time, dropout
))
n_filters_prev = n_filters_now
outlen_time = (outlen_time - filter_size_time) + 1
outlen_time = (outlen_time - pool_size_time)//pool_stride_time + 1
self.features = nn.Sequential(conv1, *conv_blocks)
self.classifier = nn.Sequential(
Conv2dNormWeight(n_filters_now, n_classes, (outlen_time, 1), max_norm=0.5, bias=True),
nn.LogSoftmax(dim=1)
)
self._reset_parameters()
def _make_block(self, in_planes, out_planes, filter_size,
pool_size, pool_stride, dropout=0.5):
return nn.Sequential(
nn.Dropout(dropout),
Conv2dNormWeight(in_planes, out_planes, (filter_size, 1), max_norm=2, bias=False),
nn.BatchNorm2d(out_planes),
nn.ELU(),
nn.MaxPool2d((pool_size, 1), stride=(pool_stride, 1)),
)
def _reset_parameters(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.xavier_uniform_(m.weight, gain=1)
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.classifier(x)
x = x[:, :, 0, 0]
return x
if __name__ == '__main__':
# model = ShallowConvNet(534, 44, 4)
# model = DeepConvNet(534, 44, 4)
# model = EEGNet(534, 44, 4)
model = CSPNet(534, 44, 4)
x = torch.randn((10, 1, 534, 44))
print(model)
y = model(x)
print(y.shape) | true |
ae280d1fbb08ce6964c2642100442c16fe1122ba | Python | leifan-123/ecshop | /scripts/test_buy_sales.py | UTF-8 | 3,138 | 2.875 | 3 | [] | no_license | import time
import allure
import pytest
from common.base import preposition_code,Base
from page.home_page import HomePage
from page.sales_page import SalesPage
from page.buy_page import BuySalesPage
from page.check_order_page import CheckOrderPage
from page.personal_page import PersonalPage
class TestBuySales:
def setup_class(self):
self.driver = preposition_code()
@pytest.allure.severity(pytest.allure.severity_level.CRITICAL)
@allure.step(title="使用余额购买促销商品")
def test_buy_sales(self):
allure.attach("点击我的","进入个人中心")
PersonalPage(self.driver).personal_click()
# 获取金额
money_b = float(PersonalPage(self.driver).get_value())
allure.attach("购买商品前的金额:",f'{money_b}')
allure.attach("点击首页", "进入商品促销")
# 进入首页
HomePage(self.driver).homepage_click()
time.sleep(2)
# 点击促销商品
HomePage(self.driver).sales_click()
time.sleep(5)
allure.attach("任意选择一商品", "进入商品详情")
# 选择促销商品
SalesPage(self.driver).sales_goods_click()
time.sleep(5)
allure.attach("商品详情","立即购买")
# 点击立即购买
BuySalesPage(self.driver).buy_click()
time.sleep(5)
# 点击确认
BuySalesPage(self.driver).ensure_click()
allure.attach("支付界面","使用余额支付")
# 点击使用余额
CheckOrderPage(self.driver).balance_click()
time.sleep(3)
# 获取订单金额
price = float(CheckOrderPage(self.driver).get_goods_price().strip("¥"))
allure.attach("购买商品的金额:", f'{price}')
try:
# self.driver.find_element_by_xpath("//*[contains(@text,'每人限购')]"):
toast = self.driver.find_element_by_xpath("//*[contains(@text,'每人限购')]")
print(toast.text)
except:
# 点击提交订单
CheckOrderPage(self.driver).submit_click()
time.sleep(3)
allure.attach("提交订单", "输入支付密码")
# 输入支付密码
text = "123456"
CheckOrderPage(self.driver).check_pwd_input(text)
# 点击确定
CheckOrderPage(self.driver).sure_click()
# 点击返回上一页
for i in range(4):
self.driver.back()
time.sleep(2)
allure.attach("点击我的", "进入个人中心")
# 进入个人中心
PersonalPage(self.driver).personal_click()
# 获取金额
money_f = float(PersonalPage(self.driver).get_value())
allure.attach("购买商品后的金额:", f'{money_f}')
# 断言
if money_b-price == money_f:
assert 1
else:
Base(self.driver).screenshot("../screenshot/buy_sales.png")
assert 0
def teardown_class(self):
"""关闭app"""
Base(self.driver).close()
| true |
0db4241ae7038cdf4d93d88823936be64c4b9078 | Python | MKermanipoor/Duet-python | /agent.py | UTF-8 | 2,780 | 3.390625 | 3 | [] | no_license | import pyglet
import numpy as np
class Agent:
blue_ball_angle = 0.0
angular_velocity = np.pi
def __init__(self, game):
self.center_circle = [game.width // 2, game.width // 4 + game.width * .08 + 15]
self.center_radius = game.width // 4
blue_circle = pyglet.resource.image('resource/images/blue-circle.png')
blue_circle.width = game.width * .08
blue_circle.height = game.width * .08
blue_circle.anchor_x = blue_circle.width // 2
blue_circle.anchor_y = blue_circle.height // 2
self.blue_ball_sprite = pyglet.sprite.Sprite(blue_circle)
red_circle = pyglet.resource.image('resource/images/red-circle.png')
red_circle.width = game.width * .08
red_circle.height = game.width * .08
red_circle.anchor_x = red_circle.width // 2
red_circle.anchor_y = red_circle.height // 2
self.red_ball_sprite = pyglet.sprite.Sprite(red_circle)
def __get_ball_position(self, angel):
x = self.center_circle[0] + self.center_radius * np.cos(angel)
y = self.center_circle[1] + self.center_radius * np.sin(angel)
return [x, y]
def draw(self):
blue_ball_position = self.__get_ball_position(self.blue_ball_angle)
self.blue_ball_sprite.x = blue_ball_position[0]
self.blue_ball_sprite.y = blue_ball_position[1]
red_ball_position = self.__get_ball_position(self.blue_ball_angle + np.pi)
self.red_ball_sprite.x = red_ball_position[0]
self.red_ball_sprite.y = red_ball_position[1]
self.blue_ball_sprite.draw()
self.red_ball_sprite.draw()
def tern_left(self, dt):
self.blue_ball_angle += self.angular_velocity * dt
if self.blue_ball_angle > 2 * np.pi:
self.blue_ball_angle -= 2 * np.pi
def tern_right(self, dt):
self.blue_ball_angle -= self.angular_velocity * dt
if self.blue_ball_angle < 0:
self.blue_ball_angle += 2 * np.pi
def is_intersects(self, obstacle):
return Agent.__is_ball_intersects(self.blue_ball_sprite, obstacle) or Agent.__is_ball_intersects(self.red_ball_sprite, obstacle)
@staticmethod
def __is_ball_intersects(ball, obstacle):
dx = abs(ball.x - obstacle.get_x())
dy = abs(ball.y - obstacle.get_y())
if dx > obstacle.get_width() / 2 + ball.width:
return False
if dy > obstacle.get_height() / 2 + ball.height:
return False
if dx <= obstacle.get_width() / 2:
return True
if dy <= obstacle.get_height() / 2:
return True
corner_distance_sq = (dx - obstacle.get_width() / 2) ** 2 + (dy - obstacle.get_height() / 2) ** 2
return corner_distance_sq <= (ball.width ^ 2)
| true |
6914fb1f79ca91bb1f8e6f081322a5eb52538eac | Python | nadimhoque/hackerrank | /Interview_Preparation_Kit/Dictionaries and Hashmaps/Two Strings/src/twostrings.py | UTF-8 | 401 | 3.1875 | 3 | [] | no_license | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the twoStrings function below.
def twoStrings(s1, s2):
s1count = Counter(s1)
s2count = Counter(s2)
for i in s1count.keys():
if i in s2count:
print(i)
else:
return 'No'
s1 = "hello"
s2 = "world"
ex=twoStrings(s1,s2)
print(ex)
| true |
419a330b0841a47bdbf4795f91aa9d79e9d67d43 | Python | IrvingBaez/ProteinAnalyzer | /App/Views/CrossMatrixConfig.py | UTF-8 | 2,543 | 2.84375 | 3 | [] | no_license | from tkinter import *
from tkinter import ttk, filedialog
import numpy
from matplotlib import pyplot as plt
from App.Views.Views import set_scrollbars, dataframe_to_treeview
class CrossMatrixConfig:
def __init__(self, controller):
self.controller = controller
self.neighbours = controller.data
popup = Toplevel()
popup.geometry("500x500+0+0")
popup.grab_set()
# Button container
button_container = LabelFrame(popup, text="Opciones")
button_container.pack(side=TOP, fill=X)
# Number of elements
self.element_text = ttk.Entry(button_container, text="Número de elementos")
self.element_text.pack(anchor=W)
# High or low
self.selection = IntVar(value=1)
radio1 = Radiobutton(button_container, text="Más altos", variable=self.selection, value=1)
radio2 = Radiobutton(button_container, text="Más bajos", variable=self.selection, value=2)
radio1.pack(anchor=W)
radio2.pack(anchor=W)
self.graph_button = ttk.Button(popup, text="Graficar", command=self.plot)
self.graph_button.pack()
def plot(self):
# Domains sorted by number of distinct neighbours
neighbours_count = [[key, len(val)] for key, val in self.neighbours.items()]
neighbours_count.sort(key=lambda x: x[1], reverse=self.selection.get() == 1)
# Extracting relevant domain names
limit = int(self.element_text.get())
domains = list(map(lambda x: x[0], neighbours_count[0:limit]))
# Creating matrix and counting relations
matrix = numpy.zeros((len(domains), len(domains)))
for domain in domains:
for neighbour in self.neighbours[domain]:
if neighbour in domains:
matrix[domains.index(domain)][domains.index(neighbour)] += 1
fig, ax = plt.subplots()
im = ax.imshow(matrix)
# We want to show all ticks...
ax.set_xticks(numpy.arange(len(domains)))
ax.set_yticks(numpy.arange(len(domains)))
# ... and label them with the respective list entries
ax.set_xticklabels(domains)
ax.set_yticklabels(domains)
plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
for i in range(len(domains)):
for j in range(len(domains)):
text = ax.text(j, i, matrix[i, j], ha="center", va="center", color="w")
ax.set_title("Heatmap")
fig.tight_layout()
plt.show()
| true |
176a78adba8fb62df2933ca71c1067b95e9d825b | Python | nguyenkimthanh1410/GameOfGo | /KimAnhNguyenA2_Version2.py | UTF-8 | 11,383 | 4.40625 | 4 | [] | no_license | """
Date: 17/05/2015.
Student: Kim Anh Nguyen
Student ID: 13138914
Basic description: Golf Game
User see menu of 4 options: Instructions, View scores, Play round, Quit
Program always returns to menu, only if quit is chosen
When the game starts:
Each swing, user selects one of 4 clubs,
Program generates random distance for each shot
The game continues until the ball is in the hole.
View scores: Display names and scores in assending order
"""
"""
Pseudocode:
# Declare GLOBAL CONSTANTS
Minimum character of name
Maximum character of name
Minimum number of rounds to play
Maximum number of rounds to play
Filename will be used to record the scores
Dictionary to store list of clubs and its properties
the club's information will be kept with key-value pair
in format as follow:
one (key: value pair) = "symbol character":(name club, length of club)
Minimum distance of Putter can hit
Origin distance of the ball
Par value
Low limit rate of average distance
High limit rate of average distance
1.Define main function
Display a welcom message with programer's name
Get valid name
Display choice menu
Get choice
while choice not equal to Quit
if choice is I
display Instructions
display list of clubs to choose
else if choice is V
display all scores, names kept in scores.txt in assending order
else if choice is P
player will play round
else
display invalid menu choice
Display choice menu
Get choice again
Display thanks for playing.
2. Define getValidName, check name's length, with 2 parameters (prompt, error message)
User keys in name with prompt
while length of name doesn't fall into range of min, max number of characters
display error message
ask user to key in other name
return name
3. Define function to display club selection
for each abbreviation in dictionary keys
display fullname and length of each club
4. Define function to view score
"""
"""
Python codes
"""
# Declare GLOBAL CONSTANTS
MIN_NAME_CHAR = 1 # Minimum character of name
MAX_NAME_CHAR = 27 # Maximum character of name
MIN_ROUND = 1 # Minimum number of round to play
MAX_ROUND = 9 # Maximum number of round to play
FILE_NAME = 'scores.txt' # File to read or write scores
# key &(name, value) of clubs stored in a dictionary
DICT_CLUBS = {'7':('7 Iron',30),
'D':('Driver',100),
'P':('Putter',10),
'3':('3 Iron',60)}
MIN_LEN_P = 1 # Minimum distance of Putter can hit: 1m
TARGET = 230 # The origin distance: 230m
PAR_NUM = 5 # par=5
LOW_RATE = 0.8 # Lower limit rate of average distance:80%
HIGH_RATE = 1.2 # High limit rate of average distance: 120%
def main():
# Display a welcome message with name in it
print("""Let's play golf, CP1200 style!
Written by Kim Anh Nguyen, May 2015
"""
,end='')
# Get valid name
name = getValidName('Please enter your name: ',\
'Your name can not be blank and must be <= 27 characters')
# Get choice and execute codes associated with choice
viewMenuChoice()
choice = input('>>> ')
choice = choice.upper()
while choice != 'Q':
if choice == 'I':
print("""Instructions: It's a golf on your console. Each shot will vary in distance around
its average.
"""
,end='')
viewClubSelection()
elif choice == 'V':
viewScores()
elif choice == 'P':
playRound(name)
else:
print('Invalid menu choice.')
viewMenuChoice()
choice = input('>>> ')
choice = choice.upper()
print('Thanks for playing.')
# Function getValidName error-checking name to satisfy name's length
def getValidName (prompt,errorMessage):
name = input(prompt)
while len(name) not in list(range(MIN_NAME_CHAR, MAX_NAME_CHAR)):
print(errorMessage)
name = input(prompt)
return name
# Function to display options of menu choice
def viewMenuChoice():
print("""
Golf!
(I)structions
(V)iew scores
(P)lay round
(Q)uit
"""
,end='')
# Function to display club selection
def viewClubSelection():
print('Club selection:')
for key in DICT_CLUBS.keys():
nameClub,lenClub = DICT_CLUBS.get(key)
print(key, ' for ', nameClub, ' (',lenClub,')',sep='')
# Function to view players' scores
# Read scores from the file, store values into a list, sort list
# Display results in ascending order
def viewScores():
scores = []
fileIn = open(FILE_NAME, 'r')
for line in fileIn:
line = line.strip().split(', ')
record = (int(line[0]),line[1])
scores.append(record)
scores.sort()
for score, name in scores:
print(name,' '*(27-len(name)), format(score,'2,d'))
fileIn.close()
# Function to error-checking valid number of rounds to play
# Check number of round is digits, alpha
def getValidRound(prompt,errorMessage):
isRoundInvalid = True
numRound = input(prompt+ ' ('+ str(MIN_ROUND)+ '-'+ str(MAX_ROUND)+ ') ')
while isRoundInvalid:
if numRound.isdigit():
if int(numRound) not in range(MIN_ROUND,MAX_ROUND+1):
print(errorMessage)
else:
isRoundInvalid = False
elif numRound.isalpha():
print(errorMessage)
else:
print(errorMessage)
if isRoundInvalid == True:
numRound = input(prompt+ ' ('+ str(MIN_ROUND)+ '-'+ str(MAX_ROUND)+ ') ')
return int(numRound)
# Function to calculate result of each shot
def calculateShotResult(distanceToTarget,countShot,club):
# Import random function to calculate result of shot
import random
lenClub = DICT_CLUBS.get(club)[1]
distanceShot = random.randint(int(lenClub*LOW_RATE),int(lenClub*HIGH_RATE))
distanceToTarget = abs(distanceToTarget - distanceShot) # get the absolute value
countShot +=1
return distanceShot, distanceToTarget, countShot
# Function to save score by appending a new score to the existing file
def saveScoreIntoFile(countShot,name):
fileOut = open(FILE_NAME, 'a')
fileOut.write(str(countShot)+ ', '+ name+ '\n')
fileOut.close()
# Function to error-checking save score
def getValidOptionSave(name):
saveScore = input('Would you like to save your score, '\
+ name.strip().split()[0]+ '? (Y/N) ')
saveScore=saveScore.upper()
while saveScore not in('Y','N'):
print('Please enter Y or N')
saveScore = input('Would you like to save your score, '\
+ name.strip().split()[0]+ '? (Y/N) ')
saveScore=saveScore.upper()
return saveScore
# Play round with a given player
def playRound(name):
numRound = getValidRound('How many rounds would you like to play? ',\
'Invalid number of rounds')
import random
# For each round, player plays by choosing clubs
# The each round only finishs when the ball is in the hole
for round in list(range(1,numRound+1)):
print()
# Display general information
print('Round', round, sep = ' ')
print('This hole is a ', TARGET, 'm par ',PAR_NUM,sep='')
viewClubSelection()
print('You are ', TARGET, 'm from the hole, after 0 shot/s',sep='')
# Declare varibales: countShot to trace number of shots
# distanceToTarget to trace the distance to Target after each shot
countShot = 0
distanceToTarget = TARGET # The postion at the beginning
# Declare a boolen variable isInHole as a flag when the ball is in the hole
isInHole = False
while not isInHole:
# Pick a club to start playing
chooseClub = input('Choose club: ')
chooseClub = chooseClub.upper()
# Calulate result for each shot
if chooseClub == 'D': # Driver is chosen
distanceShot, distanceToTarget, countShot = calculateShotResult(distanceToTarget,countShot,chooseClub)
elif chooseClub == '7': # 7 Iron is chosen
distanceShot, distanceToTarget, countShot = calculateShotResult(distanceToTarget,countShot,chooseClub)
elif chooseClub == '3': # 3 Iron is chosen
distanceShot, distanceToTarget, countShot = calculateShotResult(distanceToTarget,countShot,chooseClub)
# club P is chosen & ball within lenP
# Length of club P: lenP = dictClubs.get('P')[1]
elif (chooseClub == 'P' and distanceToTarget < DICT_CLUBS.get('P')[1]):
# min distance Putter can hit the ball
if distanceToTarget == MIN_LEN_P:
distanceShot = MIN_LEN_P
distanceToTarget = 0
countShot += 1
# Calculate distance of shot, distance to target, count shot
else:
distanceShot = random.randint(int(distanceToTarget*LOW_RATE),\
int(distanceToTarget*HIGH_RATE))
distanceToTarget = abs(distanceToTarget - distanceShot)
countShot += 1
# club P is chosen, distance >= min len of P
elif chooseClub == 'P':
distanceShot, distanceToTarget, countShot = calculateShotResult(distanceToTarget,countShot,chooseClub)
# User picked an invalid club, ball does not move
# still count number of shots
else:
distanceShot = 0
countShot += 1
print("Invalid club selection = air swing :(")
viewClubSelection()
# Display the result of each shot
print('Your shot went ',distanceShot,'m',sep='')
# Ball is still outside the hole
if distanceToTarget != 0:
print('Your are ',distanceToTarget,\
'm from the hole, after ',countShot,' shot/s',sep='')
# When the ball is in the hole, the distanceToTarget == 0
else:
isInHole = True # the flag shows up
print('Cluck... After ',countShot,' hits, the ball is in the hole!',sep='')
# Display complements depending on total shots taken and PAR_NUM
if countShot > PAR_NUM:
print('Disappointing. You are ',countShot-PAR_NUM,' over par.',sep='')
elif countShot < PAR_NUM:
print('Congratulations. You are ',PAR_NUM-countShot,' under par.','\n',sep='')
else:
print("And that's par.","\n")
saveScore = getValidOptionSave(name)
# User chose to save score
if saveScore == 'Y':
saveScoreIntoFile(countShot,name)
print('Score saved. New high scores:')
viewScores()
# Call main function to excute the code
main()
| true |
b52ba12b2259b1513f4800e0ac4e9addd58b1b70 | Python | JmKacprzak/30-Days-of-Python | /30DaysOfPython/day_1/helloworld.py | UTF-8 | 747 | 4.0625 | 4 | [] | no_license | # Question 1
print('I am using python version v2021.10.1317843341')
# Question 2
print(3+4)
print(3-4)
print(3*4)
print(4%3)
print(4/3)
print(3**4)
print(4//3)
# Question 3
print('Jacek')
print('Kacprzak')
print('Poland')
print('I am enjoying 30 days of python')
# Question 4
print(type(10))
print(type(9.8))
print(type(3.14))
print(type(4 - 4j))
print(type(['Asabeneh', 'Python', 'Finland']))
print(type('Jacek'))
print(type('Kacprzak'))
print(type('Poland'))
# Excercise: Level 3
print(5)
print(5.8)
print(1+1j)
print('hello')
print(True)
print(['Jacek','Jess','Leo'])
print(('Jacek', 7, 5.6))
print({'Jacek', 7, 5.6})
print({'name':'Jacek'})
print('euclidean distance is ', ((8-3)**2+(10-2)**2)**0.5) | true |
3ecba1c5b723004be57e12ad70ed7c88ae927a43 | Python | Aasthaengg/IBMdataset | /Python_codes/p03352/s777392322.py | UTF-8 | 173 | 2.96875 | 3 | [] | no_license | x = int(input())
ans = 1000000
for b in range(1,32):
for p in range(2,10):
if x-b**p < 0:
continue
ans = min(ans,abs(x-(b**p)))
print(x-ans)
| true |
cc137451617e138a75f89f71435a4af032cc934c | Python | gaqzi/riksdagen | /bin/riksdagen-convert-to-csv | UTF-8 | 1,712 | 2.609375 | 3 | [] | no_license | #!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import argparse
import csv
from riksdagen import db
from riksdagen.api import votation_year
from sqlalchemy import create_engine
parser = argparse.ArgumentParser(
description="Convert a Riksmöte's votations into a CSV file.")
parser.add_argument('year', help='The year a Riksmöte is started')
parser.add_argument(
'--db-connection',
default='sqlite:///riksdagen.sqlite3',
help='A DB connection string that SQLAlchemy will understand')
args = parser.parse_args()
engine = create_engine(args.db_connection)
db.Session.configure(bind=engine)
session = db.Session()
votations = {}
year = session.query(db.WorkingYear).get(votation_year(args.year))
if not year:
print 'No data for {}'.format(args.year)
exit(1)
for votation in year.votations:
votations[votation.id.encode('utf-8')] = '{0}-{1}'.format(
votation.name,
votation.set_number).encode('utf-8')
file = open('output-{0}.csv'.format(args.year), 'w+')
outfile = csv.DictWriter(file,
[u'Namn', u'Parti'] + sorted(votations.values()))
outfile.writeheader()
votation_ids = votations.keys()
for person in session.query(db.Person).order_by(db.Person.last_name,
db.Person.first_name):
votation_data = {u'Namn': person.name.encode('utf-8')}
for vote in person.votes:
votation_id = vote.votation_id.encode('utf-8')
if votation_id in votation_ids:
votation_data[votations[votation_id]] = vote.vote.encode('utf-8')
votation_data[u'Parti'] = vote.party.encode('utf-8')
outfile.writerow(votation_data)
file.close() | true |