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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b093479023e68f07a4ac27da8eb72fbf732d12f9 | Python | t19b253d/EicDesignLab | /eiclab_photorefs.py | UTF-8 | 1,416 | 3.359375 | 3 | [
"MIT"
] | permissive | # coding: UTF-8
"""
フォトリフレクタのON/OFF入力(スレッド版)
「電子情報通信設計製図」新潟大学工学部工学科電子情報通信プログラム
参考サイト
https://gpiozero.readthedocs.io/en/stable/index.html
"""
import gpiozero
from gpiozero import Button, LED
from gpiozero.tools import any_values
from signal import pause
def main():
""" メイン関数 """
# 接続ピン
PIN_LD = 23
PIN_PR = [ 10, 9, 11, 8 ]
# フォトリフレクタラベル(フィールド追加)
Button.label = 0
# 赤色lED設定
red = LED(PIN_LD)
# フォトリフレクタ(複数)設定(ボタンとして)
photorefs = [ Button(PIN_PR[idx], active_state=True, pull_up=None) \
for idx in range(len(PIN_PR)) ]
# フォトリフレクタラベル設定
for idx in range(len(photorefs)):
photorefs[idx].label = idx+1
# フォトリフレクタ検出結果の論理和をLED入力に接続
red.source = any_values(photorefs[0],photorefs[1], \
photorefs[2],photorefs[3])
# コールバック設定
for pr in photorefs:
# 白色検出時
pr.when_pressed = white
# 黒色検出時
pr.when_released = black
# 停止(Ctrl+c)まで待機
pause()
def white(pr):
""" 白色表示関数 """
print('{}:White'.format(pr.label))
def black(pr):
""" 黒色表示関数 """
print('{}:Black'.format(pr.label))
if __name__ == '__main__':
main()
| true |
e58507bb6272a723eabce5d078c644a53b25c108 | Python | edprince/uni | /121com_intro_computing/worksheets/8/bank_account.py | UTF-8 | 1,825 | 3.875 | 4 | [] | no_license | class BankAccount:
"""Stores info about an account
Holds information such as names, addresses and balances of different bank
accounts"""
bankName = 'Natwest'
__count = 0
def __init__(self, N, A):
self.name = N
self.address = A
self.__balance = 0
BankAccount.__count += 1
def withdraw(self, x):
if (self.__balance - x < 0):
raise ValueError('You do not have sufficient funds for this transaction')
else:
self.__balance -= x
def deposit(self, x):
self.__balance += x
def get_balance(self):
return(self.__balance)
def display(self):
print(self.name + ' - ' + str(self.__balance))
def transfer(self, destination, amount):
if (self.__balance - amount < 0):
raise ValueError('Insufficient funds')
else:
try:
self.__balance -= amount
destination.__balance += amount
except:
raise ValueError('Cannot find destination')
def __add__(self, other):
if type(other) == int:
self.__balance += other
else:
try:
#self.name = (self.name, other.name)
#self.address = (self.address, other.address)
self.__balance += other.__balance
other.__balance = 0
except:
pass
bank1 = BankAccount('Ed Prince', '4 Stockghyll Brow')
bank2 = BankAccount('Dan Prince', 'Somewhere, Himalayas, India')
bank1.display()
bank1.deposit(12)
bank2.deposit(100000)
print(bank1.get_balance())
bank_merge = (bank2 + bank1)
print(bank_merge)
print(bank1.get_balance())
print(bank2.get_balance())
print(bank2.display())
bank3 = BankAccount('Ambrose', 'Australia')
bank2.get_balance()
bank1.display()
| true |
63c24001cb965e129f8d1b11c59b974dacc7380a | Python | lhcopt/lhcmask | /unmask.py | UTF-8 | 3,223 | 2.921875 | 3 | [] | no_license |
def unmask(mask_filename, parameters,
output_filename=None, nocheck=False):
with open(mask_filename, 'r') as fid:
content = fid.read()
for kk in parameters.keys():
content = content.replace(kk, str(parameters[kk]))
if output_filename is None:
outfname = None
elif output_filename == 'auto':
outfname = mask_filename+'.unmasked'
else:
outfname = output_filename
if not nocheck:
if '\%' in content:
content = content.replace('\%', 'escapedpercentsymbol')
if '%' in content:
raise ValueError(
('There is still a % after unmasking!\n'
'--> Incompatible with nocheck=False\n'
'from command line add --nocheck to skip the check.'))
content = content.replace('escapedpercentsymbol', '%')
content = content.replace('/%', '%')
if outfname is not None:
with open(outfname, 'w') as fid:
fid.write(content)
return content
def parse_parameter_file(fname):
with open(fname, 'r') as fid:
lines = fid.readlines()
ddd = {}
for ii, ll in enumerate(lines):
if ':' not in ll:
print('Warning! line %d is skipped! Its content is:'%(ii+1))
print(ll)
continue
nn = ll.split(':')[0].replace(' ', '').replace('\n', '')
vv = ll.split(':')[1].replace(' ', '').replace('\n', '')
ddd[nn] = vv
return ddd
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Unmasks a madx maskfile.')
parser.add_argument('mask_filename', help='Name of the maskfile to be unmasked')
parser.add_argument('parameters', nargs='+', help=('Parameters for unmasking (can be a filename,'
'or given inline as: %%PARAM1%%:value1, %%PARAM2:value2, ...'))
parser.add_argument('--output_filename', help='Name of the output file', default='auto')
parser.add_argument('--run', help='Execute in madx after unmasking', action='store_true')
parser.add_argument('--run-cpymad', help='Execute in cpymad after unmasking', action='store_true')
parser.add_argument('--nocheck', help='Skip check that all %%s are removed', action='store_true')
args = parser.parse_args()
if ':' in args.parameters[0]:
par_dict = {}
for pp in args.parameters:
kk = pp.split(':')[0].replace(' ', '')
vv = pp.split(':')[1].replace(' ', '')
par_dict[kk] = vv
else:
par_dict = parse_parameter_file(args.parameters[0])
content = unmask(args.mask_filename, par_dict, output_filename=args.output_filename,
nocheck=args.nocheck)
if args.run:
import os
if args.output_filename == 'auto':
outfname = args.mask_filename+'.unmasked'
else:
outfname = args.output_filename
os.system('madx ' + outfname)
if args.run_cpymad:
import os
if args.output_filename == 'auto':
outfname = args.mask_filename+'.unmasked'
else:
outfname = args.output_filename
from cpymad.madx import Madx
mad=Madx()
mad.call(outfname)
| true |
f0adaac7a799629a81000d89a03a98cbe436ba7b | Python | AdamZhouSE/pythonHomework | /Code/CodeRecords/2494/60714/293127.py | UTF-8 | 163 | 2.96875 | 3 | [] | no_license | nums = eval(input())
ans = 0
for i in range(0, len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] > 2 * nums[j]:
ans += 1
print(ans)
| true |
a6d80f6fb5b02c3ed4638dc0895db1f77b9ca7c0 | Python | Davidson-Souza/ProcessamentoDeImagens | /Atividade07/grapkut.py | UTF-8 | 5,202 | 2.84375 | 3 | [] | no_license | from tkinter import *
from PIL import Image
from PIL import ImageTk
import tkinter.filedialog
import cv2
import numpy as np
class GrabCutGUI(Frame):
# Instancia um frame novo
def __init__(self, master = None):
Frame.__init__(self, master)
self.iniciaUI()
# inicializa o frame
def iniciaUI(self):
self.master.title("Janela da Imagem Segmentada")
self.pack()
# Configura as callbacks
self.computaAcoesDoMouse()
self.imagem = self.carregaImagemASerExibida()
self.canvas = Canvas(self.master, width = self.imagem.width(), height = self.imagem.height(), cursor = "cross")
self.canvas.create_image(0, 0, anchor = NW, image = self.imagem)
self.canvas.image = self.imagem
self.canvas.pack()
# Callback para quando ocorre uma ação com o mouse
def computaAcoesDoMouse(self):
self.startX = None
self.startY = None
self.rect = None
self.rectangleReady = None
self.master.bind("<ButtonPress-1>", self.callbackBotaoPressionado)
self.master.bind("<B1-Motion>", self.callbackBotaoPressionadoEmMovimento)
self.master.bind("<ButtonRelease-1>", self.callbackBotaoSolto)
# Callback para quando o botão do mouse é solto.
# Quando isso ocorre, significa que o retângulo foi traçado,
# e agora já podemos aplicar o método.
# Esta função aplica o grapkut e mostra na tela o resultado
def callbackBotaoSolto(self, event):
if self.rectangleReady:
windowGrabcut = Toplevel(self.master)
windowGrabcut.wm_title("Segmentation")
windowGrabcut.minsize(width = self.imagem.width(), height = self.imagem.height())
canvasGrabcut = Canvas(windowGrabcut, width = self.imagem.width(), height = self.imagem.height())
canvasGrabcut.pack()
mask = np.zeros(self.imagemOpenCV.shape[:2], np.uint8)
print(mask.shape)
rectGcut = (int(self.startX), int(self.startY), int(event.x - self.startX), int(event.y - self.startY))
fundoModel = np.zeros((1, 65), np.float64)
objModel = np.zeros((1, 65), np.float64)
cv2.grabCut(self.imagemOpenCV, mask, rectGcut, fundoModel, objModel, 5, cv2.GC_INIT_WITH_RECT)
maskFinal = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
maskFund = np.where((mask == 1) | (mask == 3), 0, 1).astype('uint8')
"""
Aqui ele cria duas images, uma com o objeto, outra com o fundo.
Então, aplica o blur na imagem do fundo, e finalmente, coloca as
imagens juntas novamente.
Para tanto, o algoritmo percorre pexel-a-pixel, e então verifica onde
na máscara está zerado, pois 0 na máscara significa que o píxel pertence
ao fundo, e cola o respectivo píxel do fundo na imagem original. No final,
os pixels do objeto estarão intactos, mas os pixels que estavam vazios, agora
possuem o fundo, mas com um efeito de blur aplicado
"""
imgFinal = self.imagemOpenCV * maskFinal[:,:,np.newaxis]
funFinal = self.imagemOpenCV * maskFund[:,:,np.newaxis]
funFinal = cv2.blur(funFinal,(5,5))
for x in range(0, self.imagemOpenCV.shape[1]):
for y in range(0, self.imagemOpenCV.shape[0]):
if(maskFinal[y][x] == 0):
imgFinal[y][x] = funFinal[y][x]
imgFinal = cv2.cvtColor(imgFinal, cv2.COLOR_BGR2RGB)
imgFinal = Image.fromarray(imgFinal)
imgFinal = ImageTk.PhotoImage(imgFinal)
canvasGrabcut.create_image(0, 0, anchor = NW, image = imgFinal)
canvasGrabcut.image = imgFinal
def callbackBotaoPressionadoEmMovimento(self, event):
currentX = self.canvas.canvasx(event.x)
currentY = self.canvas.canvasy(event.y)
self.canvas.coords(self.rect, self.startX, self.startY, currentX, currentY)
self.rectangleReady = True
def callbackBotaoPressionado(self, event):
self.startX = self.canvas.canvasx(event.x)
self.startY = self.canvas.canvasy(event.y)
if not self.rect:
self.rect = self.canvas.create_rectangle(0, 0, 0, 0, outline="blue")
def carregaImagemASerExibida(self):
caminhoDaImagem = tkinter.filedialog.askopenfile()
if(not caminhoDaImagem is None):
print(caminhoDaImagem)
self.imagemOpenCV = cv2.imread(caminhoDaImagem.name)
image = cv2.cvtColor(self.imagemOpenCV, cv2.COLOR_BGR2RGB)
image = Image.fromarray(image)
image = ImageTk.PhotoImage(image)
return image
def main():
# Instancia o tkinter para criar o novo frame
root = Tk()
# Cria o novo frame
appcut = GrabCutGUI(master = root)
# Loop que será responsável por exibir e atualizar itens na tela
appcut.mainloop()
# Chama a main
if __name__ == "__main__":
main()
| true |
5dfbbaba97dc1d8023387e76ccb68d5890277724 | Python | anirudhkannanvp/CODEFORCES | /Codeforces-Round-665-Div-2/3.py | UTF-8 | 330 | 3.078125 | 3 | [
"MIT"
] | permissive | t = int(input())
for _ in range(t):
n=int(input())
arr = list(map(int,input().split()))
mini=min(arr)
arr2 = sorted(arr)
st=0
for i in range(n):
if(arr[i]!=arr2[i] and arr[i]%mini!=0):
st=1
break
if(st==1):
print("NO")
else:
print("YES")
| true |
81bd1d2c7ab8364d526ee22cafe647db8071b824 | Python | jainamshah95/CodeEval | /LCS_calc.py | UTF-8 | 2,266 | 3.625 | 4 | [] | no_license | '''
Author: Sheldon Logan
Longest common subsequence
Description:
You are given two sequences. Write a program to determine the longest common
subsequence between the two strings(each string can have a maximum length of
50 characters). (NOTE: This subsequence need not be contiguous. The input
file may contain empty lines, these need to be ignored.)
Input sample:
The first argument will be a file that contains two strings per line,
semicolon delimited. You can assume that there is only one unique
subsequence per test case. e.g.
XMJYAUZ;MZJAWXU
Output sample:
The longest common subsequence. Ensure that there are no trailing empty
spaces on each line you print. e.g.
MJAU
'''
import sys
def BuidLCSTable(seq1,seq2):
len_seq1 = len(seq1)
len_seq2 = len(seq2)
dyn_prog_table = []
for row in range(len_seq2+1):
dyn_prog_table.append([0]*(len_seq1+1))
for row_idx in range(1,len_seq2+1):
for col_idx in range(1,len_seq1+1):
if(seq2[row_idx-1] == seq1[col_idx-1]):
dyn_prog_table[row_idx][col_idx] = dyn_prog_table[row_idx-1][col_idx-1] + 1
else:
dyn_prog_table[row_idx][col_idx] = max([dyn_prog_table[row_idx][col_idx-1],dyn_prog_table[row_idx-1][col_idx]])
return(dyn_prog_table)
def BuildLCS(dyn_prog_table, seq1, seq2, row_idx, col_idx):
if(row_idx == 0 or col_idx == 0):
return ""
elif seq1[col_idx-1] == seq2[row_idx-1]:
return(BuildLCS(dyn_prog_table, seq1, seq2, row_idx-1, col_idx-1)+ seq1[col_idx-1])
else:
if(dyn_prog_table[row_idx][col_idx-1]>dyn_prog_table[row_idx-1][col_idx]):
return(BuildLCS(dyn_prog_table, seq1, seq2, row_idx, col_idx-1))
else:
return(BuildLCS(dyn_prog_table, seq1, seq2, row_idx-1, col_idx))
def GetLCS(seq1,seq2):
LCStable = BuidLCSTable(seq1,seq2);
max_row_idx = len(seq2)
max_col_idx = len(seq1)
LCS = BuildLCS(LCStable, seq1, seq2, max_row_idx, max_col_idx)
print(LCS)
testcases = open(sys.argv[1],'r')
for test in testcases:
if(test.strip()):
input_line = test.split(';')
seq1 = input_line[0]
seq2 = input_line[1].strip()
GetLCS(seq1,seq2)
testcases.close()
| true |
275af5c457d8ae0bea228a48616407c1689e5753 | Python | yours520/life_game1 | /test_model.py | UTF-8 | 694 | 2.765625 | 3 | [] | no_license | from unittest import TestCase
import Model
class TestModel(TestCase):
def setUp(self):
self.model = Model.Model(4,3)
pass
def test_get_neighbor_count(self):
expected_value = [[8]*3]*4
self.model.map = [[1]*3]*4
for i in range(0,4):
for j in range(0,3):
self.assertEquals(expected_value[i][j],self.model.get_neighbor_count(i,j))
def test_updateMap(self):
self.fail()
'''
def test_rows(self):
self.assertEquals(4,self.model.numCols,"Should get correct rows")
def test_cols(self):
self.assertEquals(3,self.model.numCols,"Should get correct cols")
''' | true |
e54e04c034e4272ddb8bd729746ba7ac7674b155 | Python | Jwalin007/self-driving-car-game | /inputbox.py | UTF-8 | 1,561 | 3.1875 | 3 | [] | no_license | import pygame, pygame.font, pygame.event, pygame.draw, string
from pygame.locals import *
def get_key():
while 1:
event = pygame.event.poll()
if event.type == pygame.KEYDOWN:
return event.key
else:
pass
def display_box(screen, message):
"Print a message in a box in the middle of the screen"
fontobject = pygame.font.Font(None,30)
pygame.draw.rect(screen, (0,0,0),
((screen.get_width() / 2) - 50,
(screen.get_height() / 1.70) - 10,
250,30), 0)
pygame.draw.rect(screen, (255,255,255),
((screen.get_width() / 2) - 50,
(screen.get_height() / 1.70) - 12,
250,34), 1)
if len(message) != 0:
screen.blit(fontobject.render(message, 1, (255,255,255)),
((screen.get_width() / 2) - 185, (screen.get_height() / 1.70) - 5))
pygame.display.flip()
def ask(screen, question):
pygame.font.init()
current_string = []
display_box(screen, question + " : " + ''.join(current_string))
while 1:
inkey = get_key()
if inkey == K_BACKSPACE:
current_string = current_string[0:-1]
elif inkey == K_RETURN:
break
elif inkey == K_MINUS:
current_string.append("_")
elif inkey <= 127:
current_string.append(chr(inkey))
display_box(screen, question + " : " + ''.join(current_string))
return ''.join(current_string)
def main():
screen = pygame.display.set_mode((800,600))
print(ask(screen, "Name") + " was entered")
if __name__ == '__main__': main() | true |
1c278722e449701c8941dac8dcee1087edfd3a11 | Python | Sandmann11/kursy_walut | /waluty.py | UTF-8 | 959 | 3.359375 | 3 | [] | no_license | import requests
waluta = input('Podaj kod waluty: ')
check_api = 'http://api.nbp.pl/api/exchangerates/tables/a?format=json'
json_check_data = requests.get(check_api).json()
waluty = []
for curr in json_check_data[0]['rates']:
waluty.append(curr['code'])
# Pobiera aktualny kurs danej waluty
def currency_rate():
global rate
main_api = 'http://api.nbp.pl/api/exchangerates/rates/a/'
format = '/?format=json'
url = '{}{}{}'.format(main_api, waluta, format)
json_data = requests.get(url).json()
rate = json_data['rates'][0]['mid']
date = json_data['rates'][0]['effectiveDate']
print('Średni kurs {} na dzień '.format(waluta.upper()) + str(date) + ': ' + (str(round(rate, 2))) + ' zł.')
currency_rate()
amount_usd = input('Podaj kwotę w {}: '.format(waluta.upper()))
amount_converted = float(amount_usd) * rate
print('{} {} kosztuje '.format(amount_usd, waluta.upper()) + str(round(amount_converted, 2)) + ' zł.')
| true |
40e725c241a1026d3971c9be8af8387d4867b6be | Python | kaaja/BIC | /m2/runAssignment2Revised.py | UTF-8 | 5,497 | 3.0625 | 3 | [] | no_license |
#%%
import numpy as np
def dataAssignment2(filename='movements_day1-3.dat'):
''' Read in all data
Last column is the target value
Make a matrix of target vectors.
Target vetcot length = number different target values
Target vector values =0 for all excpt for the position corresponding to
the target value.
Split data into training, validation, test. 50/25/25
Rescaling by subtracting mean and dividing by max
'''
movements = np.loadtxt(filename,delimiter='\t')
# Subtract arithmetic mean for each sensor. We only care about how it varies:
movements[:,:40] = movements[:,:40] - movements[:,:40].mean(axis=0)
# Find maximum absolute value:
imax = np.concatenate( ( movements.max(axis=0) * np.ones((1,41)) ,
np.abs( movements.min(axis=0) * np.ones((1,41)) ) ),
axis=0 ).max(axis=0)
# Divide by imax, values should now be between -1,1
movements[:,:40] = movements[:,:40]/imax[:40]
#Me np.shape(movements[:,:40]) #--> (447, 40). One column less than original.
#Me print(np.shape(movements)[0]) #--> 447.
# Generate target vectors for all inputs 2 -> [0,1,0,0,0,0,0,0]
# Me: So instead of a scalar between 0 and 7, an array is used.
target = np.zeros((np.shape(movements)[0],8));
for x in range(1,9):
indices = np.where(movements[:,40]==x)
target[indices,x-1] = 1
# Me Col 40 is the scalar of the target.
# Me Fill up all target arrays
# Randomly order the data
order = list(range(np.shape(movements)[0]))
np.random.shuffle(order)
movements = movements[order,:]
target = target[order,:]
# Split data into 3 sets
# Training updates the weights of the network and thus improves the network
train = movements[::2,0:40]
train_targets = target[::2] #Me every 2nd row, start from row0
# Validation checks how well the network is performing and when to stop
valid = movements[1::4,0:40]
valid_targets = target[1::4] #me every 4th row, start row1
# Test data is used to evaluate how good the completely trained network is.
test = movements[3::4,0:40]
test_targets = target[3::4] #me every 4th row, start row3
return train, train_targets, valid, valid_targets, test, test_targets
#train, train_targets, valid, valid_targets, test, test_targets = dataAssignment2()
#import m2
from nnClass import *
def fixedValidationSet(train ,
train_targets ,
valid ,
valid_targets ,
numberOfHiddenNodes=9,
activationFunction= 'sigmoid',
trainingCyclesPerValidation = 5,
maxValidations= 300,
maxLocalOptima = 15):
tstRun3 = NN(inputMatrixTrain = train,
targetMatrixTrain = train_targets,
inputMatrixValid = valid,
targetMatrixValid = valid_targets,
numberOfHiddenNodes = numberOfHiddenNodes,
test = False,
activationFunction = activationFunction)
tstRun3.createWeightsAndLayers()
tstRun3.solAlg1( trainingCyclesPerValidation = trainingCyclesPerValidation, \
maxValidations = maxValidations, maxLocalOptima =maxLocalOptima)
#fixedValidationSet()
# K-fold
def runKfold( train ,
train_targets,
valid ,
valid_targets ,
test,
test_targets,
numberOfHiddenNodes=9,
activationFunction= 'sigmoid',
numberOfFolds = 3,
trainingCyclesPerValidation=1,
maxValidations = 1000,
maxLocalOptima = 15,
printConfusionMatrix=False):
tstRun4 = NN(inputMatrixTrain = train,
targetMatrixTrain = train_targets,
inputMatrixValid = valid,
targetMatrixValid = valid_targets,
inputMatrixTest = test,
targetMatrixTest = test_targets
numberOfHiddenNodes = numberOfHiddenNodes,
test = False,
activationFunction = activationFunction)
tstRun4.kFold(numberOfFolds = numberOfFolds,
trainingCyclesPerValidation = trainingCyclesPerValidation,
maxValidations=maxValidations,
maxLocalOptima=maxLocalOptima,
printConfusionMatrix=printConfusionMatrix)
#runKfold()
# Test set performance
def runTestSet( train ,
train_targets,
valid ,
valid_targets ,
test,
test_targets,
numberOfHiddenNodes=9,
activationFunction= 'sigmoid',
numberOfFolds = 3,
trainingCyclesPerValidation=1,
maxValidations = 1000,
maxLocalOptima = 15,
printConfusionMatrix=False,
printTestResults=True):
tstRun3 = NN(inputMatrixTrain = train,
targetMatrixTrain = train_targets,
inputMatrixValid = valid,
targetMatrixValid = valid_targets,
inputMatrixTest = test,
targetMatrixTest = test_targets,
numberOfHiddenNodes = numberOfHiddenNodes,
test = False,
activationFunction = activationFunction)
tstRun3.createWeightsAndLayers()
tstRun3.solAlg1( trainingCyclesPerValidation = trainingCyclesPerValidation, \
maxValidations = maxValidations, maxLocalOptima =maxLocalOptima)
tstRun3.wHidden = tstRun3.wHiddenBest
tstRun3.wOutput = tstRun3.wOutputBest
tstRun3.targetMatrixValid = tstRun3.targetMatrixTest
tstRun3.inputMatrixValid = tstRun3.inputMatrixTest
tstRun3.targetVector = tstRun3.targetMatrixTest[0, :]
tstRun3.calculateValidationError(printTestResults=printTestResults)
#print(tstRun3.confusionMatrix)
| true |
495791e07ea36f4aa1a12ad55bd8034f6bd5238d | Python | SJ0000/PS | /Programmers/12938.py | UTF-8 | 197 | 2.84375 | 3 | [] | no_license | def solution(n, s):
x = s//n
if x == 0:
return [-1]
mod = s % n
answer = [x for i in range(n-mod)] + [x+1 for i in range(mod)]
return answer
print(solution(2, 1))
| true |
2ef643e6477f5295d718b2a4424c653f2f8ce236 | Python | glo-fq/Taller-Progra-SII-2017-TP-3 | /formulas.py | UTF-8 | 302 | 3.046875 | 3 | [] | no_license | import math
import numpy
def principal():
x = [[50, 42, 80, 70], [32, 29, 15, 19]]
w = numpy.zeros((len(x), len(x[0])))
def encontrarK(x1, m1, m2):
k = argmin(x1, m1, m2)
#Formula
def calcular(x, m):
# ||x1 - m1|| =
resultado = math.sqrt((x[0][0] - m[0][0]) ** 2 + (x[0][1] - m[0][1]) ** 2) | true |
2405fc9a55823cd541ba01ccbaec593a3302a9d3 | Python | Shradha26/SVDRecommender | /RecommendMoviesToUser.py | UTF-8 | 669 | 2.828125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 27 20:22:04 2017
@author: shrad
"""
import os
import pandas as pd
os.chdir('C:\Users\shrad\Desktop\Recommendation_Systems\MatrixFactorization')
movies = pd.read_csv('movies.csv')
rec_df = pd.read_csv('all_users_rec.csv')
user_id = raw_input("Enter user id for recommendation:")
user_id = int(user_id)
outfile = open("Recommendations_"+str(user_id)+".txt","w")
sim_list = rec_df.loc[rec_df['userId']==user_id]['rec_movieId']
sim_list = list(sim_list)
for item in sim_list:
text=movies.loc[movies['movieId']==item].iloc[:,1:4]
outfile.write(str(text))
outfile.close()
print "Generated Recommendations"
| true |
f9b679e26ae47ac45189da51ac6b20e1fc9be9bd | Python | alexanderdavide/advent-of-code-2020 | /day8/8a.py | UTF-8 | 1,002 | 3.109375 | 3 | [] | no_license | def exec_instructions(lines):
lines_run_by_idx = []
acc = 0
idx = 0
while -1 < idx < len(lines):
if idx in lines_run_by_idx:
return acc
else:
lines_run_by_idx.append(idx)
instruction = lines[idx][0:3]
number = lines[idx].split()[1].strip("\n")
if instruction == "nop":
idx += 1
continue
elif instruction == "jmp":
if "+" in number:
idx += int(number[1:])
elif "-" in number:
idx -= int(number[1:])
elif instruction == "acc":
idx += 1
if "+" in number:
acc += int(number[1:])
elif "-" in number:
acc -= int(number[1:])
def main():
with open("8.txt") as input:
lines = input.readlines()
print(exec_instructions(lines))
return 0
if __name__ == "__main__":
exit(main()) | true |
47da931dcf25943d81561d72e99cc1acf70ddcb0 | Python | ryan-yang-2049/oldboy_python_study | /fourth_module/多线程多进程/old/02 多线程/01 开启线程的两种方式.py | UTF-8 | 925 | 3.5 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
__title__ = '01 开启线程的两种方式.py'
__author__ = 'yangyang'
__mtime__ = '2018.01.31'
"""
# 方式一:
# 从资源的角度看,该程序运行的是一个主进程和一个线程
# 从程序的角度看,该程序运行的是一个主线程和一个子线程
# import time
# import random
# from threading import Thread
#
#
# def piao(name):
# print('%s piaoing' %name)
# time.sleep(random.randrange(1,5))
# print('%s piao end'%name)
#
# if __name__ == '__main__':
# t1 = Thread(target=piao,args=('egon',))
# t1.start()
# print("主")
# 方式二:
from threading import Thread
import time
class MyThread(Thread):
def __init__(self,name):
super().__init__()
self.name=name
def run(self):
time.sleep(2)
print('%s say hello' % self.name)
if __name__ == '__main__':
t = MyThread('egon')
t.start()
print('主线程')
| true |
6f8a17cb496648be61c79e7de23a74088de16448 | Python | bazub/ShortUrls | /shorts/l2s.py | UTF-8 | 1,763 | 2.6875 | 3 | [] | no_license | '''
Created on Nov 28, 2012
@author: Bogdan
'''
from sqlalchemy.engine import create_engine
import hashlib
engine = create_engine('postgresql+psycopg2://*')
def long2short(url):
base32='abcdefghijklmnopqrstuvwxyz012345'
url=url.lower()
m=hashlib.md5()
m.update(url)
output=[]
for i in range(0,4):
output.append("")
subHex=m.hexdigest()[i*8:i*8+8]
intval=0x3FFFFFFF & int(subHex,16)
out=''
for j in range(0,6):
val=0x0000001F & intval
out=out+base32[val]
intval= intval>>5
output[i]=output[i]+out
return output
def check_if_long_exists(longLink):
connection= engine.connect()
result=connection.execute("SELECT * FROM shorturls WHERE long=%s",longLink)
connection.close()
return result.rowcount
def get_first_not_used(shortLink):
connection=engine.connect()
result=connection.execute("SELECT * FROM shorturls WHERE short=%s",shortLink)
connection.close()
return result.rowcount
def insert_new_pair(shortLink,longLink):
connection=engine.connect()
connection.execute("INSERT INTO shorturls (short,long) VALUES(%s,%s)", shortLink, longLink)
connection.close()
def get_short_for_long(longLink):
connection=engine.connect()
result=connection.execute("SELECT * FROM shorturls WHERE long=%s",longLink)
connection.close()
for row in result: #only executes 1 operation, but didn't spend time to think of a more clever solution
return row['short']
def get_long_url(shortLink):
connection=engine.connect()
result=connection.execute("SELECT * FROM shorturls WHERE short=%s",shortLink)
if result.rowcount==0:
return 1
for row in result:
return row["long"] | true |
25ab4aad40adb3277a7bcb587044e2d916d6a087 | Python | giffels/PRODAGENT | /src/python/JobEmulator/WorkerNodeInfo.py | UTF-8 | 644 | 2.578125 | 3 | [] | no_license | """
_WorkerNodeInfo_
Dictionary based container for information of a worker node.
"""
__revision__ = "$Id: "
__version__ = "$Revision: "
class WorkerNodeInfo(dict):
"""
_WorkerNodeInfo_
Dictionary based container for information of a worker node.
"""
def __init__(self):
dict.__init__(self)
self.setdefault("SiteName", None)
self.setdefault("HostID", None)
self.setdefault("HostName", None)
self.setdefault("se-name", None)
self.setdefault("ce-name", None)
def updateWorkerNodeInfo(self, workerNodeInfo):
self.update(workerNodeInfo) | true |
99ff4c3910e56b95d5180c068a5c55a2fc0ac16b | Python | VT-Collab/choice-sets | /simulations/lander/archive/sanitycheck.py | UTF-8 | 6,080 | 2.53125 | 3 | [
"MIT"
] | permissive | import gym
import torch
import numpy as np
from train import QNetwork
import matplotlib.pyplot as plt
import LunarLander_c1
import pickle
import random
model_name = "dqn_R3.pth"
path = "../models/" + model_name
qnetwork = QNetwork(state_size=8, action_size=4, seed=1)
qnetwork.load_state_dict(torch.load(path, map_location=torch.device('cpu')))
qnetwork.eval()
softmax = torch.nn.Softmax(dim=1)
scores = None
landings = None
dataset = []
# load environment
env = gym.make('LunarLanderC1-v0')
# we'll rollout over N episodes
episodes = 10
# reward type
r_type = 3
action_stop = 999
max_action_stop = 1000
delay = 1
for episode in range(episodes):
# reset to start
state = env.reset(reward_type = r_type)
landing = 0
score = 0
xi = []
episode_reward = 0
stop_time = random.randint(action_stop, max_action_stop)
for t in range(1000):
if t < stop_time and t % delay == 0 :
# get the best action according to q-network
with torch.no_grad():
state_t = torch.from_numpy(state).float().unsqueeze(0)
action_values = qnetwork(state_t)
action_values = softmax(action_values).cpu().data.numpy()[0]
action = np.argmax(action_values)
elif t > stop_time:
action = 0
# Noise for noisy data - UT Austin method
if r_type == 3 and np.random.random() < 0.05:
action = np.random.randint(0,4)
# apply that action and take a step
env.render() # can always toggle visualization
next_state, _, done, info = env.step(action)
reward = info['reward']
awake = info['awake']
rewards = info['rewards']
xi.append([t] + [action] + [awake] + [state])
state = next_state
score += reward
episode_reward += reward
if done:
print(score)
# print("\rReward: {:.2f}\tLanded: {}\tData Type: {}")
# print("Stoptime: {}\tCurrent Time: {}".format(stop_time, t))
dataset.append(xi)
if awake:
landing += 1
break
env.close()
#
# def get_params(r_type, d_type, max_action_stop):
# model_name = "dqn_R" + str(r_type) + ".pth"
# action_stop = max_action_stop
# # No time stop
# if d_type == 1:
# doc_name = 'R' + str(r_type)
# # With time stops
# elif d_type == 2:
# action_stop = 1
# doc_name = 'R' + str(r_type) + '_easy'
# # With noise
# elif d_type == 3:
# doc_name = 'R' + str(r_type) +'_noisy'
# return action_stop, doc_name, model_name
#
#
# def gen_traj(ep, delay=1, d_type=1, r_type=1, max_action_stop = 1000, save_data=False):
#
# action_stop, doc_name, model_name = get_params(r_type, d_type, max_action_stop)
#
# # load our trained q-network
# path = "../models/" + model_name
# qnetwork = QNetwork(state_size=8, action_size=4, seed=1)
# qnetwork.load_state_dict(torch.load(path))
# qnetwork.eval()
# softmax = torch.nn.Softmax(dim=1)
#
# scores = None
# landings = None
# dataset = []
# # load environment
# env = gym.make('LunarLanderC1-v0')
#
# # we'll rollout over N episodes
# episodes = ep
#
# score = 0
# for episode in range(episodes):
# # reset to start
# state = env.reset(reward_type = r_type)
# landing = 0
# xi = []
# episode_reward = 0
# stop_time = random.randint(action_stop, max_action_stop)
#
# for t in range(1000):
# if t < stop_time and t % delay == 0 :
# # get the best action according to q-network
# with torch.no_grad():
# state_t = torch.from_numpy(state).float().unsqueeze(0)
# action_values = qnetwork(state_t)
# action_values = softmax(action_values).cpu().data.numpy()[0]
# action = np.argmax(action_values)
# elif t > stop_time:
# action = 0
# # Noise for noisy data - UT Austin method
# if r_type == 3 and np.random.random() < 0.05:
# action = np.random.randint(0,4)
#
# # apply that action and take a step
# # env.render() # can always toggle visualization
# next_state, _, done, info = env.step(action)
# reward = info['reward']
# awake = info['awake']
# rewards = info['rewards']
# xi.append([t] + [action] + [awake] + [state])
# state = next_state
# score += reward
# episode_reward += reward
#
# if done:
# print("\rReward: {:.2f}\tLanded: {}\tData Type: {}"\
# .format(episode_reward, awake, r_type, doc_name), end="")
# # print("Stoptime: {}\tCurrent Time: {}".format(stop_time, t))
# dataset.append(xi)
# if awake:
# landing += 1
# break
# env.close()
# if save_data:
# savename = doc_name + '_t_' + str(delay)
# print("\nSave name {}\tEpisodes: {}".format(savename, len(dataset)))
# dataname = '../data/lander_' + savename + '.pkl'
# pickle.dump( dataset, open( dataname, "wb" ) )
# return dataset
#
# def main():
#
# t_delay = range(1,11)
# episodes = 25
# episodes_noisy = 100
# episodes_counter = 100
# max_action_stop = 150
# save_data = True
#
# for delay in t_delay:
# r1_demos = gen_traj(episodes, delay=delay, d_type=1, save_data=save_data)
# r1_counterfactuals = gen_traj(episodes_counter, delay=delay,\
# d_type=2, max_action_stop=max_action_stop, save_data=save_data)
# r1_noisies = gen_traj(episodes_noisy, delay=delay, d_type=3, save_data=save_data)
#
# r2_optimals = gen_traj(episodes, r_type=2, save_data=save_data)
# r3_optimals = gen_traj(episodes, r_type=3, save_data=save_data)
#
# if __name__ == "__main__":
# main()
| true |
ff77598bde3cf4b7dbd95827da1ef49c16539484 | Python | tmoreau89/tvm | /python/tvm/script/printer/doc_printer.py | UTF-8 | 1,945 | 2.609375 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"Zlib",
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Functions to print doc into text format"""
from typing import Optional
from tvm.runtime.object_path import ObjectPath
from . import _ffi_api
from .doc import Doc
def to_python_script(
doc: Doc,
indent_spaces: int = 4,
print_line_numbers: bool = False,
num_context_lines: Optional[int] = None,
path_to_underline: Optional[ObjectPath] = None,
) -> str:
"""Convert Doc into Python script.
Parameters
----------
doc : Doc
The doc to convert into Python script
indent_spaces : int
The number of indent spaces to use in the output
print_line_numbers: bool
Whether to print line numbers
num_context_lines : Optional[int]
Number of context lines to print around the underlined text
path_to_underline : Optional[ObjectPath]
Object path to be underlined
Returns
-------
script : str
The text representation of Doc in Python syntax
"""
if num_context_lines is None:
num_context_lines = -1
return _ffi_api.DocToPythonScript( # type: ignore
doc, indent_spaces, print_line_numbers, num_context_lines, path_to_underline
)
| true |
86b7fb6ce48e959fbae20dea531ac75014e5abf0 | Python | baboleevan/publicpy | /lib/test_thread_manager.py | UTF-8 | 365 | 2.71875 | 3 | [] | no_license | from lib.thread_manager import ThreadManager
import time
manager = ThreadManager()
def wait(sec):
print('Start waiting')
time.sleep(sec)
print('Waited for 3 seconds')
manager.start_worker_thread(
'worker', [(wait, [3]), (wait, [3])], lambda: print('terminated!!!!'))
time.sleep(2)
manager.stop_worker('worker')
manager.threads['worker'].join()
| true |
061161c119dd0bb41de5cedf6c4d8c8195dc41f4 | Python | hllj/drfi-webserver | /measures/custom_roc_curve.py | UTF-8 | 600 | 2.65625 | 3 | [] | no_license | import numpy as np
def custom_roc_curve(y_true, y_pred, thresholds):
fpr = []
tpr = []
for threshold in thresholds:
y_pred_threshold = y_pred.copy()
y_pred_threshold = np.where(y_pred_threshold >= threshold, 1, 0)
fp = np.sum((y_pred_threshold == 1) & (y_true == 0))
tp = np.sum((y_pred_threshold == 1) & (y_true == 1))
fn = np.sum((y_pred_threshold == 0) & (y_true == 1))
tn = np.sum((y_pred_threshold == 0) & (y_true == 0))
fpr.append(fp / (fp + tn))
tpr.append(tp / (tp + fn))
return np.array(fpr), np.array(tpr)
| true |
4abd024eb03b7b4e204d8d72e470c845547a7726 | Python | 180D-FW-2020/Team10 | /piToMac.py | UTF-8 | 5,374 | 2.59375 | 3 | [] | no_license | import sys
import time
import math
import IMU
import datetime
import os
#My import
import RPi.GPIO as GPIO
import socket
RAD_TO_DEG = 57.29578
M_PI = 3.14159265358979323846
#G_GAIN = 0.070 # [deg/s/LSB] If you change the dps for gyro, you need to update this value accordingly
AA = 0.40 # Complementary filter constant
ACC_LPF_FACTOR = 0.4 # Low pass filter constant for accelerometer
ACC_MEDIANTABLESIZE = 9 # Median filter table size for accelerometer. Higher = smoother but a longer delay
MyVar = -1
relVar = 0
Tvar = 0
def button_callback_SD(channel):
#print("Start Drawing")
client.send(str.encode("w"))
def button_callback_RA(channel):
#print("Released Arrow\n\n")
client.send(str.encode("s"))
###############Set up button reads##############################
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) #use physical pin number
GPIO.setup(8, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
#set pin 8 to be an input pin and set inital value to be pulled low (off)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
#set pin 10 to be an input pin and set inital value to be pulled low (off)
GPIO.add_event_detect(8, GPIO.FALLING, callback=button_callback_SD)
#set up event for pin 8, falling edge.
GPIO.add_event_detect(10, GPIO.RISING, callback=button_callback_RA)
oldXAccRawValue = 0
oldYAccRawValue = 0
oldZAccRawValue = 0
a = datetime.datetime.now()
#Setup the tables for the mdeian filter. Fill them all with '1' so we dont get devide by zero error
acc_medianTable1X = [1] * ACC_MEDIANTABLESIZE
acc_medianTable1Y = [1] * ACC_MEDIANTABLESIZE
acc_medianTable1Z = [1] * ACC_MEDIANTABLESIZE
acc_medianTable2X = [1] * ACC_MEDIANTABLESIZE
acc_medianTable2Y = [1] * ACC_MEDIANTABLESIZE
acc_medianTable2Z = [1] * ACC_MEDIANTABLESIZE
###############start IMU################
IMU.detectIMU() #Detect if BerryIMU is connected.
if(IMU.BerryIMUversion == 99):
print(" No BerryIMU found... exiting ")
sys.exit()
IMU.initIMU() #Initialise the accelerometer, gyroscope and compass
################Start communication with the computer###############
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.0.197'
port = 8080
print('waiting for connection')
try:
client.connect((host,port))
except socket.error as e:
print('much sad')
Response = client.recv(1024)
print(Response.decode("utf-8"))
while True:
#Read the accelerometer,gyroscope and magnetometer values
ACCx = IMU.readACCx()
ACCy = IMU.readACCy()
ACCz = IMU.readACCz()
##Calculate loop Period(LP). How long between Gyro Reads
b = datetime.datetime.now() - a
a = datetime.datetime.now()
LP = b.microseconds/(1000000*1.0)
outputString = "Loop Time %5.2f " % ( LP )
###############################################
#### Apply low pass filter ####
###############################################
ACCx = ACCx * ACC_LPF_FACTOR + oldXAccRawValue*(1 - ACC_LPF_FACTOR);
ACCy = ACCy * ACC_LPF_FACTOR + oldYAccRawValue*(1 - ACC_LPF_FACTOR);
ACCz = ACCz * ACC_LPF_FACTOR + oldZAccRawValue*(1 - ACC_LPF_FACTOR);
oldXAccRawValue = ACCx
oldYAccRawValue = ACCy
oldZAccRawValue = ACCz
#########################################
#### Median filter for accelerometer ####
#########################################
# cycle the table
for x in range (ACC_MEDIANTABLESIZE-1,0,-1 ):
acc_medianTable1X[x] = acc_medianTable1X[x-1]
acc_medianTable1Y[x] = acc_medianTable1Y[x-1]
acc_medianTable1Z[x] = acc_medianTable1Z[x-1]
# Insert the lates values
acc_medianTable1X[0] = ACCx
acc_medianTable1Y[0] = ACCy
acc_medianTable1Z[0] = ACCz
# Copy the tables
acc_medianTable2X = acc_medianTable1X[:]
acc_medianTable2Y = acc_medianTable1Y[:]
acc_medianTable2Z = acc_medianTable1Z[:]
# Sort table 2
acc_medianTable2X.sort()
acc_medianTable2Y.sort()
acc_medianTable2Z.sort()
# The middle value is the value we are interested in
ACCx = acc_medianTable2X[int(ACC_MEDIANTABLESIZE/2)];
ACCy = acc_medianTable2Y[int(ACC_MEDIANTABLESIZE/2)];
ACCz = acc_medianTable2Z[int(ACC_MEDIANTABLESIZE/2)];
#Convert Accelerometer values to degrees
AccXangle = (math.atan2(ACCy,ACCz)*RAD_TO_DEG)
AccYangle = (math.atan2(ACCz,ACCx)+M_PI)*RAD_TO_DEG
#Change the rotation value of the accelerometer to -/+ 180 and
#move the Y axis '0' point to up. This makes it easier to read.
if AccYangle > 90:
AccYangle -= 270.0
else:
AccYangle += 90.0
##################### END Tilt Compensation ########################
#ME#
if(MyVar < 5):
MyVar+=1
#print('did made it in')
continue
if(abs(AccYangle)<69):
if(relVar == 0):
time.sleep(1.5)
#print('you reload')
client.send(str.encode("r"))
relVar = 1
continue
if(relVar == 1 and Tvar < 4):
Tvar = Tvar+1
#print('tvar<4')
continue
else:
relVar = 0
Tvar = 0
#print('else statement')
continue
#ME#
#client.send(b'0')
#slow program down a bit, makes the output more readable
time.sleep(0.03)
client.close()
GPIO.cleanup() #cleanup
| true |
88285ce5c4b3015f0e3b1ccf8d26cda491dde3f9 | Python | ashish-bisht/must_do_geeks_for_geeks | /dp/python/super_seq/recursive.py | UTF-8 | 549 | 3.203125 | 3 | [] | no_license | def super_seq(str1, str2):
common_seq = helper(str1, str2, 0, 0)
return len(str1)+len(str2) - common_seq
def helper(str1, str2, index1, index2):
if not str1:
return 0
if not str2:
return 0
if index1 >= len(str1) or index2 >= len(str2):
return 0
if str1[index1] == str2[index2]:
return 1 + helper(str1, str2, index1+1, index2+1)
return max(helper(str1, str2, index1+1, index2), helper(str1, str2, index1, index2+1))
print(super_seq("abcd", "xycd"))
print(super_seq("efgh", "jghi"))
| true |
2b357693ec14be3c5dbace0a2e7be72b50737a39 | Python | CaioBrandz/Binary-Tree-ofImages | /binaryTree-ofImages.py | UTF-8 | 5,302 | 3.796875 | 4 | [] | no_license | from abc import ABC, abstractmethod
import cv2
import glob
class TreeADT(ABC):
@abstractmethod
def insert(self, value):
"""Insere <value> na arvore"""
pass
@abstractmethod
def empty(self):
"""Verifica se a arvore esta vazia"""
pass
@abstractmethod
def root(self):
"""Retorna o no raiz da arvore"""
pass
class Node:
def __init__(self, data=None, parent=None, left=None, right=None):
self._data = data
self._parent = parent
self._left = left
self._right = right
def empty(self):
return not self._data
def __str__(self):
return self._data.__str__()
class BinaryTree(TreeADT):
def __init__(self, data=None):
self._root = Node(data)
def empty(self):
if self._root._data is not None:
return False
else:
return True
def root(self):
return self._root
def insert(self, elem):
node = Node(elem)
if self.empty():
self._root = node
else:
self.__insert_children(self._root, node)
def __insert_children(self, root, node):
r_height = root._data.shape[0] # retorna a altura da imagem presente na raiz
n_height = node._data.shape[0] # retorna a altura da imagem presenta no nó a ser adicionado
if n_height <= r_height: # modificado para a condicional da altura das data
if not root._left:
root._left = node
root._left._parent = root
else:
self.__insert_children(root._left, node)
else:
if not root._right:
root._right = node
root._right._parent = root
else:
self.__insert_children(root._right, node)
def traversal(self, in_order=True, pre_order=False, post_order=False):
result = list()
if in_order:
in_order_list = list()
result.append(self.__in_order(self._root, in_order_list))
else:
result.append(None)
if pre_order:
pre_order_list = list()
result.append(self.__pre_order(self._root, pre_order_list))
else:
result.append(None)
if post_order:
post_order_list = list()
result.append(self.__post_order(self._root, post_order_list))
else:
result.append(None)
return result
def __in_order(self, root, lista):
if not root:
return
self.__in_order(root._left, lista)
lista.append(root._data)
self.__in_order(root._right, lista)
return lista
def __pre_order(self, root, lista):
if not root:
return
lista.append(root._data)
self.__pre_order(root._left, lista)
self.__pre_order(root._right, lista)
return lista
def __post_order(self, root, lista):
if not root:
return
self.__post_order(root._left, lista)
self.__post_order(root._right, lista)
lista.append(root._data)
return lista
def print_binary_tree(self):
if self._root:
print(self.traversal(False, True, False)[1])
if __name__ == '__main__': # apertar a, s ou d para seguir uma das ordens
t = BinaryTree()
lenght =0 # controlar o tanto de imagens, logo o tanto de indices que um array vai ter (no caso, 16)
for file in glob.glob("images/*.png"): #carregando todas as imagens e adicionando a arvore binaria
a= cv2.imread(file)
t.insert(a)
lenght +=1
l = t.traversal(True, True, True)
x = 0 # indice de um dos 3 metodos, seguindo o transversal
y = 0 # indice do array de um dos metodos
while True:
cv2.imshow('aperte a,s ou d continuadamente', l[x][y]) #mostrar a imagem da posicao x,y
key = cv2.waitKeyEx()
if key == 97: # in order na letra a (apertando continuadamente a)
if y < lenght -1 and x == 0: # passar os indices in order
y += 1
elif x != 0: # Se verdadeiro: ao apertar vai para o primeiro elemento da in order
print('--começo da IN order--')
x = 0
y = 0
print(y)
elif key == 115: # pre order na letra s (apertando continuadamente s)
if y < lenght -1 and x == 1: # passar os indices pre order
y += 1
elif x != 1: # Se verdadeiro: ao apertar vai para o primeiro elemento da pre order
print('--começo da PRE order--')
x = 1
y = 0
print(y)
elif key == 100: # POST order na letra d (apertando continuadamente d)
if y < lenght -1 and x == 2: # passar os indices post order
y += 1
elif x != 2: # Se verdadeiro: ao apertar vai para o primeiro elemento da post order
print('--começo da POST order--')
x = 2
y = 0
print(y)
else:
break
| true |
9f3899994e89cd5db50c9b67d16fbe7cc35cf161 | Python | Jadefjg/UnitTestRep | /UnitTest/src/tests/demo/test17_calculator_pytest_mock.py | UTF-8 | 402 | 2.796875 | 3 | [] | no_license | class ForTest:
field = 'origin'
def method(self):
pass
def test_for_test(mocker):
test = ForTest()
# 方法
mock_method = mocker.patch.object(test, 'method')
test.method()
# 检查行为
assert mock_method.called
# 域
assert 'origin' == test.field
mocker.patch.object(test, 'field', 'mocked')
# 检查结果
assert 'mocked' == test.field | true |
d85b415afbda84a1009fa620d08836bad2438a19 | Python | pcmason/Automate-the-Boring-Stuff-in-Python | /Chapter 15 - Working with PDF and Word Documents/bruteForcePdfDecrypter.py | UTF-8 | 3,201 | 4.1875 | 4 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
bruteForcePdfDecrypter.py
Created on Sun Aug 8 23:10:38 2021
@author: paulmason
program that uses the brute-force method to decrypt an encrypted PDF given by the user
program should try both the uppercase and lowercase version of each word and give the password
when/if a word in the txt file successfully decrypts the PDF file
steps:
1. get an encrypted PDF file from the user and create a PdfFileReader object and ensure it is encrypted
2. read in dictionary.txt and loop through all words in it (uppercased) and a copied list in lowercase
if the decrypt() method returns 1 then print the password and end the program
3. else then the encrypted PDF cannot be decrypted with the bruteforce method and the user should be told that
"""
#import PyPDF2 to attempt to decrypt the encrypted file given and sys to exit the program if needed
import PyPDF2, sys
#step 1 - get the encrypted PDF from the user
#create an object to store the PDF in
pdfFile = ''
#prompt user to enter an encrypted pdf
while not pdfFile.endswith('.pdf'):
print('Enter an encrypted PDF file:')
pdfFile = input()
#create a PdfFileReader object from the PDF file given
pdfReader = PyPDF2.PdfFileReader(open(pdfFile, 'rb'))
#ensure the PDF file is encrypted
if not pdfReader.isEncrypted:
#tell the user they entered a PDF that is not encrypted and exit
print('User entered a PDF file that is not decrypted! Program terminating...')
sys.exit()
#step 2 - read in the values from dictionary.txt
#open the file for dictionary.txt
dictFile = open('dictionary.txt', 'r')
#use readlines to make a list for each word in the file
passwordWords = dictFile.readlines()
#output what is happening
print('Creating lowercase words list...')
#now create a lowercased list of passwordsWords
lcPasswordWords = [x.lower() for x in passwordWords]
#while passWords is False loop through both upper and lowercase password lists
while True:
#loop through the lowercase words
for word in lcPasswordWords:
#strip all blank spaces
word = word.strip()
#print what word is being attempted to decrypt
print('Attempting with %s...' % word)
#check if the word decrypts the PDF
if pdfReader.decrypt(word):
#then print out the password
print('Success! The password for %s is %s!' % (pdfFile, word))
#set break out
sys.exit()
#loop through uppercase words
for word in passwordWords:
#strip all blank spaces
word = word.strip()
#print what word is being attempted to decrypt
print('Attempting with %s...' % word)
#check if the password decrypts the PDF
if pdfReader.decrypt(word) == 1:
#if so print out the password
print('Success! The password for %s is %s!' % (pdfFile, word))
#then break out
sys.exit()
#if you have looped through both lists and arrive here, then the password is not in dictionary.txt
print('Unfortunately, dictionary.txt does not hold the password for %s. Program terminating...' % (pdfFile))
sys.exit()
| true |
bc847fc6b6df8323f65798980bd574920215ba07 | Python | allpix-squared/allpix-squared | /etc/scripts/update_copyright_years.py | UTF-8 | 10,559 | 3.03125 | 3 | [
"MIT",
"CC-BY-4.0",
"BSD-3-Clause",
"BSL-1.0"
] | permissive | #!/usr/bin/python3
# SPDX-FileCopyrightText: 2022-2023 CERN and the Allpix Squared authors
# SPDX-License-Identifier: MIT
"""
Update copyright years for files in a git repo. The initial year is taken from git.
"""
import argparse
import logging
import os
import re
import subprocess
import time
DEFAULT_YEARS_PATTERN = r'([12]\d{3})(-[12]\d{3})?'
class MatchPattern:
"""
Class containing functions for year matching and replacing.
Attributes:
match_pattern: Regex pattern for year matching. The first match group contains the substring to be replaced.
replace_pattern: Function that returns the replace pattern for a given year range.
"""
def __init__(self, years: str, appendix: str = None, prependix: str = None) -> None:
self._match_pattern = ''
self._prependix_repl = ''
self._appendix_repl = ''
# only add prependix with space if non-empty
if prependix is not None:
self._prependix_repl = prependix + ' '
self._match_pattern += re.escape(prependix) + ' '
# add top-level match group to year matching pattern
self._match_pattern += rf'({years})'
# only add appendix with space if non-empty
if appendix is not None:
self._appendix_repl = ' ' + appendix
self._match_pattern += ' ' + re.escape(appendix)
@property
def match_pattern(self):
"""
Regex pattern for year matching. The first match group contains the substring to be replaced.
"""
return self._match_pattern
def replace_pattern(self, years: str) -> str:
"""
Returns the replace pattern for a given year range.
Args:
years: String to replace the year range with.
Returns:
String with the replace pattern.
"""
return self._prependix_repl + years + self._appendix_repl
def parse_cmdline_args(args: list[str] = None) -> argparse.Namespace:
"""
Parses the command-line arguments.
Args:
args: Optional list of strings to parse as command-line arguments. If set to None, parse from sys.argv instead.
Returns:
A namespace with the parsed arguments.
"""
parser = argparse.ArgumentParser(description='Update copyright years for files in a git repo.')
parser.add_argument('-v', '--verbose', help='enable verbose output', action='store_true')
parser.add_argument('-a', '--appendix', help='pattern to append to year matching, i.e. <years> <pattern>', action='store', type=str)
parser.add_argument('-p', '--prependix', help='pattern to prepend to year matching, i.e. <pattern> <years>', action='store', type=str)
parser.add_argument('-y', '--years', help='regex pattern to match years', action='store', type=str, default=DEFAULT_YEARS_PATTERN)
parser.add_argument('-x', '--exclude', help='files to exclude', action='extend', nargs='+', type=str, default=list[str]())
parser.add_argument('-f', '--files', help='only run on specified files', action='extend', nargs='+', type=str, default=None)
return parser.parse_args(args=args)
def get_known_file_paths_git() -> list[str]:
"""
Get paths of all files known to git.
Returns:
A list containing strings with the relative paths of the files.
"""
proc = subprocess.run(['git', 'ls-files'], check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
if proc.returncode != 0:
raise Exception(f'git ls-files failed:\n{proc.stderr}')
known_file_paths = proc.stdout.splitlines()
return known_file_paths
def expand_dir_paths(paths: list[str]) -> list[str]:
"""
Expand directories in a list of paths to explicit file paths.
Args:
paths: A list containing strings with paths.
Returns:
A list containing strings with paths that point to files.
"""
file_paths = list[str]()
for path in paths:
if os.path.isdir(path):
for root_dir, _dirs, files in os.walk(path):
file_paths += [os.path.join(root_dir, file) for file in files]
elif os.path.isfile(path):
file_paths.append(path)
return file_paths
def get_file_paths(file_paths: list[str], excluded_paths: list[str]) -> list[str]:
"""
Get list of relaitve file paths from an include and exclude path list. If no included paths are specified, get a file list via git instead.
Args:
included_paths: A list containing strings with paths, can be None.
excluded_paths: A list containing strings with paths.
Returns:
A list containing strings with relative paths.
"""
# lambda to convert list of paths to relative paths
def convert_to_relative_paths(paths: list[str]) -> list[str]:
return [os.path.relpath(path) for path in paths]
# get files from git except if file_paths is not specified
if file_paths is None:
logging.debug('Looking up all files known to git in %s', os.getcwd())
# get files from git (relative paths)
file_paths = get_known_file_paths_git()
else:
logging.debug('Using files specified via the include option')
# ensure relative paths from user input
file_paths = convert_to_relative_paths(file_paths)
# expand dirs in file_paths (e.g. --files src/)
file_paths = expand_dir_paths(file_paths)
# ensure relative paths from user input
excluded_paths = convert_to_relative_paths(excluded_paths)
# lambda to check if to paths share a common prefix
def has_commonprefix(path1: str, path2: str):
return os.path.commonprefix([path1, path2]) != ''
# remove excluded paths
for file_path in file_paths.copy():
for excluded_path in excluded_paths:
if has_commonprefix(file_path, excluded_path):
file_paths.remove(file_path)
continue
return file_paths
def get_current_year() -> str:
"""
Get the current year in UTC (+0, no DST).
Returns:
String containing the current year.
"""
current_year = time.strftime('%Y', time.gmtime())
logging.debug('Setting current year to %s', current_year)
return current_year
def replace_copyright_years(string: str, years: str, matching_opts: MatchPattern) -> tuple[str, str]:
"""
Replace the first copyright year range in a string.
Args:
string: String in which to replace the copyright year range.
years: String to replace the year range with.
matching_opts: MatchingOptions with options for pattern matching.
Returns:
Tuple with two strings, the first is the given string with the replaced year range. The second entry is a string with the replaced year range that got
replaced. If no year range was found, the first string return the given string unchanged and the second entry is none.
"""
match_pattern = matching_opts.match_pattern
replace_pattern = matching_opts.replace_pattern(years)
# first only search for pattern to get replaced years, then replace it
match = re.search(match_pattern, string, flags=re.MULTILINE)
if not match:
return (string, None)
replaced_years = match[1]
replaced_string = re.sub(match_pattern, replace_pattern, string, count=1, flags=re.MULTILINE)
return (replaced_string, replaced_years)
def update_copyright_years(file_path: str, current_year: str, matching_opts: MatchPattern) -> bool:
"""
Update the copyright year range in file from initial year to current year. The initial year is determined via git.
Args:
file_path: String containing the relative path.
current_year: String containing the current year.
matching_opts: MatchingOptions with options for pattern matching.
Returns:
Bool that is true if the copyright year range was changed.
"""
# list all commits on file, including renames, and format to only output the year
git_cmd = ['git', 'log', '--follow', '--format=%ad', '--date=format-local:%Y', file_path]
# ensure dates are given in UTC (+0, no DST)
os.environ['TZ'] = 'UTC0'
proc = subprocess.run(git_cmd, check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
if proc.returncode != 0:
raise Exception(f'git failed to find initial year for {file_path}:\n{proc.stderr}')
if len(proc.stdout) == 0:
logging.debug('git has no initial year information for %s, assuming current year', file_path)
initial_year = current_year
else:
initial_year = proc.stdout.splitlines()[-1]
years = initial_year
if int(current_year) > int(initial_year):
years += f'-{current_year}'
# try to open as text file, skip if not possible
file_content = str()
try:
with open(file_path, mode='rt', encoding='utf-8') as file:
file_content = file.read()
except UnicodeDecodeError:
logging.debug('Skipped %s (not a text file)', file_path)
return False
replaced_file_content, replaced_years = replace_copyright_years(file_content, years, matching_opts)
if replaced_years is None:
logging.debug('Skipped %s (no year range found)', file_path)
return False
with open(file_path, mode='wt', encoding='utf-8') as file:
file.write(replaced_file_content)
logging.debug('Replaced copyright years from %s to %s in %s', replaced_years, years, file_path)
return True
def main(args: list[str] = None) -> None:
"""
Main loop adjusting all files in the current working directory.
Args:
args: Optional list of strings to parse as command-line arguments. If set to None, parse from sys.argv instead.
"""
logging.basicConfig(level=logging.INFO, format='%(message)s')
options = parse_cmdline_args(args=args)
if options.verbose:
logging.getLogger().setLevel(logging.DEBUG)
logging.debug('Running with verbose output')
matching_opts = MatchPattern(options.years, options.appendix, options.prependix)
file_paths = get_file_paths(options.files, options.exclude)
current_year = get_current_year()
logging.info('Looping over %d files, this might take a while', len(file_paths))
counter = 0
for file_path in file_paths:
if update_copyright_years(file_path, current_year, matching_opts):
counter += 1
logging.info('Updated copyright years in %d files', counter)
if __name__ == '__main__':
main()
| true |
a0f2971f3be4712d92ae5c50fca43ea39276e482 | Python | FelipeKatao/DataSciencePython | /Estatistica e probalidade/main.py | UTF-8 | 1,665 | 2.984375 | 3 | [
"MIT"
] | permissive | from random import *
import Vetores as Vt
import Matrizes as Mt
import Graficos as Gf
import Estatistica as est
import Probalidade as prb
import Gradiente as grd
#Variaveis
z = [12,34,56,7,8,2,10,43,21,67,8,9,3,4]
w = [2, 2, 2]
c = ['a', 'c', 'd']
v = ['d', 'b', 's']
zw = [[1, 2, 3], [4, 5, 6]]
ProbalidadeNormal=[]
ProbalidadeFinal=[]
NumRandom = randint(2, max(z))
Gard=grd.gradiente()
print(Gard.passos(z,w,3))
#Importar das Classes
VetorX = Vt.Vetor()
MatrizX= Mt.Matriz()
GraficoX= Gf.Graficos()
EstatiX=est.estatic()
ProbL=prb.prob()
#Criando uma probalidade acima ou abaixo
Media=EstatiX.Media(z)
print("O valor medio é:"+ str(Media))
print("O valor maximo é: "+ str(max(z)))
ProbalidadeFinal.append(ProbL.Aproximacao_dois_dados(NumRandom,max(z),Media))
print("Dado analizado: "+str(NumRandom))
NumRandom = randint(2, max(z))
ProbalidadeFinal.append(ProbL.Aproximacao_dois_dados(NumRandom,max(z),Media))
print("Dado analizado: "+str(NumRandom))
NumRandom = randint(2, max(z))
ProbalidadeFinal.append(ProbL.Aproximacao_dois_dados(NumRandom,max(z),Media))
print("Dado analizado: "+str(NumRandom))
NumRandom = randint(2, max(z))
ProbalidadeFinal.append(ProbL.Aproximacao_dois_dados(NumRandom,max(z),Media))
print("Dado analizado: "+str(NumRandom))
NumRandom = randint(2, max(z))
ProbalidadeFinal.append(ProbL.Aproximacao_dois_dados(NumRandom,max(z),Media))
print("Dado analizado: "+str(NumRandom))
NumRandom = randint(2, max(z))
ProbalidadeFinal.append(ProbL.Aproximacao_dois_dados(NumRandom,max(z),Media))
#Criação do Grafico
print("Pronto")
GraficoX.CriarGraficoBarras(ProbalidadeFinal,"Estatistica")
print("Grafico gerado com sucesso")
| true |
16f6fd3ba8c4c01163aa368f9067ac9dcb826185 | Python | georgynemirovsky/Elina_1sem | /turtle_part1/7.py | UTF-8 | 281 | 3.25 | 3 | [] | no_license | import turtle
import time
import numpy
k = float(input('k'))
n = int(input('number of cycles'))
dphi = 1
phi = 0
m = int(360 / 10)
for j in range (m * n):
dl = k * dphi * numpy.sqrt(1 + phi ** 2)
turtle.forward(dl)
turtle.left(10)
phi = phi + dphi
time.sleep(10)
| true |
9382768efe6bde55e3d9e71805259166ab0a39a0 | Python | superSeanLin/Algorithms-and-Structures | /36_Valid_Sudoku/36_Valid_Sudoku.py | UTF-8 | 705 | 3.125 | 3 | [] | no_license | class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
# naive solution must work; maybe use constraint propagation (AC-3) but should be slow and memory consuming here
seen = set()
for i in range(9):
for j in range(9):
cell = board[i][j]
if cell == '.':
continue
elif (i, cell) in seen or (cell, j) in seen or (i//3, j//3, cell) in seen: # seen value
return False
seen.add((i, cell))
seen.add((cell, j))
seen.add((i//3, j//3, cell))
return True
| true |
483d8e6260d2675467204a40a028899b0e251119 | Python | hamioo66/Test | /classTest/DataBase.py | UTF-8 | 1,113 | 2.859375 | 3 | [] | no_license | # -*- coding: UTF-8 -*-
class Vector:
def __init__(self,a,b):
self.a=a
self.b=b
def __str__(self):
return 'Vector (%d,%d)' %(self.a,self.b)
def __add__(self, other):
return Vector(self.a+other.a,self.b+other.b)
v1=Vector(1,16)
v2=Vector(-22,100)
print v1+v2
import re
print(re.match('www','www.baidu.com').span())
print(re.match('com','www.runoob.com'))
line="Cats are smarter than dogs"
matchObj=re.match(r'(.*) are (.*?).*',line,re.M|re.I)
if matchObj:
print "matchObj.group():",matchObj.group()
print "matchObj.group(1):",matchObj.group(1)
print "matchObj.group(2):",matchObj.group(2)
else:
print "no match!!!"
import MySQLdb
db=MySQLdb.connect("localhost","root","root","hello",charset="utf8")
cursor=db.cursor()
cursor.execute("select version()")
data=cursor.fetchone()
name="zhm"
age=24
address="重庆渝中区万科锦尚"
#sql="""insert into student values("%s","%s","%s")%(name,age,address)"""
try:
cursor.execute('insert into student values("%s","%s","%s")' %(name,age,address))
db.commit()
except:
db.rollback()
db.close()
| true |
c6db40b90735b0a06b4a63bd11e5235d308bc5b3 | Python | adamb70/AdventOfCode2020 | /19/solution_19.py | UTF-8 | 1,091 | 3.25 | 3 | [] | no_license | import regex
from functools import lru_cache
def load_rules(inputfile):
rules = {}
messages = []
with open(inputfile, 'r') as infile:
input_rules, input_messages = infile.read().split('\n\n')
for rule in input_rules.splitlines():
k, v = rule.split(': ')
rules[k] = v.replace('"', '')
for message in input_messages.splitlines():
messages.append(message)
return rules, messages
def count_matches(rules, messages, match='0'):
@lru_cache
def compile_rule(rule):
if not rule.isdigit():
return rule
else:
return f'(?:{"".join(compile_rule(x) for x in rules[rule].split())})'
count = 0
pattern = regex.compile(compile_rule(match))
for message in messages:
if pattern.fullmatch(message):
count += 1
return count
rules, messages = load_rules('input.txt')
# Part 1
print(count_matches(rules, messages, match='0'))
# Part 2
rules['8'] = '42 +'
rules['11'] = '(?<R> 42 (?&R)? 31 )'
print(count_matches(rules, messages, match='0'))
| true |
3742ae557c39dc0c1c03d0dc31ee7e80a7dc6f2e | Python | gevalenz/rut-chile | /rut_chile/rut_chile.py | UTF-8 | 5,433 | 3.609375 | 4 | [
"MIT"
] | permissive | """Module that provides common functionality regarding Chilean RUT
"""
import re
def is_valid_rut(rut: str) -> bool:
"""Determines if a given rut is valid
Arguments:
rut {str} -- Complete rut, including verification digit. It might
contain dots and a dash.
Returns:
bool -- True if rut is valid. False otherwise.
Raises:
ValueError: when input is not valid to be processed.
"""
__raise_error_if_rut_input_format_not_valid(rut)
rut = __clean_rut(rut)
return get_verification_digit(rut[:-1]) == rut[-1]
def get_verification_digit(rut: str) -> str:
"""Calculates the verification digit for a given rut
Arguments:
rut {str} -- Rut containing digits only. No dots nor verification
digit allowed.
Returns:
str -- Verification digit. It might be a digit or 'k'.
Raises:
ValueError: when input is not valid to be processed.
"""
__raise_error_if_input_to_get_verification_digit_not_valid(rut)
partial_sum = __get_partial_sum_for_verification_digit_computation(rut)
return __get_verification_digit_from_partial_sum(partial_sum)
def get_capitalized_verification_digit(rut: str) -> str:
"""Calculates the capitalized verification digit for a given rut
Arguments:
rut {str} -- Rut containing digits only. No dots nor verification
digit allowed.
Returns:
str -- Verification digit. It might be a digit or 'K'.
Raises:
ValueError: when input is not valid to be processed.
"""
return get_verification_digit(rut).upper()
def format_rut_with_dots(rut: str) -> str:
"""Formats RUT, adding dots and dash
Arguments:
rut {str} -- RUT to be formatted
Returns:
str -- Formatted RUT.
Raises:
ValueError: when input is not valid to be processed.
"""
__raise_error_if_rut_input_format_not_valid(rut)
formatted_rut = __clean_rut(rut)
formatted_rut = __add_dash_to_rut(formatted_rut)
base_rut = __add_thousands_separator(formatted_rut[:-2])
return base_rut + formatted_rut[-2:]
def format_capitalized_rut_with_dots(rut: str) -> str:
"""Formats RUT, adding dots, dash and capitalized verification digit
Arguments:
rut {str} -- RUT to be formatted
Returns:
str -- Formatted RUT.
Raises:
ValueError: when input is not valid to be processed.
"""
return format_rut_with_dots(rut).upper()
def format_rut_without_dots(rut: str) -> str:
"""Formats RUT, adding dash
Arguments:
rut {str} -- RUT to be formatted
Returns:
str -- Formatted RUT.
Raises:
ValueError: when input is not valid to be processed.
"""
__raise_error_if_rut_input_format_not_valid(rut)
formatted_rut = __clean_rut(rut)
return __add_dash_to_rut(formatted_rut)
def format_capitalized_rut_without_dots(rut: str) -> str:
"""Formats RUT, adding dash and capitalized verification digit
Arguments:
rut {str} -- RUT to be formatted
Returns:
str -- Formatted RUT.
Raises:
ValueError: when input is not valid to be processed.
"""
return format_rut_without_dots(rut).upper()
def __raise_error_if_rut_input_format_not_valid(rut: str):
if not __is_rut_input_valid(rut):
raise ValueError("invalid input")
def __is_rut_input_valid(rut: str) -> bool:
return rut and __is_well_formatted(rut)
def __is_well_formatted(rut: str) -> bool:
format_regex = r"^((\d{1,3}(\.\d{3})+-)|\d+-?)(\d|k|K)$"
return re.match(format_regex, rut) is not None
def __raise_error_if_input_to_get_verification_digit_not_valid(rut: str):
if not __is_rut_format_valid_to_get_verification_digit(rut):
raise ValueError("invalid input")
def __is_rut_format_valid_to_get_verification_digit(rut: str) -> bool:
format_regex = r"^\d+$"
return rut and re.match(format_regex, rut)
def __get_partial_sum_for_verification_digit_computation(rut: str) -> int:
factors = [2, 3, 4, 5, 6, 7]
partial_sum = 0
factor_position = 0
for digit in reversed(rut):
partial_sum += int(digit) * factors[factor_position]
factor_position = (factor_position + 1) % 6
return partial_sum
def __get_verification_digit_from_partial_sum(partial_sum: int) -> str:
verification_digit = (11 - partial_sum % 11) % 11
return str(verification_digit) if verification_digit < 10 else 'k'
def __clean_rut(rut: str) -> bool:
return rut.replace(".", "").replace("-", "").lower()
def __add_thousands_separator(rut: str) -> str:
if len(rut) < 4:
return rut
digit_groups = __generate_digit_groups(rut)
return ".".join(digit_groups)
def __generate_digit_groups(rut: str) -> []:
digit_groups = __add_most_significant_digits_group(rut) + \
__generate_least_significant_digit_groups(rut)
return digit_groups
def __add_most_significant_digits_group(rut: str) -> []:
digit_group = []
if len(rut) % 3 > 0:
digit_group.append(rut[:len(rut) % 3])
return digit_group
def __generate_least_significant_digit_groups(rut: str) -> []:
digit_groups = []
for i in range(int(len(rut) / 3)):
start = len(rut) % 3 + 3 * i
digit_groups.append(rut[start:start + 3])
return digit_groups
def __add_dash_to_rut(rut: str) -> str:
return '-'.join([rut[:-1], rut[-1]])
| true |
b9816f039f74c921e5c66d3cccdef3d5fb96b51d | Python | vamshiaruru/InformationRetrieval | /Scrapper/downloader.py | UTF-8 | 872 | 3.625 | 4 | [] | no_license | """
This module defines downloader helper function to scrap text from given link.
We use requests module to send requests to the server and BeautifulSoup to
parse the response.
"""
import requests
from bs4 import BeautifulSoup
# from string import printable as ascii_characters
def downloader(link):
"""
This is a helper function to scrap date from the link.
:param link: link to an article that is to be scrapped
:return: None
"""
print link
r = requests.get(link)
soup = BeautifulSoup(r.text)
# printable = set(ascii_characters)
file_name = "{}.txt".format(soup.title.string.encode('utf-8'))
with open(file_name, 'w') as f:
for line in soup.find_all('p')[:-10]:
try:
f.write(line.text.encode('utf-8'))
f.write("\n")
except AttributeError:
pass
| true |
67c9754f235df5762a5cab6cacf15e27f7e751e5 | Python | JunboS/Homework2 | /1c.py | UTF-8 | 925 | 3.765625 | 4 | [
"Apache-2.0"
] | permissive | import matplotlib.pyplot as plt
if __name__ == '__main__':
data_1a = open("1a.csv", "r")
data_1b = open("1b.csv", "r")
x_1a = []
x_1b = []
for row in data_1a:
x_1a.append(int(row))
for row in data_1b:
x_1b.append(int(row))
#print(str(x_1a))
#print(str(x_1b))
# ----line
plt.plot(x_1a, x_1b)
plt.title("Line of Random Numbers")
plt.xlabel("X", size=14)
plt.ylabel("Y", size=14)
plt.savefig('number_line.png')
plt.show()
#----histogram
#bins = square root of 1000 and round up
plt.hist(x_1a,bins=32, alpha = 0.5, label = "0-100")
plt.hist(x_1b,bins=32, alpha = 0.5, label = "3x+6")
plt.legend(loc='upper right')
plt.xlabel("Number", size=14)
plt.ylabel("Count", size=14)
plt.title("Overlapping Histograms of Random Numbers")
plt.savefig('number_histogram.png')
plt.show()
| true |
28b24481c305d14b17937010cd3da6a6f5266c67 | Python | ykosuke0508/multi_class_glad | /Multi_Class_GLAD.py | UTF-8 | 9,416 | 3.125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
入力データの形式について
1. データはcsvファイル形式で与える。
2. headerは順に Name(ワーカ名:0~), Prob_No.(問題番号:0~99), ラベル名...,
3. ラベルはワーカがそのラベルをつけている場合には1, つけていない場合には0を与えている。
"""
import numpy as np
import warnings
import pandas as pd
import sys
from scipy import optimize
# warningは別途処理をしている。
warnings.simplefilter('ignore', RuntimeWarning)
# マルチクラス用のGLAD (Generative model of Labels, Abilities, and Difficulties)
class MultiGLAD:
def __init__(self,n_labels, n_workers, n_tasks, nu = 1.0):
"""
(self.)n_labels : 候補ラベル数
(self.)n_workers : クラウドワーカの数
(self.)n_tasks : タスクの数
self.alpha : クラウドワーカの能力 (初期化は原論文に基づく)
self.beta : タスクの難しさ (初期化は原論文に基づく)
nu : 正則化パラメータ
self.prior_z : zの事前確率, 現状「局所一様事前分布を用いている」
"""
self.n_labels = int(n_labels)
self.n_workers = int(n_workers)
self.n_tasks = int(n_tasks)
self.nu = float(nu)
self.alpha = np.random.normal(1, 1, n_workers)
self.beta = np.exp(np.random.normal(1, 1, n_tasks))
self.prior_z = np.ones(self.n_labels) / self.n_labels
def get_status(self):
"""
基本情報を出力する関数
"""
print(" +-- < data status > --+")
print(" | n_labels : {0:4d} |".format(self.n_labels))
print(" | n_workers : {0:4d} |".format(self.n_workers))
print(" | n_tasks : {0:4d} |".format(self.n_tasks))
print(" +---------------------+")
def get_ability(self):
"""
クラウドワーカの能力を出力する関数
"""
print(" +---- < Ability > ----+")
for (i, a) in enumerate(self.alpha):
print(" | No.{0:3d} : {1:+.6f} |".format(i,a))
print(" +---------------------+")
def get_difficulty(self):
"""
問題の難しさを出力する関数
"""
print(" +--- < Difficulty > ---+")
for (i, b) in enumerate(self.beta):
print(" | No. {0:3d} : {1:+.6f} |".format(i,b))
print(" +----------------------+")
def _mold_data(self, csv_data, expression = False):
"""
行列形式のcsv_dataを入力として与えて、tensor形式のラベルデータを保持する。
tensor形式のラベルデータ:
[クラウドワーカNo., タスクNo., ラベルNo.]でアクセスできる。
得られていない部分はnanとなっている。
csv_data : csvファイルを読み取ってnumpy形式にした行列 (詳細は最上部を参照)
"""
if expression:
print("Molding data")
label_matrix = np.zeros([self.n_workers, self.n_tasks])
label_matrix[:,:] = float("NaN")
for row in csv_data:
label_matrix[row[0],row[1]] = row[2]
if expression:
print("Finished to Mold data")
return label_matrix
# log(sigma(x))
def _log_sigma(self, x):
return - np.maximum(0,-x)+np.log(1+np.exp(-np.abs(x)))
# log((1 / (K - 1)) * (1 - sigma(x)))
def _Ilog_sigma(self, x):
return - np.log(self.n_labels - 1) - np.maximum(0,x)+np.log(1+np.exp(-np.abs(x)))
def _E_step(self):
# 事前確率 : self.prior_z
# 尤度 : likelihood
# 事後確率 : post_z
# alphaのベクトルとbetaのベクトルを掛けて行列を作成。
# [alphaの番号, betaの番号]
x = self.alpha[:, np.newaxis].dot(self.beta[np.newaxis, :])
# あたりの場合
log_sigma = self._log_sigma(x)
# ハズレの場合
Ilog_sigma = self._Ilog_sigma(x)
def compute_likelihood(k):
likelihood = np.where(self.label_matrix == k, log_sigma, Ilog_sigma)
likelihood = np.where(np.isnan(self.label_matrix), 0, likelihood)
return np.exp(likelihood.sum(axis = 0))
post_z = np.array([compute_likelihood(i) * self.prior_z[i] for i in range(self.n_labels)])
Z = post_z.sum(axis = 0)
post_z = (post_z / Z).T
if np.any(np.isnan(post_z)):
sys.exit('Error: Invalid Value [E_step]')
return post_z
def _Q_function(self, x):
# ベクトルの形式で与えられているalphaとbetaを分離する。
new_alpha = x[:self.n_workers]
new_beta = x[self.n_workers:]
Q = (self.post_z * np.log(self.prior_z)).sum()
# xをここから下は全く別のものとして扱う。
# alphaのベクトルとbetaのベクトルを掛けて行列を作成。
# [alphaの番号, betaの番号]
x = new_alpha[:, np.newaxis].dot(new_beta[np.newaxis, :])
# nanの処理を後でしなければならない。
# あたりの場合
log_sigma = self._log_sigma(x)
# ハズレの場合
Ilog_sigma = self._Ilog_sigma(x)
def compute_likelihood(k):
log_likelihood = np.where(self.label_matrix == k, log_sigma, Ilog_sigma)
log_likelihood = np.where(np.isnan(self.label_matrix), 0, log_likelihood)
return log_likelihood
z = np.array([compute_likelihood(i) for i in range(self.n_labels)])
Q += (self.post_z * z.transpose((1,2,0))).sum()
# 正則化ペナルティ
Q -= self.nu * ((new_alpha ** 2).sum() + (new_beta ** 2).sum())
return Q
def _MQ(self,x):
return - self._Q_function(x)
@staticmethod
@np.vectorize
def _sigma(x):
sigmoid_range = 34.538776394910684
if x <= -sigmoid_range:
return 1e-15
if x >= sigmoid_range:
return 1.0 - 1e-15
return 1.0 / (1.0 + np.exp(-x))
@staticmethod
@np.vectorize
def _Isigma(x):
sigmoid_range = 34.538776394910684
if x <= -sigmoid_range:
return 1.0 - 1e-15
if x >= sigmoid_range:
return 1e-15
return 1.0 / (1.0 + np.exp(x))
def _gradient(self, x):
# ベクトルで与えられるalphaとbetaを分ける。
new_alpha = x[:self.n_workers]
new_beta = x[self.n_workers:]
y = new_alpha[:, np.newaxis].dot(new_beta[np.newaxis, :])
sigma = self._sigma(y)
Isigma = self._Isigma(y)
def compute_likelihood(k):
likelihood = np.where(self.label_matrix == k, Isigma, -sigma)
likelihood = np.where(np.isnan(self.label_matrix), 0, likelihood)
return likelihood
z = np.array([compute_likelihood(i) for i in range(self.n_labels)])
dQ_dalpha = (self.post_z * (z * new_beta).transpose((1,2,0))).sum(axis = (1,2)) - self.nu * new_alpha
dQ_dbeta = (self.post_z * (z.transpose((0,2,1)) * new_alpha).transpose((2,1,0))).sum(axis = (0,2)) - self.nu * new_beta
return np.r_[-dQ_dalpha, -dQ_dbeta]
def _M_step(self):
init_params = np.r_[self.alpha, self.beta]
params = optimize.minimize(fun = self._MQ, x0=init_params, method='CG',jac = self._gradient, tol=0.01,options={'maxiter': 25, 'disp': False})
self.alpha = params.x[: self.n_workers]
self.beta = params.x[self.n_workers:]
return -params.fun
def _EM_algo(self, tol, max_iter):
"""
コードの概要
for
E_step
M_step
収束チェック
"""
# 事後確率P(Z|l,alpha,beta)を計算する
self.post_z = self._E_step()
# 更新前のalphaとbetaを保持する。
alpha = self.alpha.copy()
beta = self.beta.copy()
# 最適化の際に便利なようにalphaとbetaを一つの行列に変換
x = np.r_[alpha, beta]
# 現在のQを計算しておく。
now_Q = self._Q_function(x)
# 収束するまで更新を繰り返す。
for i in range(max_iter):
prior_Q = now_Q
now_Q = self._M_step()
self.post_z = self._E_step()
# 収束判定
if np.abs((now_Q - prior_Q) / prior_Q) < tol:
break
return self.post_z
def predict(self, data, tol = 0.0001, max_iter = 1000):
debag = True
"""
tol : 収束判定に用いる値
max_iter : iterationの最大回数
"""
# データの入力
self.label_matrix = self._mold_data(data)
# 本クラスのプロパティであるself.post_Zの値をEMアルゴリズムで更新する。
# EM_algorithm
# イタレーション回数(max_iter)と収束値(tol)を入れる。
self._EM_algo(tol, max_iter)
# 結果出力
return self.post_z
def main():
# n_labels:候補ラベル数
# n_workers:クラウドワーカの数
# n_tasks:タスクの数
# filename:データが入ったファイル
MGLAD = MultiGLAD(n_labels, n_workers, n_tasks)
Bdata = np.array(pd.read_csv(filename))
pred = MGLAD.predict(Bdata)
if __name__ == '__main__':
main()
| true |
2ea37765113319de92d55540c7183419ae9f5f9d | Python | liyi0206/leetcode-python | /14 longest common prefix.py | UTF-8 | 380 | 2.6875 | 3 | [] | no_license | class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ""
res=strs[0]
for string in strs:
for i in range(len(res)):
if i==len(string) or res[i]!=string[i]:
res=res[:i]
break
return res | true |
34f413582b4f01289fc40fda178c731cb5cc0a4f | Python | pedro823/parallel-matrix-mult | /generate_matrices.py | UTF-8 | 963 | 3.28125 | 3 | [] | no_license | #!/bin/env python3
from sys import argv, exit
from random import SystemRandom
random = SystemRandom()
def print_usage(args):
print('Usage:', args[0], 'outfile', '<M>', '<N>')
def print_matrix_to_file(matrix, outfile):
m, n = len(matrix), len(matrix[0])
with open(outfile, 'w') as f:
f.write(str(m) + ' ' + str(n) + '\n')
for i, v in enumerate(matrix):
for j, item in enumerate(v):
f.write(' '.join([str(i), str(j), str(round(item, 3))]) + '\n')
# str_item = ' ' * (idx != 0) + str(round(item, 2))
# f.write(str_item)
# f.write('\n')
def generate_matrix(m, n):
matrix = list()
for i in range(m):
matrix.append(list())
for j in range(n):
matrix[i].append(random.random() * 50)
return matrix
if len(argv) != 4:
print_usage(argv)
exit(0)
print_matrix_to_file(generate_matrix(int(argv[2]), int(argv[3])), argv[1])
| true |
af1bce8207371f224a76f9296c0422135a6a9160 | Python | LoseNine/DataStructureAndAlgorithms | /基本数字运算/5.1024!末尾有几个0.py | UTF-8 | 148 | 3.0625 | 3 | [] | no_license | def zeroCount(n):
count=0
while n>0:
n=n//5
count+=n
return count
if __name__ == '__main__':
print(zeroCount(1024)) | true |
6f4184cc1f390bf7168343819d96e31a51bdaa41 | Python | Aasthaengg/IBMdataset | /Python_codes/p02548/s963217713.py | UTF-8 | 100 | 3.0625 | 3 | [] | no_license | import math
N = int(input())
cnt =0
for a in range(1,N):
cnt += math.floor((N-1)/a)
print(cnt) | true |
83e6411ba913c5a0b3456465e47c1c1e8bf2e93b | Python | liyulun/mantid | /Framework/PythonInterface/test/python/mantid/kernel/StatisticsTest.py | UTF-8 | 4,093 | 2.9375 | 3 | [] | no_license | import unittest
from mantid.kernel import Stats
import math
import numpy
DELTA_PLACES = 10
class StatisticsTest(unittest.TestCase):
def test_getStatistics_with_floats(self):
data = numpy.array([17.2,18.1,16.5,18.3,12.6])
stats = Stats.getStatistics(data)
self.assertAlmostEqual(16.54, stats.mean, places = 10)
self.assertAlmostEqual(2.0733, stats.standard_deviation, places = 4)
self.assertEquals(12.6, stats.minimum)
self.assertEquals(18.3, stats.maximum)
self.assertEquals(17.2, stats.median)
data = numpy.sort(data)
stats = Stats.getStatistics(data, sorted=True)
self.assertAlmostEqual(16.54, stats.mean, places = 10)
self.assertAlmostEqual(2.0733, stats.standard_deviation, places = 4)
self.assertEquals(12.6, stats.minimum)
self.assertEquals(18.3, stats.maximum)
self.assertEquals(17.2, stats.median)
def test_getStatistics_accepts_sorted_arg(self):
data = numpy.array([17.2,18.1,16.5,18.3,12.6])
data = numpy.sort(data)
stats = Stats.getStatistics(data, sorted=True)
self.assertAlmostEqual(16.54, stats.mean, places = 10)
self.assertAlmostEqual(2.0733, stats.standard_deviation, places = 4)
self.assertEquals(12.6, stats.minimum)
self.assertEquals(18.3, stats.maximum)
self.assertEquals(17.2, stats.median)
def test_getZScores(self):
"""Data taken from C++ test"""
values = [12,13,9,18,7,9,14,16,10,12,7,13,14,19,10,16,12,16,19,11]
arr = numpy.array(values,dtype=numpy.float64)
zscore = Stats.getZscore(arr)
self.assertAlmostEqual(1.63977, zscore[4], places = 4)
self.assertAlmostEqual(0.32235, zscore[6], places = 4)
modZ = Stats.getModifiedZscore(arr)
self.assertAlmostEqual(1.23658, modZ[4], places = 4)
self.assertAlmostEqual(0.33725, modZ[6], places = 4)
# Test the sorted argument still works. Remove this when the function is removed
# sorted=True only ever affected the order
zscore = Stats.getZscore(arr, sorted=True)
self.assertAlmostEqual(1.63977, zscore[4], places = 4)
self.assertAlmostEqual(0.32235, zscore[6], places = 4)
def test_getMoments(self):
mean = 5.
sigma = 4.
deltaX = .2
numX = 200
# calculate to have same number of points left and right of function
offsetX = mean - (.5 * deltaX * float(numX))
# variance about origin
expVar = mean*mean+sigma*sigma;
# skew about origin
expSkew = mean*mean*mean+3.*mean*sigma*sigma;
# x-values to try out
indep = numpy.arange(numX, dtype=numpy.float64)
indep = indep*deltaX + offsetX
# y-values
# test different type
depend = numpy.arange(numX, dtype=numpy.int32)
self.assertRaises(ValueError, Stats.getMomentsAboutOrigin, indep, depend)
# now correct y values
weightedDiff = (indep-mean)/sigma
depend = numpy.exp(-0.5*weightedDiff*weightedDiff)/sigma/math.sqrt(2.*math.pi)
aboutOrigin = Stats.getMomentsAboutOrigin(indep, depend)
self.assertTrue(isinstance(aboutOrigin, numpy.ndarray))
self.assertEquals(4, aboutOrigin.shape[0])
self.assertAlmostEqual(1., aboutOrigin[0], places=4)
self.assertAlmostEqual(mean, aboutOrigin[1], places=4)
self.assertTrue(math.fabs(expVar - aboutOrigin[2]) < 0.001*expVar)
self.assertTrue(math.fabs(expSkew - aboutOrigin[3]) < 0.001*expSkew)
aboutMean = Stats.getMomentsAboutMean(indep, depend)
self.assertTrue(isinstance(aboutOrigin, numpy.ndarray))
self.assertEquals(4, aboutOrigin.shape[0])
self.assertAlmostEqual(1., aboutMean[0], places=4)
self.assertAlmostEqual(0., aboutMean[1], places=4)
self.assertTrue(math.fabs(sigma*sigma - aboutMean[2]) < 0.001*expVar)
self.assertTrue(math.fabs(0. - aboutMean[3]) < 0.0001*expSkew)
# end class definition
if __name__ == '__main__':
unittest.main()
| true |
155fc40dcc4172878e8b28c82e05f01c211b585c | Python | oluseyi/propublica-campaign-finance | /presidential.py | UTF-8 | 2,097 | 2.875 | 3 | [] | no_license | from .client import Client
from .utils import CURRENT_CYCLE
class PresidentialClient(Client):
def totals(self, cycle=CURRENT_CYCLE):
path = "{cycle}/president/totals.json".format(cycle=cycle)
return self.fetch(path)
def candidates(self, cycle=CURRENT_CYCLE, candidate_name=None, fec_id=None):
"""
Takes a cycle and candidate last name or FEC ID, returns a presidential candidate in the given cycle.
Use either a candidate's name or an FEC ID, but not both.
Parameter Description
========= ===========
candidate-name The last name of a presidential candidate, in lower case.
fec_id The FEC-assigned 9-character ID of a presidential candidate's main committee.
To find a committee's official FEC ID, use the presidential totals request or
`the FEC web site`_.
"""
path = "{cycle}/president/candidates".format(cycle=cycle)
if candidate_name:
path = path + "/{candidate_name}.json".format(candidate_name=candidate_name)
elif fec_id:
path = path + "/{fec_id}.json".format(fec_id=fec_id)
else:
raise ValueError("Must specify ONE of `candidate_name` or `fec_id`")
return self.fetch(path)
def state_totals(self, state, cycle=CURRENT_CYCLE):
"""
Takes a campaign cycle and a 2-letter state abbreviation, returns total individual itemized
contributions to presidential candidates in the specified state for the specified cycle
"""
path = "{cycle}/president/states/{state}.json".format(cycle=cycle, state=state)
return self.fetch(path)
def zip_totals(self, zip, cycle=CURRENT_CYCLE):
"""
Takes a campaign cycle and a 5-digit ZIP code, returns total individual itemized
contributions to presidential candidates in the specified ZIP code for the specified cycle
"""
path = "{cycle}/president/zips/{zip}.json".format(cycle=cycle, zip=zip)
return self.fetch(path)
| true |
2cc6258d533f437f4f29a0831457b3e1ca657536 | Python | ohmin839/pyplgr | /pyplgr/plgrconv/mapping.py | UTF-8 | 11,811 | 3.046875 | 3 | [
"MIT"
] | permissive | def calc_score(text):
return add_score_dialesis(text,
add_score_breath(text,
add_score_accent(text,
add_score_iota_subscriptum(text))))
def add_score_dialesis(text, score=0):
if '"' in text:
return 4 ** 3 + score
else:
return score
def add_score_breath(text, score=0):
if "<" in text:
return 4 ** 2 * 1 + score
elif ">" in text:
return 4 ** 2 * 2 + score
else:
return score
def add_score_accent(text, score=0):
if "'" in text:
return 4 ** 1 * 1 + score
elif "`" in text:
return 4 ** 1 * 2 + score
elif "~" in text:
return 4 ** 1 * 3 + score
else:
return score
def add_score_iota_subscriptum(text, score=0):
if "|" in text:
return 1 + score
else:
return score
def convert_to_large_alpha(text):
s = calc_score(text)
if s == 1: return "\u1FBC" # A|
if s == 4: return "\u1FBB" # 'A
# if s == 5: return "\uxxxx" # 'A|
if s == 8: return "\u1FBA" # `A
# if s == 9: return "\uxxxx" # `A|
# if s == 12: return "\uxxxx" # ~A
# if s == 13: return "\uxxxx" # ~A|
if s == 16: return "\u1F09" # <A
if s == 17: return "\u1F89" # <A|
if s == 20: return "\u1F0D" # <'A
if s == 21: return "\u1F8D" # <'A|
if s == 24: return "\u1F0B" # <`A
if s == 25: return "\u1F8B" # <`A|
if s == 28: return "\u1F0F" # <~A
if s == 29: return "\u1F8F" # <`A|
if s == 32: return "\u1F08" # >A
if s == 33: return "\u1F88" # >A|
if s == 36: return "\u1F0C" # >'A
if s == 37: return "\u1F8C" # >'A|
if s == 40: return "\u1F0A" # >`A
if s == 41: return "\u1F8A" # >`A|
if s == 44: return "\u1F0E" # >~A
if s == 45: return "\u1F8E" # >~A|
return "\u0391" # A
def convert_to_large_epsilon(text):
s = calc_score(text)
if s == 4: return "\u1FC9" # 'E
if s == 8: return "\u1FC8" # `E
if s == 16: return "\u1F19" # <E
if s == 20: return "\u1F1D" # <'E
if s == 24: return "\u1F1B" # <`E
if s == 32: return "\u1F18" # >E
if s == 36: return "\u1F1C" # >'E
if s == 40: return "\u1F1A" # >`E
return "\u0395" # E
def convert_to_large_eta(text):
s = calc_score(text)
if s == 1: return "\u1FCC" # ^E|
if s == 4: return "\u1FCB" # '^E
# if s == 5: return "\uxxxx" # '^E|
if s == 8: return "\u1FCA" # `^E
# if s == 9: return "\uxxxx" # `^E|
# if s == 12: return "\uxxxx" # ~^E
# if s == 13: return "\uxxxx" # ~^E|
if s == 16: return "\u1F29" # <^E
if s == 17: return "\u1F99" # <^E|
if s == 20: return "\u1F2D" # <'^E
if s == 21: return "\u1F9D" # <'^E|
if s == 24: return "\u1F2B" # <`^E
if s == 25: return "\u1F9B" # <`^E|
if s == 28: return "\u1F2F" # <~^E
if s == 29: return "\u1F9F" # <`^E|
if s == 32: return "\u1F28" # >^E
if s == 33: return "\u1F98" # >^E|
if s == 36: return "\u1F2C" # >'^E
if s == 37: return "\u1F9C" # >'^E|
if s == 40: return "\u1F2A" # >`^E
if s == 41: return "\u1F9A" # >`^E|
if s == 44: return "\u1F2E" # >~^E
if s == 45: return "\u1F9E" # >~^E|
return "\u0397" # ^E
def convert_to_large_iota(text):
s = calc_score(text)
if s == 4: return "\u1FDB" # 'I
if s == 8: return "\u1FDA" # `I
# if s == 12: return "\uxxxx" # ~I
if s == 16: return "\u1F39" # <I
if s == 20: return "\u1F3D" # <'I
if s == 24: return "\u1F3B" # <`I
if s == 28: return "\u1F3F" # <~I
if s == 32: return "\u1F38" # >I
if s == 36: return "\u1F3C" # >'I
if s == 40: return "\u1F3A" # >`I
if s == 44: return "\u1F3E" # >~I
if s == 64: return "\u03AA" # "I
return "\u0399" # I
def convert_to_large_omicron(text):
s = calc_score(text)
if s == 4: return "\u1FF9" # 'O
if s == 8: return "\u1FF8" # `O
if s == 16: return "\u1F49" # <O
if s == 20: return "\u1F4D" # <'O
if s == 24: return "\u1F4B" # <`O
if s == 32: return "\u1F48" # >O
if s == 36: return "\u1F4C" # >'O
if s == 40: return "\u1F4A" # >`O
return "\u039F" # O
def convert_to_large_upsilon(text):
s = calc_score(text)
if s == 4: return "\u1FEB" # 'Y
if s == 8: return "\u1FEA" # `Y
# if s == 12: return "\uxxxx" # ~Y
if s == 16: return "\u1F59" # <Y
if s == 20: return "\u1F5D" # <'Y
if s == 24: return "\u1F5B" # <`Y
if s == 28: return "\u1F5F" # <~Y
if s == 64: return "\u03AB" # "Y
return "\u03A5" # Y
def convert_to_large_omega(text):
s = calc_score(text)
if s == 1: return "\u1FFC" # ^O|
if s == 4: return "\u1FFB" # '^O
# if s == 5: return "\uxxxx" # '^O|
if s == 8: return "\u1FFA" # `^O
# if s == 9: return "\uxxxx" # `^O|
# if s == 12: return "\uxxxx" # ~^O
# if s == 13: return "\uxxxx" # ~^O|
if s == 16: return "\u1F69" # <^O
if s == 17: return "\u1FA9" # <^O|
if s == 20: return "\u1F6D" # <'^O
if s == 21: return "\u1FAD" # <'^O|
if s == 24: return "\u1F6B" # <`^O
if s == 25: return "\u1FAB" # <`^O|
if s == 28: return "\u1F6F" # <~^O
if s == 29: return "\u1FAF" # <`^O|
if s == 32: return "\u1F68" # >^O
if s == 33: return "\u1FA8" # >^O|
if s == 36: return "\u1F6C" # >'^O
if s == 37: return "\u1FAC" # >'^O|
if s == 40: return "\u1F6A" # >`^O
if s == 41: return "\u1FAA" # >`^O|
if s == 44: return "\u1F6E" # >~^O
if s == 45: return "\u1FAE" # >~^O|
return "\u03A9" # ^O
def convert_to_large_kappa(text):
if "h" in text:
return "\u03A7" # large khi
else:
return "\u039A" # large kappa
def convert_to_large_pi(text):
if "h" in text:
return "\u03A6" # large phi
elif "s" in text:
return "\u03A8" # large psi
else:
return "\u03A0" # large pi
def convert_to_large_rho(text):
s = calc_score(text)
if s == 16 : return "\u1FEC"
return "\u03A1"
def convert_to_large_tau(text):
if "h" in text:
return "\u0398" # large theta
else:
return "\u03A4" # large tau
def convert_to_small_alpha(text):
s = calc_score(text)
if s == 1: return "\u1FB3" # a|
if s == 4: return "\u1F71" # 'a
if s == 5: return "\u1FB4" # 'a|
if s == 8: return "\u1F70" # `a
if s == 9: return "\u1FB2" # `a|
if s == 12: return "\u1FB6" # ~a
if s == 13: return "\u1FB7" # ~a|
if s == 16: return "\u1F01" # <a
if s == 17: return "\u1F81" # <a|
if s == 20: return "\u1F05" # <'a
if s == 21: return "\u1F85" # <'a|
if s == 24: return "\u1F03" # <`a
if s == 25: return "\u1F83" # <`a|
if s == 28: return "\u1F07" # <~a
if s == 29: return "\u1F87" # <`a|
if s == 32: return "\u1F00" # >a
if s == 33: return "\u1F80" # >a|
if s == 36: return "\u1F04" # >'a
if s == 37: return "\u1F84" # >'a|
if s == 40: return "\u1F02" # >`a
if s == 41: return "\u1F82" # >`a|
if s == 44: return "\u1F06" # >~a
if s == 45: return "\u1F86" # >~a|
return "\u03B1"; # a
def convert_to_small_epsilon(text):
s = calc_score(text)
if s == 4: return "\u1F73" # 'e
if s == 8: return "\u1F72" # `e
if s == 16: return "\u1F11" # <e
if s == 20: return "\u1F15" # <'e
if s == 24: return "\u1F13" # <`e
if s == 32: return "\u1F10" # >e
if s == 36: return "\u1F14" # >'e
if s == 40: return "\u1F12" # >`e
return "\u03B5" # e
def convert_to_small_eta(text):
s = calc_score(text)
if s == 1: return "\u1FC3" # ^e|
if s == 4: return "\u1F75" # '^e
if s == 5: return "\u1FC4" # '^e|
if s == 8: return "\u1F74" # `^e
if s == 9: return "\u1FC2" # `^e|
if s == 12: return "\u1FC6" # ~^e
if s == 13: return "\u1FC7" # ~^e|
if s == 16: return "\u1F21" # <^e
if s == 17: return "\u1F91" # <^e|
if s == 20: return "\u1F25" # <'^e
if s == 21: return "\u1F95" # <'^e|
if s == 24: return "\u1F23" # <`^e
if s == 25: return "\u1F93" # <`^e|
if s == 28: return "\u1F27" # <~^e
if s == 29: return "\u1F97" # <`^e|
if s == 32: return "\u1F20" # >^e
if s == 33: return "\u1F90" # >^e|
if s == 36: return "\u1F24" # >'^e
if s == 37: return "\u1F94" # >'^e|
if s == 40: return "\u1F22" # >`^e
if s == 41: return "\u1F92" # >`^e|
if s == 44: return "\u1F26" # >~^e
if s == 45: return "\u1F96" # >~^e|
return "\u03B7" # ^e
def convert_to_small_iota(text):
s = calc_score(text)
if s == 4: return "\u1F77" # 'i
if s == 8: return "\u1F76" # `i
if s == 12: return "\u1FD6" # ~i
if s == 16: return "\u1F31" # <i
if s == 20: return "\u1F35" # <'i
if s == 24: return "\u1F33" # <`i
if s == 28: return "\u1F37" # <~i
if s == 32: return "\u1F30" # >i
if s == 36: return "\u1F34" # >'i
if s == 40: return "\u1F32" # >`i
if s == 44: return "\u1F36" # >~i
if s == 64: return "\u03CA" # "i
if s == 68: return "\u1FD3" # "'i
if s == 72: return "\u1FD2" # "`i
if s == 76: return "\u1FD7" # "~i
return "\u03B9" # i
def convert_to_small_omicron(text):
s = calc_score(text)
if s == 4: return "\u1F79" # 'o
if s == 8: return "\u1F78" # `o
if s == 16: return "\u1F41" # <o
if s == 20: return "\u1F45" # <'o
if s == 24: return "\u1F43" # <`o
if s == 32: return "\u1F40" # >o
if s == 36: return "\u1F44" # >'o
if s == 40: return "\u1F42" # >`o
return "\u03BF" # o
def convert_to_small_upsilon(text):
s = calc_score(text)
if s == 4: return "\u1F7B" # 'y
if s == 8: return "\u1F7A" # `y
if s == 12: return "\u1FE6" # ~y
if s == 16: return "\u1F51" # <y
if s == 20: return "\u1F55" # <'y
if s == 24: return "\u1F53" # <`y
if s == 28: return "\u1F57" # <~y
if s == 32: return "\u1F50" # >y
if s == 36: return "\u1F54" # >'y
if s == 40: return "\u1F52" # >`y
if s == 44: return "\u1F56" # >~y
if s == 64: return "\u03CB" # "y
if s == 68: return "\u1FE3" # "'y
if s == 72: return "\u1FE2" # "`y
if s == 76: return "\u1FE7" # "~y
return "\u03C5"# y
def convert_to_small_omega(text):
s = calc_score(text)
if s == 1: return "\u1FF3" # ^o|
if s == 4: return "\u1F7D" # '^o
if s == 5: return "\u1FF4" # '^o|
if s == 8: return "\u1F7C" # `^o
if s == 9: return "\u1FF2" # `^o|
if s == 12: return "\u1FF6" # ~^o
if s == 13: return "\u1FF7" # ~^o|
if s == 16: return "\u1F61" # <^o
if s == 17: return "\u1FA1" # <^o|
if s == 20: return "\u1F65" # <'^o
if s == 21: return "\u1FA5" # <'^o|
if s == 24: return "\u1F63" # <`^o
if s == 25: return "\u1FA3" # <`^o|
if s == 28: return "\u1F67" # <~^o
if s == 29: return "\u1FA7" # <`^o|
if s == 32: return "\u1F60" # >^o
if s == 33: return "\u1FA0" # >^o|
if s == 36: return "\u1F64" # >'^o
if s == 37: return "\u1FA4" # >'^o|
if s == 40: return "\u1F62" # >`^o
if s == 41: return "\u1FA2" # >`^o|
if s == 44: return "\u1F66" # >~^o
if s == 45: return "\u1FA6" # >~^o|
return "\u03C9"; # ^o
def convert_to_small_kappa(text):
if "h" in text:
return "\u03C7" # small khi
else:
return "\u03BA" # small kappa
def convert_to_small_pi(text):
if "h" in text:
return "\u03C6" # small phi
elif "s" in text:
return "\u03C8" # small psi
else:
return "\u03C0" # small pi
def convert_to_small_rho(text):
s = calc_score(text)
if s == 16 : return "\u1FE5"
if s == 32 : return "\u1FE4"
return "\u03C1"
def convert_to_small_sigma(text):
if "s" == text:
return "\u03C2" # final sigma
else:
return "\u03C3" # non-final sigma
def convert_to_small_tau(text):
if "h" in text:
return "\u03B8" # small khi
else:
return "\u03C4" # small kappa
| true |
1cc7a6b7a096212d63ef2728391a0db466710709 | Python | avicfei/avic | /GetHeight.py | UTF-8 | 1,637 | 2.6875 | 3 | [] | no_license | import numpy as np
import cv2 as cv
def height_building(img, im_orig):
img2 = np.copy(im_orig)
center = int(img.shape[1]/2)
minY = 0
maxY = 0
continua = True
try:
for x in range(0, img.shape[0]):
if(img[x, center][0] > 0 and continua):
minY = x
continua = False
if(img[x, center][0] > 0 and x >= maxY):
maxY = x
except:
for x in range(0, img.shape[0]):
if(img[x, center] > 0 and continua):
minY = x
continua = False
if(img[x, center] > 0 and x >= maxY):
maxY = x
img2 = cv.cvtColor(img2, cv.COLOR_GRAY2BGR)
cv.line(img2, (center, maxY), (center, minY), (0,0,255), 3, cv.LINE_4)
hgt = abs(minY - maxY)
return [img2, hgt]
# '_MASC.png'
def get_height(name_base):
ant = 0
arr_h = []
arr_url = []
url_1 = name_base
w = True
i = 1
while(w):
url = ''
url = '_base\\' + str(i) + url_1
im1 = cv.imread(url)
try:
if(im1.size > 0):
arr_url.append(url)
i += 1
else:
w = False
except:
break
for y in range(0, len(arr_url)):
im1 = cv.imread(arr_url[y])
im2 = np.copy(im1)
im1 = cv.cvtColor(im1, cv.COLOR_BGR2GRAY)
im2 = cv.cvtColor(im2, cv.COLOR_BGR2GRAY)
[im, a] = height_building(im1, im2)
cv.imwrite('_result/' + str(y) + url_1, im)
print('Height in ' + str(arr_url[y]) + ': ' + str(a))
| true |
b5de17e96b5680240971d721b23b4551a4d532d1 | Python | Stuey61296/Tower-Of-Hanoi | /Python/Tower.py | UTF-8 | 3,185 | 3.21875 | 3 | [] | no_license | from colorama import Fore
from colorama import Style
from TowerPole import TowerPole
class Tower:
def __init__(self, pole_count, node_count):
possible_names = list('ABCDEF')
self.pole_count = pole_count
self.node_count = node_count
self.move_count = 0
self.pole_names = possible_names[0:pole_count]
empty = False
self.poles = list()
self.poles.append(TowerPole(node_count, empty, self.pole_names[0]))
empty = True
for i in range(1, pole_count):
self.poles.append(TowerPole(node_count, empty, self.pole_names[i]))
def print_tower(self):
print("________________________________________________________________________________\n\n")
temp_list = list()
for pole in self.poles:
temp_list.append(pole.get_node_list())
temp_list = list(map(tuple, zip(*temp_list)))
output = ""
for nodes in temp_list:
output += "\t"
for i in range(0, self.pole_count):
if nodes[i] == -1:
output += "|"
else:
output += str(nodes[i])
output += "\t\t"
output += "\n"
output += "\t"
for i in range(0, self.pole_count):
output += "_\t\t"
output += "\n\t"
for pole in self.poles:
output += pole.get_pole_name() + "\t\t"
output += "\n"
print(output)
def play_game(self):
while not self.game_finished():
pole_move_from = None
pole_move_to = None
while pole_move_from not in self.pole_names:
pole_move_from = input("Which pole would you like to move the top disk from (A - " +
self.poles[-1].get_pole_name() + ")? ").upper()
if pole_move_from not in self.pole_names:
print(f"{Fore.RED}Invalid Pole ({pole_move_from}) Selected!\n{Style.RESET_ALL}")
while pole_move_to not in self.pole_names:
pole_move_to = input("Which pole would you like to move the top disk to (A - " +
self.poles[-1].get_pole_name() + ")? ").upper()
if pole_move_to not in self.pole_names:
print(f"{Fore.RED}Invalid Pole ({pole_move_to}) Selected!\n{Style.RESET_ALL}")
if not self.poles[self.pole_names.index(pole_move_from.upper())].reallocate_pole(
self.poles[self.pole_names.index(pole_move_to.upper())]):
print(f"{Fore.RED}Invalid move!\n{Style.RESET_ALL}")
self.print_tower()
continue
self.move_count += 1
print("")
self.print_tower()
print("________________________________________________________________________________\n\t\t\t\t"
"Congratulations! Game completed in " +
str(self.move_count) +
" moves.\n________________________________________________________________________________")
def game_finished(self):
return self.poles[-1].check_pole_values()
| true |
5d51abd2d2790a7cef0e03fee7d3d5db8139bd9b | Python | fossabot/IdeaBag2-Solutions | /Text/Morse Code Maker/tests.py | UTF-8 | 450 | 2.78125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
import unittest
from morse_code_maker import convert_from_morse_code, convert_to_morse_code
class Test(unittest.TestCase):
def test_convert_to_morse_code(self):
self.assertEqual(convert_to_morse_code("hello"), ".... . .-.. .-.. ---")
def test_convert_from_morse_code(self):
self.assertEqual(convert_from_morse_code(".... . .-.. .-.. ---"), "hello")
if __name__ == "__main__":
unittest.main()
| true |
d837b3e1748c4b80b76225ddcd66205b5a049a1b | Python | JessicaDeLuca/HelloWorld | /L1-10.py | UTF-8 | 11,747 | 4.15625 | 4 | [] | no_license | # Learn Python The Hard Way
# http://learnpythonthehardway.org/book/
# iTerm for terminal
# iPython
# Atom as IDE (integrated developent environment) / Text Editor
# GitHub, keep remote cooy of your git repository
# Exercise 1
print "Begin Exercise 1" + "\n"
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.' + "\n"
# Hello World!
# Hello Again
# I like typing this.
# This is fun.
# Yay! Printing.
# I'd much rather you 'not'.
# I "said" do not touch this.
# Exercise 3
print "Begin Exercise 3"+"\n"
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print 25 * 3 % 4
print 25 * 3
print 75 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2, "\n"
# I will now count my chickens:
# Hens 30
# Roosters 97
# 3
# 75
# 3
# Now I will count the eggs:
# 7
# Is it true that 3 + 2 < 5 - 7?
# False
# What is 3 + 2? 5
# What is 5 - 7? -2
# Oh, that's why it's False.
# How about some more.
# Is it greater? True
# Is it greater or equal? True
# Is it less or equal? False
# Exercise 4
print "Begin Exercise 4" + "\n"
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
# There are 100 cars available.
# There are only 30 drivers available.
# There will be 70 empty cars today.
# We can transport 120.0 people today.
# We have 90 to carpool today.
# We need to put about 3 in each car.
print "Hey %s there." % "you" + "\n"
# Hey you there.
# What do you mean by "read the file backward"?
# Very simple. Imagine you have a file with 16 lines of code in it. Start at line 16,
# and compare it to my file at line 16. Then do it again for 15,
# and so on until you've read the whole file backward.
# Exercise 5
print "Begin Exercise 5" + "\n"
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
print "%s is really fat. He weighs %d pounds." % (my_name, my_weight)
# Let's talk about Zed A. Shaw.
# He's 74 inches tall.
# He's 180 pounds heavy.
# Actually that's not too heavy.
# He's got Blue eyes and Brown hair.
# His teeth are usually White depending on the coffee.
# Zed A. Shaw is really fat. He weighs 180 pounds.
# If I add 35, 74, and 180 I get 289.
# Format specifiers: %s for string, %d for decimal, %r for debugging
# What are formatters?
# They tell Python to take the variable on the right and put it in to replace the %s with its value.
# I don't get it, what is a "formatter"? Huh? The problem with teaching you programming is that
# to understand many of my descriptions you need to know how to do programming already.
# The way I solve this is I make you do something, and then I explain it later.
# When you run into these kinds of questions, write them down and see if I explain it later.
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (
my_age, my_height, my_weight, my_age + my_height + my_weight) + "\n"
# Begin Exercise 6
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
# There are 10 types of people.
# Those who know binary and those who don't.
print "I said: %r." % x
# I said: 'There are 10 types of people.'.
# Notice the stylistic choice of using single quotes and then the double quotes
# for a string with a string noted below
print "I also said: '%s'." % y
# I also said: 'Those who know binary and those who don't.'.
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
# Isn't that joke so funny?! False
w = "This is the left side of..."
e = "a string with a right side."
# This is the left side of...a string with a right side.
print w + e + "\n"
# What is the difference between %r and %s?
# Use the %r for debugging, since it displays the "raw" data of the variable,
# but the others are used for displaying to users.
# What's the point of %s and %d when you can just use %r?
# The %r is best for debugging, and the other formats are for actually displaying variables to users.
# Begin Exercise 7
print "Begin Exercise 7" "\n"
# print a string
print "Mary had a little lamb."
# print a string with a format specifer for string 'snow'
print "Its fleece was white as %s." % 'snow'
# print a string with a format specifer for string 'black'
print "What about the %s sheep?" % 'black'
# Mistake: I forgot to have black in quotes, threw an error
print "And everywhere that Mary went."
print "." * 10 # what'd that do?
print "F$#@" * 4, "it"
# Mistake: Without the comma it returns the whole line as a string, need comma not () to isolate
#Create a string with format specifiers for multiple string and decimal values as well as a variable
selling = "What if we sold"
print "%s the %s sheep for $%d and the %s sheep for $%d?" % (selling, 'black', 10, 'white', 5)
# Mary had a little lamb.
# Its fleece was white as snow.
# What about the black sheep?
# ..........
# F$#@F$#@F$#@F$#@ it
# What if we sold the black sheep for $10 and the white sheep for $5?
paradise = "Paradise"
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. try removing it to see what happens
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12
print "in %s" % paradise +"\n"
# Without the comma after end6 a new line is automatically created,
# The comma acts as a space between both print lines when it returns values
# It's bad form to go over 80 characters per line (ie- this line to the right ->)
# Exercise 8
print "Exercise 8" "\n"
formatter = "%r %r %r %r"
print formatter % (1,2,3,4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight.") +"\n"
# Mistake: I forgot the commas for the last 4 sentences
# Mistake: The last 4 sentences >80 characters so I had to put on new lines
# Note: Used double quotes in lieu of single quoates due to conjunction: didn't
# Note: Only string values need quotes
# 1 2 3 4
# 'one' 'two' 'three' 'four'
# True False False True
# '%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'
# 'I had this thing.' 'That you could type up right.'
# "But it didn't sing." 'So I said goodnight.'
# Exercise 9
print "Exercies 9" +"\n"
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
# Note: "\n" adds a new line
print "Here are the days:", days
print "Here are the months:", months
print "Test"
print """There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6."""
print "Test"
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
#Below code will only print the top line (ie - limiation of "" single line)
print "There's something going on here.",
"With the three double-quotes.",
"We'll be able to type as much as we like.",
"Even 4 lines if we want, or 5, or 6."
# Triple quotes on their own lines at beginning and end will add new lines
# Note: You can use ' or " or """ to wrap around strings
# They can use ' or " quotation marks (eg 'foo' "bar").
# The main limitation with these is that they don't wrap across multiple lines.
# That's what multiline-strings are for: These are strings surrounded by
# triple single or double quotes (''' or """) and are terminated only when
# a matching unescaped terminator is found. They can go on for as many
# lines as needed, and include all intervening whitespace.
# Here are the days: Mon Tue Wed Thu Fri Sat Sun
# Here are the months: Jan
# Feb
# Mar
# Apr
# May
# Jun
# Jul
# Aug
#
# There's something going on here.
# With the three double-quotes.
# We'll be able to type as much as we like.
# Even 4 lines if we want, or 5, or 6.
# Exercise 10
print "Exercise 10" +"\n"
# Sometimes you need to escape the ' or " within a string (use /)
print "I am 6'2\" tall." # escape double-quote inside string
print 'I am 6\'2" tall.' # escape single-quote inside string
# Tab a line in
tabby_cat = "\tI'm tabbed in."
# Add a new line mid string
persian_cat = "I'm split\non a line."
# Add a single backslash within a string 2 methods
backslash_cat = "I'm \\ a \\ cat."
backslash_cat2 = "I'm \ a \ cat."
# Make a formatted list 2 methods
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
fat_cat2 = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip
\t* Grass
"""
# Note: New line automatically created in output when formatted such here
print tabby_cat
print persian_cat
print backslash_cat
print backslash_cat2
print fat_cat
print fat_cat2
# Escape sequence list reference (notice the '\' preface)
# http://learnpythonthehardway.org/book/ex10.html
# \\ Backslash (\)
# \' Single-quote (')
# \" Double-quote (")
# \a ASCII bell (BEL)
# \b ASCII backspace (BS)
# \f ASCII formfeed (FF)
# \n ASCII linefeed (LF)
# \N{name} Character named name in the Unicode database (Unicode only)
# \r Carriage Return (CR)
# \t Horizontal Tab (TAB)
# \uxxxx Character with 16-bit hex value xxxx (Unicode only)
# \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)
# \v ASCII vertical tab (VT)
# \ooo Character with octal value ooo
# \xhh Character with hex value hh
print 'A "smart" man named %s with an IQ of %d.' % ("Steven", 140)
print 'A /"smart/" man named %r with an IQ of %r.' % ("Steven", 140)
# Sometimes you need to escape the ' or " within a string (use /)
print "I am 6'2\" %s with long %s." % ("tall", "arms")
print "I am 6'2\" %r with long %r." % ("tall", "arms")
print 'I am %d\'%d" tall with %d" long %s.' % (6,2,36, "arms")
print 'I am %r\'%r" tall with %d" long %s.' % (6,2,36,"arms")
print "I am 6'2\""
# print "I am 6'2""
# The above throws and error without the escape sequence
print "\n" "End Of Exercise Block 1-10"+ "\n"
| true |
2bfb2e2ceda8b5de37b081ec411dcfc228d0830a | Python | KrammyGod/AirplaneDefense | /main.py | UTF-8 | 25,326 | 3.109375 | 3 | [
"CC0-1.0"
] | permissive | '''
By: Mark Xue
Date: May 3, 2019
Description: This program is a tower defense game.
AIRPLANE DEFENSE V2.0.0
------------------------------------------------------------------------------
This is a tower defense inspired game:
The goal of the game is to survive as many waves of airplanes as possible,
with each wave having increasing speed, and reach the highest score possible.
How to play this game:
Controls:
W, S, Q, and mouse control
Pressing down W moves your player up and S moves it down.
Use your mouse to move the cursor and left click to shoot down the airplanes
trying to reach the left side (your tower).
Press Q anytime during the game to pause the game.
Left click anywhere or press Q again to unpause.
If the planes hit your tank they will also die
If the planes reach your tower, they will blow up and you will lose a life.
You have a total of 20 lives.
Scoring:
10 points will be awarded for every hit with the missile
5 points if you kill them with your tank
No points will be rewarded if they blow up when hitting the tower.
'''
# I - Import and Initialize
import pygame
import gameSprites
import random
import os
pygame.init()
#Center screen
os.environ['SDL_VIDEO_CENTERED'] = '1'
def instructionsScreen(crosshair, screen):
'''
This function is used to display the instructions picture to teach the user
how to play the game.
'''
controls = pygame.image.load('images/instructions.png')
group = pygame.sprite.Group(crosshair)
keepGoing = True
pygame.mouse.set_visible(False)
while keepGoing:
xy_position = pygame.mouse.get_pos()
crosshair.set_position(xy_position)
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
# Exit when user left clicks
if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]:
keepGoing = False
screen.blit(controls, (0, 0))
group.draw(screen)
pygame.display.flip()
def pauseScreen(crosshair, screen, background):
'''
This function is used to pause the game
'''
click = gameSprites.Label("left click anywhere to continue", 30, center=(screen.get_width()/2, 20))
# Change into picture and fade in+out
pause = pygame.image.load('images/pause.png').convert()
group = pygame.sprite.OrderedUpdates(click, crosshair)
keepGoing = True
screen.blit(background, (0, 0))
alpha = 255
add = -5
# Assign key variables
clock = pygame.time.Clock()
while keepGoing:
# 30 frames loaded per second
clock.tick(30)
xy_position = pygame.mouse.get_pos()
crosshair.set_position(xy_position)
for event in pygame.event.get():
if event.type == pygame.QUIT:
click.kill()
keepGoing = False
# Exit when user left clicks
if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]:
click.kill()
keepGoing = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
click.kill()
keepGoing = False
pause.set_alpha(alpha)
alpha += add
if alpha <= 0:
add = 5
elif alpha >= 255:
add = -5
screen.blit(background, (0, 0))
screen.blit(pause, (8, screen.get_height()//2-39))
group.draw(screen)
pygame.display.flip()
def startMenu():
'''
This function is the start menu of the game.
'''
# Display
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Airplane Defense')
# Entities
background = pygame.image.load('images/background.png').convert()
# Save rect attributes to check for mouse on buttons collision
startButton = pygame.draw.rect(background, (0, 255, 255), (349, 165, 105, 25), 1)
hacksToggle = pygame.draw.rect(background, (0, 255, 255), (349, 265, 200, 25), 1)
controlsButton = pygame.draw.rect(background, (0, 255, 255), (349, 215, 180, 25), 1)
screen.blit(background, (0, 0))
pygame.mixer.music.load('sounds/musicEarth.mp3')
pygame.mixer.music.set_volume(0.3)
pygame.mixer.music.play(-1)
'''
For all the correct comments, these are just copy and pasted code from
the game function.
'''
# Load same things for training grounds before game starts
leftEndzone = gameSprites.EndZone(screen, -screen.get_width(), 0, False)
rightEndzone = gameSprites.EndZone(screen, screen.get_width(), 0, False)
topEndzone = gameSprites.EndZone(screen, 0, 0, True)
bottomEndzone = gameSprites.EndZone(screen, 0, screen.get_height(), True)
scoreKeeper = gameSprites.ScoreKeeper(screen)
player = gameSprites.Player(screen)
missile = gameSprites.Projectile(screen, (-30, 10))
crosshair = gameSprites.Crosshair()
# Preload explosion effects so it doesn't lag when actual explosion comes
explosionTemp = gameSprites.Explosion((0, 0), 0)
del explosionTemp
explosionTemp = gameSprites.Explosion((0, 0), 1)
del explosionTemp
missileSprites = pygame.sprite.Group()
endzoneSprites = pygame.sprite.Group(leftEndzone, rightEndzone, topEndzone,\
bottomEndzone)
# Start button and border definitions
start = gameSprites.Label('start', 30, left=350, top=150)
startBorderx = range(startButton.left, startButton.right + 1)
startBordery = range(startButton.top, startButton.bottom + 1)
# Control instruction button and border definitions
controls = gameSprites.Label('controls', 30, left=350, top=200)
controlsBorderx = range(controlsButton.left, controlsButton.right + 1)
controlsBordery = range(controlsButton.top, controlsButton.bottom + 1)
# Hack toggle and border definitions
hack = gameSprites.Label('Hacks: off', 30, left=350, top=250)
hackBorderx = range(hacksToggle.left, hacksToggle.right + 1)
hackBordery = range(hacksToggle.top, hacksToggle.bottom + 1)
title = gameSprites.Label('List of highscores:', 30, left=120, top=70)
# Check highscore file for list of highscores
y_pos = 100
highscores = []
try:
file = open('highscores.txt', 'r')
# pygame.font.render does not aceept \n so it must be done manually.
for line in file:
highscores.append(gameSprites.Label(line.strip(), 30, left=120, top=y_pos))
y_pos += 30
if y_pos == 370:
break
file.close()
except FileNotFoundError:
highscores = gameSprites.Label('You deleted highscores.txt :(', 20, left=120, top=100)
allSprites = pygame.sprite.OrderedUpdates(highscores, start, title, hack,\
controls, player, crosshair,\
scoreKeeper)
# ACTION
# Assign key variables
clock = pygame.time.Clock()
# Hacks is computer playing the game.
hacks = False
moved = False
keepGoing = True
reload = 15
pygame.mouse.set_visible(False)
xy_position = pygame.mouse.get_pos()
# Loop
while keepGoing:
# Time
clock.tick(30)
# Event Handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False, hacks
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed() == (1, 0, 0):
# Check if player clicks start
if xy_position[0] in startBorderx and xy_position[1] in startBordery:
return True, hacks
# Check if player clicks instructions button
if xy_position[0] in controlsBorderx and xy_position[1] in controlsBordery:
instructionsScreen(crosshair, screen)
screen.blit(background, (0, 0))
break
# Check if player toggles hacks
if xy_position[0] in hackBorderx and xy_position[1] in hackBordery:
if hacks:
hack.change_text('Hacks: off')
pygame.mixer.music.set_volume(0.3)
hacks = False
else:
hack.change_text('Hacks: on')
pygame.mixer.music.set_volume(0)
hacks = True
# Player movement
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
player.move(-10)
if keys[pygame.K_s]:
player.move(10)
xy_position = pygame.mouse.get_pos()
crosshair.set_position(xy_position)
# Shoot a missile
if pygame.mouse.get_pressed()[0] and not moved:
player.shoot()
missile = gameSprites.Projectile(screen, player.rect.center)
missile.set_speed(xy_position)
missile.rotate(xy_position)
allSprites.add(missile)
missileSprites.add(missile)
moved = True
# Check for collision of missile with endzone
collision = pygame.sprite.groupcollide(missileSprites, endzoneSprites, True, False)
if collision:
missile = list(collision)[0]
explosion = gameSprites.Explosion(missile.rect.center, 0)
allSprites.add(explosion)
missile.kill()
# Set up reload speed
if moved:
reload -= 1
if reload == 0:
moved = False
player.reload()
reload = 15
player.rotate(xy_position)
# Refresh display
allSprites.clear(screen, background)
allSprites.update()
allSprites.draw(screen)
pygame.display.flip()
def gameOver(scoreKeeper):
'''
This function is the endgame screen.
'''
# Display
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Airplane Defense")
# Entities
background = pygame.image.load('images/background.png').convert()
# Save rect attributes to check for collision with mouse on button
button = pygame.draw.rect(background, (0, 255, 255), (220, 395, 160, 25), 1)
screen.blit(background, (0, 0))
crosshair = gameSprites.Crosshair()
highscores = []
try:
file = open('highscores.txt', 'r')
for line in file:
# Slice the position so it only contains the score and append it to
# highscores list
highscores.append(int(line[3:]))
highscores.append(scoreKeeper.score)
# Create a new list that orders the new highscores.
newHighscores = []
for i in range(len(highscores)):
high = max(highscores)
newHighscores.append(high)
highscores.remove(high)
file.close()
# Overwrite to make new highscores.
file = open('highscores.txt', 'w')
placement = 1
for highscore in newHighscores:
file.write(f'{placement}. {highscore}\n')
placement += 1
if placement == 10:
break
except FileNotFoundError:
# Create new highscores.txt file if it doesn't exsist.
file = open('highscores.txt', 'w')
file.write(f'1. {scoreKeeper.score}\n')
for i in range(2, 10):
file.write(f'{i}. 0\n')
file.close()
labelBorderx = range(button.left, button.right + 1)
labelBordery = range(button.top, button.bottom + 1)
label1 = gameSprites.Label('game over!', 90, center=(screen.get_width()/2, 160))
label2 = gameSprites.Label('your score has been recorded', 30, left=25, top=220)
label3 = gameSprites.Label('continue', 30, left=220, top=380)
label4 = gameSprites.Label(f'Score: {scoreKeeper.score} Wave: {scoreKeeper.wave}', 30, center=(screen.get_width()/2, 305))
allSprites = pygame.sprite.OrderedUpdates(label1, label2, label3, label4, crosshair)
# ACTION
# Assign key variables
clock = pygame.time.Clock()
# Loop
while True:
# Timer to set frame rate
clock.tick(30)
# Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
# If the mouse click is on the label
xy_position = pygame.mouse.get_pos()
if pygame.mouse.get_pressed()[0] == 1:
if xy_position[0] in labelBorderx and xy_position[1] in labelBordery:
return
crosshair.set_position(xy_position)
# Refresh display
allSprites.clear(screen, background)
allSprites.update()
allSprites.draw(screen)
pygame.display.flip()
def game(hacks):
'''
This function is the game loop.
'''
# Display
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Airplane Defense")
# Entities
background = pygame.image.load('images/background.png').convert()
screen.blit(background, (0, 0))
pygame.mixer.music.load('sounds/musicLife.mp3')
pygame.mixer.music.set_volume(0.1)
pygame.mixer.music.play(-1)
missileExplosionSound = pygame.mixer.Sound('sounds/explosion.wav')
missileExplosionSound.set_volume(0.3)
planeExplosionSound = pygame.mixer.Sound('sounds/ono.wav')
# Set up endzones that are outside of the screen.
leftEndzone = gameSprites.EndZone(screen, -screen.get_width(), 0, False)
rightEndzone = gameSprites.EndZone(screen, screen.get_width(), 0, False)
topEndzone = gameSprites.EndZone(screen, 0, 0, True)
bottomEndzone = gameSprites.EndZone(screen, 0, screen.get_height(), True)
player = gameSprites.Player(screen)
missile = gameSprites.Projectile(screen, (-30, 10))
crosshair = gameSprites.Crosshair()
scoreKeeper = gameSprites.ScoreKeeper(screen)
waveLabel = gameSprites.WaveLabel(scoreKeeper.wave+1)
# Missile sprite group to check for all missiles on the screen.
missileSprites = pygame.sprite.Group()
# Endzone group to check for collision
endzoneSprites = pygame.sprite.Group(leftEndzone, rightEndzone, topEndzone,\
bottomEndzone)
# Plane group to check for collision
planeSprites = pygame.sprite.Group()
# Add them to allSprites group to display.
allSprites = pygame.sprite.LayeredUpdates(player, crosshair, scoreKeeper)
# ACTION
# Assign
# This variable is used to make sure it only takes the position of the first
# mouse click.
moved = False
clock = pygame.time.Clock()
keepGoing = True
# speed_up modifies the speed of the plane as the wave increases
speed_up = 0
# Time gives a 2 second pause before starting the next wave.
timer = 60
# Add planes (in increments of 100) by increasing the x coord range
increase_plane = 0
# This sets up the reload speed for the rocket (15 frames = 0.5 seconds)
reload = 15
# Hide the mouse cursor to display crosshair.
pygame.mouse.set_visible(False)
# Loop
while keepGoing:
# Time
clock.tick(30)
# Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pauseScreen(crosshair, screen, background)
screen.blit(background, (0, 0))
# Get coordinates of mouse to later use to rotate player and missile
xy_position = pygame.mouse.get_pos()
if hacks:
# Auto move
if planeSprites:
if abs(planeSprites.sprites()[0].rect.centery - player.rect.centery) < 10:
pass
elif planeSprites.sprites()[0].rect.centery - player.rect.centery > 0:
player.move(10)
elif planeSprites.sprites()[0].rect.centery - player.rect.centery < 0:
player.move(-10)
else:
# Move player using keys W and S
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
player.move(-10)
if keys[pygame.K_s]:
player.move(10)
# Set position of crosshair
crosshair.set_position(xy_position)
if hacks:
# Shoot missile whenever possible with hacks on
if not moved:
# Auto aim enabled
# Set up missile sprite.
if planeSprites:
missile = gameSprites.Projectile(screen, player.rect.center)
# Make cpu smarter by moving towards the closest plane but
# shooting at the further plane
if len(planeSprites) >= 2 and abs(planeSprites.sprites()[0].rect.centery - player.rect.centery) > 25:
missile.set_speed(planeSprites.sprites()[1].rect.center)
missile.rotate(planeSprites.sprites()[1].rect.center)
else:
missile.set_speed(planeSprites.sprites()[0].rect.center)
missile.rotate(planeSprites.sprites()[0].rect.center)
# Change player image to already shot.
player.shoot()
# Add the missile sprite to display + update
allSprites.add(missile)
missileSprites.add(missile)
moved = True
else:
# Check if mouse click to shoot missile.
if pygame.mouse.get_pressed()[0] and not moved:
# Change player image to already shot.
player.shoot()
# Set up missile sprite.
missile = gameSprites.Projectile(screen, player.rect.center)
missile.set_speed(xy_position)
missile.rotate(xy_position)
# Add the missile sprite to display + update
allSprites.add(missile)
missileSprites.add(missile)
moved = True
# Check for collision of missile with planes.
collision = pygame.sprite.groupcollide(missileSprites, planeSprites, False, False)
if collision:
for plane in list(collision.values())[0]:
scoreKeeper.add_score(10)
# Kill each plane.
plane.kill()
missileExplosionSound.play()
explosion = gameSprites.Explosion(plane.rect.center, 0)
allSprites.add(explosion)
# Take the first key of the dictionary (the missile) and kill it
missile = list(collision)[0]
missile.kill()
missile.set_position((-30, 10))
# Check for collision of player with planes.
collision = pygame.sprite.spritecollide(player, planeSprites, False)
if collision:
for plane in collision:
scoreKeeper.add_score(5)
# Kill each plane sprite.
plane.kill()
missileExplosionSound.play()
explosion = gameSprites.Explosion(plane.rect.center, 0)
allSprites.add(explosion)
# Check for collision of planes with left endzone
collision = pygame.sprite.spritecollide(leftEndzone, planeSprites, False)
for plane in collision:
# Subtract life from player
scoreKeeper.subtract_life()
# Kill each plane sprite.
plane.kill()
planeExplosionSound.play()
explosion = gameSprites.Explosion(plane.rect.center, 1)
allSprites.add(explosion)
# Check for collision of planes with top endzone
collision = pygame.sprite.spritecollide(topEndzone, planeSprites, False)
for plane in collision:
# Reverse y-direction of plane.
plane.change_directionY()
# Check for collision of planes with bottom endzone
collision = pygame.sprite.spritecollide(bottomEndzone, planeSprites, False)
for plane in collision:
# Reverse y-direction of plane.
plane.change_directionY()
# Check for collision of missile with endzone
collision = pygame.sprite.groupcollide(missileSprites, endzoneSprites, True, False)
if collision:
# Get the missile object that collided with the endzone
missile = list(collision)[0]
missileExplosionSound.play()
explosion = gameSprites.Explosion(missile.rect.center, 0)
allSprites.add(explosion)
missile.kill()
# If all planes are destroyed, one wave is completed
if not planeSprites:
timer -= 1
allSprites.add(waveLabel)
allSprites.move_to_front(waveLabel)
# If 2 seconds are up.
if not timer:
waveLabel.kill()
# Add one to wave number
scoreKeeper.add_wave()
waveLabel.add_wave()
wave = []
for x in range(screen.get_width(), screen.get_width()+1000+\
increase_plane*50, 100):
# Make the planes bounce up and down after it reaches third
# wave
if scoreKeeper.wave >= 3:
bounce = random.randint(-3, 3)
else:
bounce = 0
# Generate random spawning y-coordinates
y = random.randint(75, screen.get_height() - 25)
wave.append(gameSprites.Plane(screen, (x, y), 5+speed_up//2, bounce))
speed_up += 1
increase_plane += 1
# Set maximum speed up
if speed_up > 10:
speed_up = 10
# Add the waves to respective sprite groups
planeSprites.add(wave)
allSprites.add(wave)
# Reset timer.
timer = 60
# Set up reload speed.
if moved:
reload -= 1
if reload == 0:
moved = False
player.reload()
reload = 15
if scoreKeeper.check_lose():
keepGoing = False
if hacks:
# Auto aim player rotation
if planeSprites:
if len(planeSprites) >= 2 and abs(planeSprites.sprites()[0].rect.centery - player.rect.centery) > 25:
player.rotate(planeSprites.sprites()[1].rect.center)
else:
player.rotate(planeSprites.sprites()[0].rect.center)
else:
# Get x and y coordinates of mouse to rotate turret in correct direction
player.rotate(xy_position)
# Refresh screen
allSprites.clear(screen, background)
screen.blit(background, (0, 0))
allSprites.update()
allSprites.draw(screen)
pygame.display.flip()
if not moved:
pygame.draw.line(screen, (220, 220, 220), player.rect.center, xy_position)
return scoreKeeper
def main():
'''
This function defines the 'mainline logic' for the game.
'''
keepGoing = True
while keepGoing:
keepGoing, hacks = startMenu()
if keepGoing:
scoreKeeper = game(hacks)
# Make sure only record score if it is greater than 0
if scoreKeeper.score:
gameOver(scoreKeeper)
# Close the game window
pygame.quit()
# Call the main function
main()
| true |
48d060e1bf4f96801899bded56c5b7ebb64f7e5d | Python | praveenpkg8/stroryboard | /utils/exception.py | UTF-8 | 782 | 2.515625 | 3 | [] | no_license | class EmailFormatException(Exception):
def __init__(self, value):
self.error_message = value
class MobileNumberLengthException(Exception):
def __init__(self, value):
self.error_message = value
class MobileNumberFormatException(Exception):
def __init__(self, value):
self.error_message = value
class UserNameAlreadyTakenException(Exception):
def __init__(self, value):
self.error_message = value
class UserNameLengthException(Exception):
def __init__(self, value):
self.error_message = value
class AccountAlreadyExist(Exception):
def __init__(self, value):
self.error_message = value
class PasswordLengthException(Exception):
def __init__(self, value):
self.error_message = value
| true |
bf416df8b075cdd0281682d9839231850b355ef3 | Python | longxin1991/numeric | /fft.py | UTF-8 | 1,027 | 2.59375 | 3 | [] | no_license | import numpy as np
import scipy as sp
def f(x):
return x**4-3*x**3+2*x**2-np.tan(x*(x-2))
p=3
#A1=[f(i/4.000) for i in np.arange(8)]
#A2=[f(i/4.000) for i in np.arange(8)]
A1=range(1,9)
A2=range(1,9)
w=[]
t=0+1j
t=-np.pi*t
for m in range(4) :
b=0+1j
c=np.e**(2*np.pi/(2**p)*m*b)
w.append(c)
for q in range(1,4):
if q%2==1 :
for k in range(2**(p-q)) :
for j in range(2**(q-1)):
A2[k*2**q+j]=A1[k*2**(q-1)+j]+A1[k*2**(q-1)+j+2**(p-1)]
A2[k*2**q+j+2**(q-1)]=(A1[k*2**(q-1)+j]-A1[k*2**(q-1)+j+2**(p-1)])*w[k*2**(q-1)]
else :
for k in range(2**(p-q)) :
for j in range(2**(q-1)) :
A1[k*2**q+j]=A2[k*2**(q-1)+j]+A2[k*2**(q-1)+j+2**(p-1)]
A1[k*2**q+j+2**(q-1)]=(A2[k*2**(q-1)+j]-A2[k*2**(q-1)+j+2**(p-1)])*w[k*2**(q-1)]
if p%2==0 :
for i in range(8) :
A2[i]=A1[i]
c=[1.0/4*A2[i]*np.e**(t*i) for i in range(5)]
c[0]=c[0]/2
a=[c[i].real for i in range(5)]
b=[c[i].imag for i in range(5)]
| true |
5ad7fa263b2e3c8adf36ef402e12cfedd0476190 | Python | silpaps/mypython | /OOPS/calculator.py | UTF-8 | 769 | 3.953125 | 4 | [] | no_license | class Calc:
def add(self,a,b):
self.a=a
self.b=b
res=self.a+self.b
print(res)
def sub(self,a,b):
self.a=a
self.b=b
res=self.a-self.b
print(res)
def mul(self,a,b):
self.a=a
self.b=b
res=self.a*self.b
print(res)
def div(self,a,b):
self.a=a
self.b=b
res=self.a/self.b
print(res)
ob=Calc()
print("1.addition")
print("2.subtraction")
print("3.multipllication")
print("4.division")
choice=int(input("enter a chioce"))
num1=int(input("first number"))
num2=int(input("second number"))
if choice == 1:
ob.add(num1,num2)
elif choice == 2:
ob.sub(num1, num2)
elif choice == 3:
ob.mul(num1, num2)
else:
ob.div(num1, num2) | true |
abfebdbe09454126c0819ad057c5bbb31a44b1f8 | Python | FisicaComputacionalI/creaunagrafica2ddesdecero-AlondraMin | /Sin título 0.py | UTF-8 | 384 | 3.4375 | 3 | [] | no_license | import numpy as np
import pylab as pl
#Crea un vector (arreglo) con los valores del eje X
x=[1,2,3,4]
#Crea un vector (arreglo) con valores en el eje Y para cada valor en el eje X
y=[8,9.2,8.5,8.5]
#Grafica del vector x contra el vector y
pl.plot(x,y)
pl.ylabel('Promedio')
pl.xlabel('Semestre')
pl.title('Promedio por semestre')
#Guarda la grafica
pl.savefig('temp1.png') | true |
348a2437754e48bb005c5338f9bb6ea4ffe3ae99 | Python | zonkisa/leezyer | /TheAlgorithms/data_structures/python/union_find/union_find.py | UTF-8 | 6,981 | 3.625 | 4 | [] | no_license | # coding:utf-8
from __future__ import print_function
"""
动态连通性问题 --> 过滤掉序列中所有无意义的整数对
A,给出两个节点,判断它们是否连通,如果连通,不需要给出具体的路径
B,给出两个节点,判断它们是否连通,如果连通,需要给出具体的路径
其中union-find是解决问题A,而问题B可以使用基于深度优先的算法
动态连通性的应用场景:
1.网络连接判断:
如果每个pair中的两个整数分别代表一个网络节点,那么该pair就是用来表示这两个节点是需要连通的。那么为所有的pairs建立了动态连通图后,就能够尽可能少的减少布线的需要,因为已经连通的两个节点会被直接忽略掉。
2.变量名等同性(类似于指针的概念):
在程序中,可以声明多个引用来指向同一对象,这个时候就可以通过为程序中声明的引用和实际对象建立动态连通图来判断哪些引用实际上是指向同一对象。
基础假设,对于连通的所有节点,可以认为它们属于一个组,因此不连通的节点必然就于不同的组。
随着Pair的输入,需要首先判断输入的两个节点是否连通。
如何判断呢?按照上面的假设,可以通过判断它们属于的组,然后看看这两个组是否相同,如果相同,那么这两个节点连通,反之不连通。
为简单起见,将所有的节点以整数表示,即对N个节点使用0到N-1的整数表示。
而在处理输入的Pair之前,每个节点必然都是孤立的,即分属于不同的组,可以使用数组来表示这一层关系,
数组的index是节点的整数表示,而相应的值就是该节点的组号
数组的index是节点的整数表示,而相应的值就是该节点的组号
数组的index是节点的整数表示,而相应的值就是该节点的组号
"""
"""
quick-find 复杂度分析:
union和connect都是基于find操作,在进行Union时,根据p、v值分别访问数组(2次),
若不等,需要检查整个数组(N次),可能的改变次数为1~N-1次。 N+3 ~ 2N+1
若最后只有一个连通分量,最少连接是邻居互连,共N-1次。
平方复杂度
9条 0.024s
900条 36.5s 1600呗
"""
class QuickFind:
# count的含义为等价类/组的数量
def __init__(self, N):
if N <= 0:
raise ValueError(" N should be greater than 0 ")
self.count = N
self.ids = list(range(self.count))
# 连接两个节点,使之属于同一个组
def union(self, p, v):
pID = self.find(p)
qID = self.find(v)
if pID == qID:
return
if pID != qID:
for i in range(len(self.ids)):
if self.ids[i] == pID:
self.ids[i] = qID
self.count -= 1
# 查询节点属于的组,数组对应位置的值即为组号
def find(self, p):
return self.ids[p]
# 判断两个节点是否属于同一个组,分别得到两个节点的组号,然后判断组号是否相等
def connected(self, p, v):
return self.find(p) == self.find(v)
# return self.ids[p] == self.ids[v]
# 获取组的数目
def count(self):
return self.count()
class QuickUnion:
def __init__(self, N):
if N <= 0:
raise ValueError(" N should be greater than 0 ")
self.count = N
self.ids = list(range(self.count))
def connected(self, p, v):
return self.find(p) == self.find(v)
# 获取组的数目
def count(self):
return self.count()
def find(self, p):
while p != self.ids[p]:
p = self.ids[p]
return p
def union(self, p, q):
pRoot = self.find(p)
qRoot = self.find(q)
if pRoot == qRoot:
return
if pRoot != qRoot:
self.ids[pRoot] = qRoot
self.count -= 1
class WeightedQuickUnion:
def __init__(self, N):
if N <= 0:
raise ValueError(" N should be greater than 0 ")
self.count = N
self.ids = list(range(N))
self.size = [1] * N
def connected(self, p, v):
return self.find(p) == self.find(v)
# 获取组的数目
def count(self):
return self.count()
def find(self, p):
while p != self.ids[p]:
p = self.ids[p]
return p
def union(self, p, q):
"""
分配权重
重点在于父节点与权重的更新
父节点权重大,则将权重小的父节点指向权重大的父节点,同时更新父节点权重
"""
pRoot = self.find(p)
qRoot = self.find(q)
if pRoot == qRoot:
return
elif self.size[pRoot] < self.size[qRoot]:
self.ids[pRoot] = qRoot
self.size[qRoot] += self.size[pRoot]
else:
self.ids[qRoot] = pRoot
self.size[pRoot] += self.size[qRoot]
self.count -= 1
class PathCompressedWeightedQuickUnion:
"""
1.5.12 使用路径压缩的加权quick-union
要实现路径压缩,需要为find方法添加循环,将路径上的所有节点直接链接到根节点,得到几乎完全扁平的树
"""
def __init__(self, N):
if N <= 0:
raise ValueError(" N should be greater than 0 ")
self.count = N
self.ids = list(range(N))
self.size = [1] * N
def find_bad(self, p):
"""
循环将从p到根节点的路径上的每个节点都连接到节点,这里用到两次循环
"""
tmp = p
while p != self.ids[p]:
p = self.ids[p]
pRoot = p
p = tmp
while pRoot != self.ids[p]:
tmp = self.ids[p]
self.ids[p] = pRoot
p = tmp
return pRoot
def find(self, p):
"""
循环将从p到根节点的路径上的每个节点都连接到节点
此处路径压缩体现在,更新父节点时,由于p != self.ids[p],故每次多往前走一部
"""
while p != self.ids[p]:
self.ids[p] = self.ids[self.ids[p]]
p = self.ids[p]
return p
def connected(self, p, v):
return self.find(p) == self.find(v)
# 获取组的数目
def count(self):
return self.count()
def union(self, p, q):
"""
分配权重
重点在于父节点与权重的更新
父节点权重大,则将权重小的父节点指向权重大的父节点,同时更新父节点权重
"""
pRoot = self.find(p)
qRoot = self.find(q)
if pRoot == qRoot:
return
elif self.size[pRoot] < self.size[qRoot]:
self.ids[pRoot] = qRoot
self.size[qRoot] += self.size[pRoot]
else:
self.ids[qRoot] = pRoot
self.size[pRoot] += self.size[qRoot]
self.count -= 1
| true |
73483dd04739ecb69335484489c5c749fdac0250 | Python | moisescaldas/LockChain | /src/lockchain.py | UTF-8 | 4,572 | 2.953125 | 3 | [] | no_license | from logging import error
from typing import Union
from rsa import PublicKey, PrivateKey
from os import PathLike
from hashlib import sha256
import secrets
class CryptMessage:
def __init__(self, data : bytes = b"", key : Union[PrivateKey, PublicKey] = None) -> None:
self.data = data
self.key = key
def set_data(self, data : bytes = b"") -> bool:
if type(data) != bytes:
return False
else:
self.data = data
return True
def set_key(self, key : Union[PrivateKey, PublicKey]) -> bool:
if type(key) == PrivateKey:
self.key = key
return True
elif type(key) == PublicKey:
self.key = key
return True
else:
return False
def get(self) -> bytes:
return self.data
def encrypt(self) -> bool:
if (type(self.key) != PrivateKey) and (type(self.key) != PublicKey):
return False
lenght_key = length_int(self.key.n)
lenght_seg = lenght_key - 40
checksum = sha256(self.data).digest()
data = b""
for sep in range(0, lenght_data := len(self.data), lenght_seg):
if (sep + lenght_seg) < lenght_data:
segment = self.data[sep: sep + lenght_seg]
else:
segment = self.data[sep:]
packet_prefix = CryptMessage.__rand_prefix()
packet = packet_prefix + segment
value_packet = int.from_bytes(packet, 'big')
calc = pow(value_packet, self.key.e, self.key.n)
data += int.to_bytes(calc, lenght_key, 'big')
self.data = checksum + data
return True
def decrypt(self) -> bool:
if type(self.key) != PrivateKey:
return False
lenght_key = length_int(self.key.n)
work_data = self.data[32:]
checksum = self.data[:32]
data = b''
for sep in range(0, lenght_data := len(work_data), lenght_key):
if (sep + lenght_key) < lenght_data:
segment = work_data[sep: sep + lenght_key]
else:
segment = work_data[sep:]
value_segment = int.from_bytes(segment, 'big')
calc = pow(value_segment, self.key.d, self.key.n)
packet = int.to_bytes(calc, length_int(calc), 'big')
message = packet[32:]
data += message
if checksum != sha256(data).digest():
raise error("Erro na Descriptografia da Mensagem")
self.data = data
return True
def __rand_prefix() -> bytes:
while True:
value_prefix = secrets.randbits(32 * 8)
if len(data := int_bytes(value_prefix)) == 32:
return data
class CryptFile(CryptMessage):
def __init__(self, file: PathLike = "", key: Union[PrivateKey, PublicKey] = None) -> None:
try:
with open(file, 'rb') as by_file:
data = by_file.read()
except:
data = b""
super().__init__(data, key)
self.file = file
def set_file(self, file: PathLike) -> bool:
try:
with open(file, 'rb') as by_file:
data = by_file.read()
except FileNotFoundError:
return False
self.data = data
return True
def encrypt(self) -> bool:
try:
if super().encrypt():
with open(self.file, "wb") as by_file:
by_file.write(self.data)
return True
else:
return False
except:
return False
def decrypt(self) -> bool:
try:
if super().decrypt():
with open(self.file, "wb") as by_file:
by_file.write(self.data)
return True
else:
return False
except:
return False
def length_int(num : int = 0) -> int:
bits = int.bit_length(num)
if bits % 8 == 0:
return bits // 8
else:
return ((bits // 8) + 1)
int_bytes = lambda x : int.to_bytes(x, length_int(x), 'big')
bytes_int = lambda x: int.from_bytes(x, 'big') | true |
04886eb5f394fcf5a57d6a25c0ab128c47a01498 | Python | the5ixth/other | /mobil.py | UTF-8 | 5,913 | 2.984375 | 3 | [] | no_license | from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.button import Button
import time
import random
class PongPaddle(Widget):
score = NumericProperty(0)
velocity_y = NumericProperty(0)
velocity_x = NumericProperty(0)
velocity = ReferenceListProperty(velocity_x, velocity_y)
trickey_direction = 0
trickey_degree = 0
def bounce_ball(self, ball):
if self.collide_widget(ball):
self.trickey_direction = random.choice([-1,1])
self.trickey_degree = random.randint(0,20)
vx, vy = ball.velocity
offset = (ball.center_y - self.center_y) / (self.height / 2) * 7
bounced = Vector(-1 * vx, vy)
vel = bounced * 1.1
ball.velocity = vel.x, vel.y + offset
def move(self, ball, speed=.7):
if ball.center_y > self.center_y:
self.velocity = (0, speed)
elif ball.center_y < self.center_y:
self.velocity = ( 0, -speed)
else:
self.velocity = (0, 0)
self.pos = Vector ( *self.velocity ) + self.pos
def predict_AI(self, ball, height, width, speed=2, player_one=False, trickey=True, oponent=None):
# get variables
b_cntr_x, b_cntr_y = ball.center
b_pos_x, b_pos_y = ball.pos
b_vx, b_vy = ball.velocity
#each player calculates the width different because the b_vx is negative
if player_one:
width_remain = b_pos_x - 50
else:
width_remain = width - b_pos_x -50
frames_remain = width_remain / b_vx
# make sure the frames remaning is pos due to b_vx negative
if frames_remain < 0:
frames_remain *= -1
# calculate the y address where the ball will colide
y_addr = b_cntr_y
for i in range(int(frames_remain)):
y_addr += b_vy
tgt_y = y_addr
# calculate bounces
while tgt_y > height *2:
tgt_y -= height
while tgt_y < 0 - height:
tgt_y += height
if tgt_y >= height:
tgt_y = height - (tgt_y - height)
elif tgt_y < 0:
tgt_y = height - ( tgt_y + height)
# use the enemys position against them
if oponent and trickey:
enmy_y = oponent.pos[1]
if enmy_y > (height / 2 ):
tgt_y = tgt_y + ((( height - self.pos[1] ) / ( height / 2 )) * 75 )
elif enmy_y < (height / 2 ):
tgt_y = tgt_y - (( self.pos[1] / ( height / 2 )) * 75 )
# try to make the ball bounce at weird angles
elif trickey:
tgt_y = tgt_y + ( self.trickey_direction * 5 * self.trickey_degree)
#if tgt_y < 100:
# tgt_y = 100
#if tgt_y > height - 100:
# tgt_y = height-100
# if the target y is closer than the speed will allow
if tgt_y > self.center_y:
diff = tgt_y - self.center_y
if diff < speed:
self.velocity = (0, diff)
else:
self.velocity= (0,speed)
elif tgt_y < self.center_y:
diff = self.center_y - tgt_y
if diff < speed:
self.velocity = (0, -diff)
else:
self.velocity = (0, -speed)
elif tgt_y == self.center_y:
self.velocity = (0, 0)
# set the new paddles position
self.pos = Vector( *self.velocity) + self.pos
class PongBall(Widget):
velocity_x = NumericProperty(0)
velocity_y = NumericProperty(0)
velocity = ReferenceListProperty(velocity_x, velocity_y)
def move(self):
if 0 <= self.velocity_x < 4:
self.velocity_x = 4
elif 0 > self.velocity_x > -4:
self.velocity_x = -4
self.pos = Vector( *self.velocity ) + self.pos
class PongGame(Widget):
ball = ObjectProperty(None)
player1 = ObjectProperty(None)
player2 = ObjectProperty(None)
def serve_ball(self, vel=(-4, 0)):
#vel = Vector(vel).rotate(random.randint(0,360))
self.ball.center = self.center
self.player1.center_y = self.center[1]
self.player2.center_y = self.center[1]
self.ball.velocity = vel
def update(self, dt):
self.ball.move()
# bounce of paddles
self.player1.bounce_ball(self.ball)
self.player2.bounce_ball(self.ball)
# player ai movement
#self.player2.center_y = self.ball.center_y
#self.player1.center_y = self.ball.center_y
self.player2.predict_AI(self.ball, self.top, self.width)
self.player1.predict_AI(self.ball, self.top, self.width, player_one=True, oponent=self.player2)
# bounce ball off bottom or top
if (self.ball.y < self.y) or (self.ball.top > self.top):
self.ball.velocity_y *= -1
# went of to a side to score point?
if self.ball.x < self.x:
pts = 1
if pts < 0:
pts *= -1
self.player2.score += int(pts)
self.serve_ball(vel=(4, 0))
if self.ball.x > self.width:
pts = 1
if pts < 0:
pts *= -1
self.player1.score += int(pts)
self.serve_ball(vel=(-4, 0))
def on_touch_move(self, touch):
if touch.x < self.width / 3:
self.player1.center_y = touch.y
#if touch.x > self.width - self.width / 3:
#self.player2.center_y = touch.y
class PongApp(App):
def build(self):
game = PongGame()
game.serve_ball()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
if __name__ == '__main__':
PongApp().run()
| true |
422c20d4e615f2f8ab6730ba237d4c76022cfa37 | Python | BraydenCleary/SF_DAT_15_WORK | /final_project/crime_test_add_features.py | UTF-8 | 1,974 | 2.8125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 2 11:52:47 2015
@author: braydencleary
"""
import pandas as pd
import numpy as np
from sklearn.grid_search import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
from sklearn import tree
from sklearn import metrics
import matplotlib.pyplot as plt
from datetime import datetime
import re
WEEKEND_DAYS = ['Saturday', 'Sunday']
EARLY_MORNING = [5,6,7]
LATE_MORNING = [8,9,10]
EARLY_AFTERNOON = [11,12,13]
LATE_AFTERNOON = [14,15,16]
EARLY_EVENING = [17,18,19]
LATE_EVENING = [20,21,22]
EARLY_NIGHT = [23,0,1]
LATE_NIGHT = [2,3,4]
def determine_time_of_day_bucket(date):
hour = datetime.strptime(date, '%Y-%m-%d %H:%M:%S').hour
if hour in EARLY_MORNING:
return 1
elif hour in LATE_MORNING:
return 2
elif hour in EARLY_AFTERNOON:
return 3
elif hour in LATE_AFTERNOON:
return 4
elif hour in EARLY_EVENING:
return 5
elif hour in LATE_EVENING:
return 6
elif hour in EARLY_NIGHT:
return 7
elif hour in LATE_NIGHT:
return 8
crime_test = pd.read_csv('https://s3.amazonaws.com/braydencleary-data/final_project/crime_test_full.csv')
dummies = pd.get_dummies(crime_test, columns=['DayOfWeek', 'PdDistrict'])
for column_name, column in dummies.transpose().iterrows():
crime_test[column_name] = column
crime_test['is_weekend'] = crime_test.apply(lambda x: 1 if x['DayOfWeek'] in WEEKEND_DAYS else 0, axis=1)
crime_test['time_of_day_bucket'] = crime_test.apply(lambda x: determine_time_of_day_bucket(x['Dates']), axis=1)
crime_test['day_of_month'] = crime_test.apply(lambda x: datetime.strptime(x['Dates'], '%Y-%m-%d %H:%M:%S').day, axis=1)
crime_test['month_of_year'] = crime_test.apply(lambda x: datetime.strptime(x['Dates'], '%Y-%m-%d %H:%M:%S').month, axis=1)
crime_test['year'] = crime_test.apply(lambda x: datetime.strptime(x['Dates'], '%Y-%m-%d %H:%M:%S').year, axis=1)
| true |
80136a2221f829a9d2e85b3d9223efc40947d017 | Python | Dunnel45/ca117 | /week_09/lab_9.2/queue_092.py | UTF-8 | 407 | 3.609375 | 4 | [] | no_license | class Queue(object):
def __init__(self):
self.l = []
def enqueue(self, num):
self.l.append(num)
def dequeue(self):
a = []
a.append(self.l[0])
del self.l[0]
for o in a:
return o
def first(self):
return self.l[0]
def is_empty(self):
return len(self.l) == 0
def __len__(self):
return len(self.l)
| true |
3a0eaa713296fd01d25964d192dd6ce1756ac503 | Python | thePortus/dhelp | /dhelp/text/_bases.py | UTF-8 | 5,966 | 3.5625 | 4 | [
"MIT"
] | permissive | #!/usr/bin/python
import re
from collections import UserString
class BaseText(UserString):
"""Performs text manipulation and natural language processing.
Base class for all Text objects. Can be used on its own to perform a number
of operations, although it is best used with on of its language-specific
children.
Args:
text (:obj:`str`) Text to be stored for processing/nlp
options (:obj:`dict`, optional) Options settings found at respective keywords
Example:
>>> from dhelp import BaseText
>>> text = BaseText('Lorem ipsum dolor sit amet...')
>>> print(text)
'Lorem ipsum dolor sit amet...'
""" # noqa
options = {
'encoding': 'utf-8',
'language': 'english'
}
def __init__(self, text, *args, **kwargs):
super().__init__(str)
# update .options if options keyword arg passed
if 'options' in kwargs:
if type(kwargs['options']) == dict:
self.options.update(kwargs['options'])
self.data = text
def __enter__(self):
pass
def __exit__(self, ctx_type, ctx_value, ctx_traceback):
pass
def stringify(self):
"""Returns the text of this object as a pure string type.
Can be useful when you need the text back in a string object format
for comparison with regular strings.
Returns:
:obj:`str` String form of the text
Example:
>>> text = BaseText('Lorem ipsum dolor sit amet...')
>>> stringified_text = text.stringify()
>>> print(type(stringified_text))
<class 'str'>
"""
return str(self.data)
def rm_lines(self):
"""Removes endlines.
Gives a new version of the text with all endlines removed. Removes
any dashed line endings and rejoins split words.
Returns:
:obj:`self.__class__` New version of text, with endlines removed
Example:
>>> text = BaseText('Lorem\\nipsum do-\\nlor sit amet....\\n')
>>> modified_text = text.rm_lines()
>>> print(modified_text)
'Lorem ipsum dolor sit amet...'
"""
rexr = re.compile(r'\n+')
# substituting single endlines for matching endline blocks
clean_text = rexr.sub(' ', self.data)
return self.__class__(
clean_text
.replace('-\n ', '').replace('- \n', '').replace('-\n', '')
.replace(' - ', '').replace('- ', '').replace(' -', '')
.replace('\n', ' '),
self.options
)
def rm_nonchars(self):
"""Removes non-language characters.
Gives a new version of the text with only latin characters remaining,
or Greek characters for Greek, texts, and so on. Defaults to assuming
Latin based.
Returns:
:obj:`self.__class__` Returns new version of text, with non-letters removed
Example:
>>> text = BaseText('1αLorem ipsum 2βdolor sit 3γamet...')
>>> modified_text = text.rm_nonchars()
>>> print(modified_text)
'Lorem ipsum dolor sit amet...'
""" # noqa
if self.options['language'] == 'greek':
valid_chars_pattern = '([ʹ-Ϋά-ϡἀ-ᾯᾰ-῾ ])'
else:
valid_chars_pattern = '([A-Za-z ])'
return self.__class__(
"".join(re.findall(valid_chars_pattern, self.data)),
self.options
)
def rm_edits(self):
"""Removes text inside editor's marks.
Gives a new version with any text between editorial marks such as
brackets or parentheses removed.
Returns:
:obj:`self.__class__` Returns new version of text, with editoria removed
Example:
>>> text = BaseText('Lore[m i]psum {dolo}r sit a(met)...')
>>> modified_text = text.rm_edits()
>>> print(modified_text)
'Lor psum r sit a...'
""" # noqa
return self.__class__(
re.sub("\〚(.*?)\〛", "", re.sub("\{(.*?)\}", "", re.sub(
"\((.*?)\)", "", re.sub("\<(.*?)\>", "", re.sub(
"\[(.*?)\]", "", self.data))))),
self.options
)
def rm_spaces(self):
"""Removes extra whitespace.
Gives a new version of the text with extra whitespace collapsed.
Returns:
:obj:`self.__class__` Returns new version of text, with extra spaced collapsed
Example:
>>> text = BaseText('Lorem ipsum dolor sit amet...')
>>> modified_text = text.rm_spaces()
>>> print(modified_text)
'Lorem ipsum dolor sit amet...'
""" # noqa
# regex compiler for all whitespace blocks
rexr = re.compile(r'\s+')
# substituting single spaces for matching whitespace blocks
clean_text = rexr.sub(' ', self.data)
return self.__class__(
clean_text.strip(),
self.options
)
def re_search(self, pattern):
"""Search text for matching pattern.
Receives search pattern and returns True/False if it matches. Pattern
can be a simple string match (e.g. .re_search('does this match?')), or
a full Regular Expression.
Args:
pattern (:obj:`str`) String with the desired Regular Expression to search
Returns:
:obj:`bool` True if matching, False if not
Example:
>>> text = BaseText('Lorem ipsum dolor sit amet...')
>>> print(text.re_search('Lorem ipsum'))
True
>>> print(text.re_search('Arma virumque cano'))
False
""" # noqa
# Converting pattern to regex
pattern = re.compile(pattern)
if pattern.search(self.data):
return True
else:
return False
| true |
9248fef35ca5fbd246a6ec566d608d629cd085c3 | Python | winsold107/testing_1c | /Balda/python-src/WordCollector.py | UTF-8 | 3,260 | 2.984375 | 3 | [] | no_license | from Letter import Coordinates
from PySide import QtCore
import copy
__author__ = 'user1'
class WordCollector(QtCore.QObject):
send_to_dictionary = QtCore.Signal(str)
clear_state = QtCore.Signal(Coordinates)
end_of_transaction = QtCore.Signal(str)
approve_word = QtCore.Signal()
def __init__(self):
QtCore.QObject.__init__(self)
self._word_ = ''
self._x_list_ = list()
self._y_list_ = list()
self._is_new_ = list()
self._changed_cell_ = Coordinates()
self._is_approved_ = False
def connect_to_dictionary(self, dictionary):
self.send_to_dictionary.connect(dictionary.check_word)
def connect_to_board(self, board):
self.clear_state.connect(board.reset_state)
self.end_of_transaction.connect(board.remake_move)
self.approve_word.connect(board.set_approved)
def clear_word(self):
if not self._is_approved_:
self.clear_state.emit(self._changed_cell_)
sent_word = copy.deepcopy(self._word_)
self._word_ = ''
self._x_list_ = list()
self._y_list_ = list()
self._is_new_ = list()
self.end_of_transaction.emit(sent_word)
def end_move(self):
print("Move ended")
print("Approved word " + self._word_)
self.approve_word.emit()
@QtCore.Slot(str)
def add_letter(self, letter):
self._word_ += letter
@QtCore.Slot(int)
def add_x(self, x):
self._x_list_.append(x)
@QtCore.Slot(int)
def add_y(self, y):
self._y_list_.append(y)
@QtCore.Slot(Coordinates)
def add_changed_cell(self, coordinates: Coordinates):
self._changed_cell_ = coordinates
@QtCore.Slot()
def has_approved(self):
return self._is_approved_
@QtCore.Slot(int)
def add_new(self, is_new_value):
self._is_new_.append(is_new_value)
@QtCore.Slot()
def check_word(self):
if len(self._x_list_) == 0:
self._is_approved_ = False
self.clear_word()
return
self._is_approved_ = True
cnt_new = 0
for i in range(1, len(self._x_list_)):
if abs(self._x_list_[i] - self._x_list_[i - 1]) + abs(self._y_list_[i] - self._y_list_[i - 1]) != 1:
self._is_approved_ = False
for i in range(len(self._x_list_)):
if self._x_list_[i] == self._changed_cell_.x and self._y_list_[i] == self._changed_cell_.y:
cnt_new += 1
if cnt_new != 1:
self._is_approved_ = False
for i in range(0, len(self._x_list_)):
for j in range(i + 1, len(self._y_list_)):
if self._x_list_[i] == self._x_list_[j] and self._y_list_[i] == self._y_list_[j]:
self._is_approved_ = False
if self._is_approved_:
self.send_to_dictionary.emit(self._word_)
if self._is_approved_:
self.end_move()
self.clear_word()
@QtCore.Slot(int)
def set_word_approved(self, value):
self._is_approved_ = value
if __name__ == '__main__':
wc = WordCollector()
| true |
32a9e5b24fd129f48f3e98230f42811fe7a08c88 | Python | bradyz/sandbox | /hackerrank/graph/matrix.py | UTF-8 | 960 | 2.671875 | 3 | [] | no_license | from queue import Queue
def min_path(u):
# print(g)
r = None
while p[u] != u and g[u][p[u]] != -1:
if not r or g[u][p[u]] < g[r][p[r]]:
r = u
u = p[u]
tmp = g[r][p[r]]
g[r][p[r]] = -1
g[p[r]][r] = -1
return tmp
def bfs(s):
global r
# print("bfs", u)
q = Queue()
p[s] = s
q.put(s)
while not q.empty():
u = q.get()
if u in c and p[u] != u:
r += min_path(u)
continue
for v in g[u]:
if p[v] != -1 or g[u][v] == -1:
continue
p[v] = u
q.put(v)
if __name__ == "__main__":
n, k = map(int, input().split())
g = {u: dict() for u in range(n)}
for _ in range(n-1):
u, v, w = map(int, input().split())
g[u][v] = w
g[v][u] = w
c = {int(input()) for _ in range(k)}
r = 0
p = [-1 for _ in range(n)]
for u in c:
bfs(u)
print(r)
| true |
a0cd5e3604816a39c6523f8fab2847754d5f9580 | Python | krava322/ca1 | /ca117/lab-031/test.py | UTF-8 | 191 | 2.609375 | 3 | [] | no_license |
k = ['Ababa', 'civic', 'Damon', 'Hannah', 'lager', 'leper', 'level', 'lever', 'madam', 'minim', 'nomad', 'radar', 'refer', 'regal', 'repel', 'revel', 'rever', 'rotor', 'tenet']
print(len(k)) | true |
577a654d580cde04307be0088f89e22a6423910f | Python | gmainkar/python-practice | /q2.py | UTF-8 | 412 | 4.59375 | 5 | [] | no_license | '''
Write a program which can compute the factorial of a given numbers.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8
Then, the output should be:
40320
'''
def fact(x):
if x == 0:
return 1
else:
return x * fact(x-1)
num = int(input('Enter a number\n'))
print(str(num) + '! is ' + str(fact(num))) | true |
82d82865a1a13060c51107b01e7362c13b233eb8 | Python | Windsooon/LeetCode | /Single Number.py | UTF-8 | 182 | 2.703125 | 3 | [] | no_license | class Solution:
def singleNumber(self, nums):
res = 0
for num in nums:
res ^= num
return res
k = [2, 1]
s = Solution()
s.singleNumber(k)
| true |
9c87261f6f37c57a99a9638dd3d1451a0867abaf | Python | MarcelPohl97/python-socket-chat-app | /client.py | UTF-8 | 904 | 3.140625 | 3 | [] | no_license | import socket
from threading import Thread
import time
global client_socket
name_input = input("Bitte gib deinen Namen ein: ")
client_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server_addr = ('127.0.0.1', 1339)
client_socket.connect(server_addr)
client_socket.send(bytes(name_input + " Has joined the chat", "utf-8"))
def send_messages():
while True:
client_socket.send(bytes(name_input + ": " + input(), "utf-8"))
def get_messages():
while True:
try:
msg = client_socket.recv(1024)
if msg == "":
time.sleep(1)
else:
print(str(msg, "utf-8"))
except:
time.sleep(1)
get_Thread = Thread(target=get_messages)
get_Thread.start()
get_thread = Thread(target=send_messages)
get_thread.start()
| true |
61d5ae7d7ad8e43fd5e25063d80951d015e43741 | Python | HongMyunggi/MSE_Python | /ex190.py | UTF-8 | 545 | 4 | 4 | [] | no_license | #190
apart = [ [101, 102], [201, 202], [301, 302] ] # 2차원 배열이다.
for i in apart: # 우선 apart에 있는 행을 가지고 for문을 돌린다.
for j in i: # 그리고 가지고온 행의 열을 가지고 for문을 돌린다.
print(j,'호') # j는 apart에서 갖고온 행에 있는 열의 값이다.
# 만약 for문 안에 print를 넣고 마지막에 출력되게 만들고 싶으면 아래처럼 하면된다.
#if j == 302:
#print('-----')
print('-----')# 그리고 마지막에 -----넣어주어야한다.
| true |
6eaa1250af0754e67690747ddc809f0810e3eee2 | Python | Coder-Chandler/L_0 | /Algorithm BinaryTree/Implicit_Decision_Tree.py | UTF-8 | 798 | 3.359375 | 3 | [] | no_license | a = [6,3]
b = [7,2]
c = [8,4]
d = [9,5]
def DTImplicit(toConsider, avail):
if toConsider == [] or avail == 0:
result = (0, ())
elif toConsider[0][1] > avail:
result = DTImplicit(toConsider[1:], avail)
else:
nextItem = toConsider[0]
withVal, withToTake = DTImplicit(toConsider[1:], avail - nextItem[1])
withVal += nextItem[0]
withoutVal, withoutToTake = DTImplicit(toConsider[1:], avail)
if withVal > withoutVal:
result = (withVal, withToTake + (nextItem,))
else:
result = (withoutVal, withoutToTake)
return result
stuff = [[6,3],[7,2],[8,4],[9,5]]
val, taken = DTImplicit(stuff, 10)
print ''
print 'implicit decision search'
print 'value of stuff'
print val
print 'actual stuff'
print taken
| true |
7c856af0d00017aab21f08fb4fece9bc5a50b5b8 | Python | tiwaripulkit99/pythonpractice | /pythonpractice/foorlooppractice.py | UTF-8 | 88 | 4.375 | 4 | [] | no_license | for index, item in enumerate(['one', 'two', 'three', 'four']):
print(index, '::', item) | true |
3fb0619ab8227a38f020206e6dffce7c52fe7d7d | Python | reaprman/Data-Struct-algo-nanodegree | /proj2/problem1.py | UTF-8 | 3,571 | 4.03125 | 4 | [] | no_license | """
maps and double linked list
a double linked list can be used as a LRU cache
a dictionary can be used to map the keys to the nodes to facilitate constant, i.e. O(1), lookups insertions and deletions
added print lines to the cache lookups to see value in console.
"""
class Node():
def __init__(self, key=0, value=0):
self.next = None
self.prev = None
self.value = value
self.key = key
class LRU_Cache(object):
def __init__(self, capacity=5):
# Initialize class variables
self.maxsize = capacity
self.map = dict() #should be a map of the key and the node for the value
self.head = None
self.tail = None
pass
def get(self, key):
# Retrieve item from provided key. Return -1 if nonexistent.
cache_map = self.map
cache_node = cache_map.get(key)
if self.head == cache_node:
return cache_node.value
if cache_node != None:
if self.tail != cache_node:
nxt = cache_node.next
if nxt.prev != None:
nxt.prev = cache_node.prev
elif self.tail == cache_node:
self.tail = cache_node.prev
prev = cache_node.prev
if prev.next != None:
prev.next = cache_node.next
head = self.head
head.prev = cache_node
cache_node.next = head
cache_node.prev = None
self.head = cache_node
return cache_node.value
return -1
pass
def set(self, key, value):
# Set the value if the key is not present in the cache. If the cache is at capacity remove the oldest item.
cache_map = self.map
cache_item = Node(key, value)
if self.head == None:
self.head = cache_item
self.tail = cache_item
else:
if len(cache_map) == self.maxsize:
tail = self.tail
cache_map.pop(tail.key)
self.tail = tail.prev
cache_item.next = self.head
old_head = self.head
old_head.prev = cache_item
self.head = cache_item
cache_map[key] = cache_item
pass
our_cache = LRU_Cache(5)
second_cache = LRU_Cache()
third_cache = LRU_Cache(-1)
our_cache.set(1, 1)
our_cache.set(2, 2)
our_cache.set(3, 3)
our_cache.set(4, 4)
print("First test")
print(our_cache.get(1)) # returns 1
print(our_cache.get(2)) # returns 2
print(our_cache.get(9)) # returns -1 because 9 is not present in the cache
our_cache.set(5, 5)
our_cache.set(6, 6)
print(our_cache.get(6))
print(our_cache.get(3)) # returns -1 because the cache reached it's capacity and 3 was the least recently used entry
second_cache.set(1, 1)
second_cache.set(2, 2)
second_cache.set(3, 3)
second_cache.set(4, 4)
print("Second test")
print(second_cache.get(1)) # returns 1
print(our_cache.get(2)) # returns 2
print(our_cache.get(9)) # returns -1 because 9 is not present in the cache
second_cache.set(5, 5)
second_cache.set(6, 6)
print(second_cache.get(6))
print(second_cache.get(3))
third_cache.set(1, 1)
third_cache.set(2, 2)
third_cache.set(3, 3)
third_cache.set(4, 4)
print("Third test")
print(third_cache.get(1)) # returns 1
print(third_cache.get(2)) # returns 2
print(third_cache.get(9)) # returns -1 because 9 is not present in the cache
third_cache.set(5, 5)
third_cache.set(6, 6)
print(third_cache.get(6))
print(third_cache.get(3)) | true |
bd81ac77a31e5be87e1253a7bff8b8491a362c70 | Python | Kivy-CN/KivyRoad | /yingshaoxo/Kivy Painter.py | UTF-8 | 1,592 | 2.703125 | 3 | [] | no_license | from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.widget import Widget
from kivy.graphics import Line
class Painter(Widget):
def on_touch_down(self, touch):
with self.canvas:
touch.ud["line"] = Line(points=(touch.x, touch.y))
def on_touch_move(self, touch):
touch.ud["line"].points += (touch.x, touch.y)
class MainScreen(Screen):
pass
class AnotherScreen(Screen):
pass
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_string("""
#: import FadeTransition kivy.uix.screenmanager.FadeTransition
ScreenManagement:
transition: FadeTransition()
MainScreen:
AnotherScreen:
<MainScreen>:
name: "main"
Button:
on_release: root.manager.current = "other"
text: "Next Screen"
font_size: 50
<AnotherScreen>:
name: "other"
FloatLayout:
Painter:
id: painter
Button:
color: 0, 1, 0, 1
font_size: 25
size_hint: 0.3, 0.2
text: "Back Home"
on_release: root.manager.current = "main"
pos_hint: {"right": 1, "top":1}
Button:
color: 0, 1, 0, 1
font_size: 25
size_hint: 0.3, 0.2
text: "Clear"
on_release: root.ids['painter'].canvas.clear()
pos_hint: {"left": 0, "top":1}
""")
class SimpleKivy(App):
def build(self):
return presentation
if __name__ == "__main__":
SimpleKivy().run()
| true |
f8b0db157fc0f76ae0279102d44a65f8b7f62e48 | Python | Er1c-ai/potential-journey | /sql_rd_assignment /test_sql_test.py | UTF-8 | 1,139 | 2.703125 | 3 | [] | no_license | import unittest
import sqlite3
from sql_test import DatabaseEditor
class TestSqlData(unittest.TestCase):
def setUp(self):
self.new_output = DatabaseEditor()
self.new_output.db = sqlite3.connect(":memory:")
self.new_output.c = self.new_output.db.cursor()
self.new_output.c.execute("CREATE TABLE IF NOT EXISTS products (id SERIAL PRIMARY KEY, created "
"timestamp with time zone NOT NULL, modified timestamp with time zone NOT NULL, "
"description character varying(255) NOT NULL, amount numeric(12,2) NOT NULL); ")
def read_data(self):
self.new_output.adding_additional_column()
self.new_output.data_entry()
def query_data(self):
self.new_output.c.execute("SELECT count(*) FROM products")
result = self.new_output.c.fetchone()[0]
print(result)
return result
def test_number_rows(self):
self.read_data()
self.assertEqual(self.query_data(), 20)
def tearDown(self):
self.new_output.db.close()
if __name__ == "__main__":
unittest.main()
| true |
5d2905eb01cfecb212da989ef2a70e6e0932574f | Python | TonyStarkkkkkkkk/Captcha | /4-segment.py | UTF-8 | 1,694 | 2.734375 | 3 | [] | no_license | import os
from PIL import Image
os.makedirs('./segment/', exist_ok=True)
def getCutPoint(lst, width):
mid = len(lst)//2
temp = lst[mid-width: mid+width+1]
point = min(temp)
return mid-width+temp.index(point)
def findEdge(img):
hrz_begin, hrz_end = 0, 0
ver_begin, ver_end = 0, 0
w, h = img.size
a = [0 for pw in range(w)]
b = [0 for ph in range(h)]
# 垂直投影
for i in range(w):
for j in range(h):
if(img.getpixel((i, j))) <= 200:
a[i] += 1
for i in range(w):
if a[i] >= 5:
hrz_begin = i
break
for i in range(w-1, 0, -1):
if a[i] >= 5:
hrz_end = i
break
mid = getCutPoint(a[hrz_begin:hrz_end+1], 5)+hrz_begin
mid_1 = getCutPoint(a[hrz_begin:mid+1], 3)+hrz_begin
mid_2 = getCutPoint(a[mid: hrz_end+1], 3)+mid
# 水平投影
for j in range(h):
for i in range(w):
if(img.getpixel((i, j))) <= 200:
b[j] += 1
for i in range(h):
if b[i] >= 5:
ver_begin = i
break
for i in range(h-1, 0, -1):
if b[i] >= 5:
ver_end = i
break
return [(ver_begin, ver_end), (hrz_begin, mid_1, mid, mid_2, hrz_end)]
for ii in range(200):
path = "./denoise/" + str(ii) + ".jpg"
img = Image.open(path)
outDir = "./segment/"
point = findEdge(img)
for i in range(len(point[1]) - 1):
box = (point[1][i], point[0][0], point[1][i + 1], point[0][1])
img.crop(box).save(outDir + str(400+ii) + "_" + str(i) + '.jpg')
print('finished')
| true |
8be4d5aa1b2e3f233c56e542333f2c2c551e2e7e | Python | andreim9816/Facultate | /Anul III/Sem 2/Tehnici de Optimizare/Teme/344_Manolache_Andrei_3/344_Manolache_Andrei_3.py | UTF-8 | 5,484 | 2.78125 | 3 | [] | no_license | # Manolache Andrei
# 344
# Tema 3
import matplotlib.pyplot as plt
import numpy as np
from numpy import linalg as la
import random
import cvxpy as cp
"""Generam datele, folosindu-ne de o functie genRand() care genereaza un numar aleator intre -5 si 5"""
def genRand():
startRandom = -5
endRandom = 5
return random.randrange(startRandom, endRandom)
"""Definim functia pe care vrem sa o minimizam"""
def func(x):
global a
return 0.5 * x.T @ (a @ a.T + np.eye(a.size)) @ x
"""Functie care calculeaza gradientul"""
def gradient(x, Q):
return Q @ x
"""Functie care calculeaza eroarea absoluta """
def cond_oprire_err_absolut(x_k, f_x_minim):
return func(x_k) - f_x_minim
"""Functie care calculeaza norma gradientului intr-un punct"""
def cond_oprire_norma(x_new, x_old):
return la.norm(x_new - x_old)
"""Functie care il calculeaza pe Q"""
def calcul_Q(a):
return a @ a.T + np.eye(a.size)
"""Functie care il calculeaza pe alpha """
def calcul_alpha(Q):
Lips = np.max(la.eigvals(Q))
alpha = 1 / Lips
return alpha
"""Functie care calculeaza proiectia unui punct pe multimea fezabila"""
def proiectie(x, a, b=1):
return x - ((a.T @ x - b) / (la.norm(a) ** 2)) * a
"""Functie care calculeaza alpha la pasul curent, pentru varianta cu backtracking"""
def alege_alpha(x_k_old, a, b, Q):
"""Setam alpha_k_0 initial"""
alpha = 0.25
grad = gradient(x_k_old, Q)
x_new = proiectie(x_k_old - alpha * grad, a, b)
"""Alegem c si p"""
c = 0.1
p = 0.1
"""Se calculeaza "x_k+1" cu un alpha ales de noi, dupa care se updateaza pana il gasim pe x_k+1"""
while (func(proiectie(x_k_old - alpha * grad, a, b)) > func(x_k_old) - c / alpha * (la.norm(x_new - x_k_old) ** 2)):
alpha *= p
x_new = proiectie(x_k_old - alpha * grad, a, b)
return alpha, x_new
"""Functie care minimizeaza functia respectiva, folosind metoda gradientului proiectat cu pas constant"""
def gradient_pas_constant(Q, x, cond_oprire, val_min):
"""Array cu sirul solutiilor obtinute"""
sol = []
x_old = x
"""Pt calculul cu norma, pt x0, nu putem aplica x_k+1 - x_k"""
if cond_oprire != "norma":
sol = [cond_oprire_err_absolut(x, val_min)]
alpha = calcul_alpha(Q)
"""Numarul de iteratii"""
k = 0
while True:
"""Calculeaza alpha, face update lui x, adauga noua eroare obtinuta"""
grad = gradient(x_old, Q)
x_new = proiectie(x_old - alpha * grad, np.ones(n), 1)
if cond_oprire == "norma":
criteriu_stop = cond_oprire_norma(x_new, x_old)
else:
criteriu_stop = cond_oprire_err_absolut(x_new, val_min)
"""Adauga in sirul solutiilor"""
sol.append(criteriu_stop)
k += 1
"""Verifica conditie de oprire"""
if criteriu_stop < eps:
break
"""Update"""
x_old = x_new
return x, sol, k
def gradient_pas_bkt(Q, x, cond_oprire, x_min, a, b):
"""Array cu sirul solutiilor obtinute"""
sol = []
x_old = x
"""Pt calculul cu norma, pt x0, nu putem aplica x_k+1 - x_k"""
if cond_oprire != "norma":
sol = [cond_oprire_err_absolut(x, x_min)]
"""Numarul de iteratii"""
k = 0
while True:
"""Calculeaza alpha, face update lui x, adauga noua eroare obtinuta"""
alpha, x_new = alege_alpha(x_old, a, b, Q)
if cond_oprire == "norma":
criteriu_stop = cond_oprire_norma(x_new, x_old)
else:
criteriu_stop = cond_oprire_err_absolut(x_new, x_min)
"""Adauga in sirul solutiilor"""
sol.append(criteriu_stop)
k += 1
"""Verifica conditie de oprire"""
if criteriu_stop < eps:
break
"""Update"""
x_old = x_new
return x, sol, k
"""Alegem dimensiunea lui n si il generam pe a"""
n = 2
a = np.array([genRand() for i in range(n)])
"""Setam eroarea, calculam pe Q si setam punctul de start"""
eps = 1e-3
Q = calcul_Q(a)
x0 = np.array([2, -1])
"""Calculeaza valoarea minima a functiei folosind CVXPY"""
z = cp.Variable(n)
b = 1
objective = cp.Minimize(0.5 * cp.quad_form(z, Q))
constraints = [np.ones(n) @ z == b]
prob = cp.Problem(objective, constraints)
result = prob.solve(solver='CVXOPT')
sol = prob.value
"""Calculeaza sirul solutiilor pt fiecare metoda si tipul erorii"""
x_sol_constant_norma = gradient_pas_constant(Q, x0, "norma", sol)
x_sol_bkt_norma = gradient_pas_bkt(Q, x0, "norma", sol, np.ones(n), 1)
x_sol_constant_err_abs = gradient_pas_constant(Q, x0, "eroare", sol)
x_sol_bkt_err_abs = gradient_pas_bkt(Q, x0, "eroare", sol, np.ones(n), 1)
"""Cele 2 gragice"""
"""Graficul cu eroarea fata de eroarea absoluta"""
plt.figure(0)
plt.xlabel("k")
plt.ylabel("f(x_k) - f*")
plt.title("Figura 1")
plt.plot([i for i in range(0, x_sol_constant_err_abs[2])], x_sol_constant_err_abs[1][1:], c="orange",
label="Pas constant")
plt.plot([i for i in range(0, x_sol_bkt_err_abs[2])], x_sol_bkt_err_abs[1][1:],
c="blue",
label="Pas backtracking")
plt.legend()
plt.show()
"""Graficul cu eroarea fata de norma"""
plt.figure(1)
plt.xlabel("k")
plt.ylabel("||x_k+1 - x_k||")
plt.title("Figura 2")
plt.plot([i for i in range(1, x_sol_constant_norma[2])], x_sol_constant_norma[1][1:], c="orange",
label="Pas constant")
plt.plot([i for i in range(0, x_sol_bkt_norma[2])], x_sol_bkt_norma[1][:], c="blue",
label="Pas backtracking")
plt.legend()
plt.show()
| true |
af3292e8dbb8323f4733e485bfb20b1fb3f53492 | Python | vidhyagp/TableClassification | /src/CRF/CRFFeatures.py | UTF-8 | 5,099 | 2.640625 | 3 | [] | no_license | '''
Created on Dec 1, 2012
@author: shriram
'''
from Utils.SparseType import SparseType
from Utils.Constants import Constants
import sys
class CRFFeatures:
def orthographicfeatures(self, featurelist, col, prevtag, curtag, i, fontdict):
issamefont = i!=0 and (fontdict[int(col[i][1].attrib['font'])] == fontdict[int(col[i - 1][1].attrib['font'])])
if(issamefont and curtag == SparseType.OTHERSPARSE and prevtag == SparseType.OTHERSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
if(not issamefont and curtag == SparseType.OTHERSPARSE and prevtag == SparseType.NONSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
tabletextbefore = ((i>0 and col[i-1][1].text is not None and col[i-1][1].text.lower().startswith("table ")) or
(i>1 and col[i-2][1].text is not None and col[i-2][1].text.lower().startswith("table ")))
#tabletextafter = (i < len(col) - 2 and col[i+1][1].text is not None and col[i+2][1].text is not None
# and (col[i+1][1].text.lower().startswith("table ") or col[i+2][1].text.lower().startswith("table ")))
if((tabletextbefore) and curtag == SparseType.OTHERSPARSE and prevtag == SparseType.NONSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
def lexicalfeatures(self, featurelist, col, prevtag, curtag, i):
pass
def spaceinline(self, text):
if(text is None):
return [0,0,0]
spacecount = 0
largestspace = 0
wordcount = 0
smallestspace = sys.maxint
for r in xrange(len(text)):
if(text[r] == ' '):
spacecount += 1
elif(spacecount != 0):
wordcount += 1
if(spacecount < smallestspace):
smallestspace = spacecount
if(spacecount > largestspace):
largestspace = spacecount
spacecount = 0
return [largestspace, smallestspace, wordcount+1 ]
def spacelayoutfeatures(self, featurelist, col, curtag, i):
spaceincurrentline = self.spaceinline(col[i][1].text)
if (spaceincurrentline[0] >= Constants.LARGEST_SPACE and curtag == SparseType.OTHERSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
if (spaceincurrentline[1] <= Constants.SMALLEST_SPACE and curtag == SparseType.OTHERSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
if (spaceincurrentline[2] <= Constants.WORDS_IN_LINE and curtag == SparseType.OTHERSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
def layoutfeatures(self, featurelist, col, prevtag, curtag, i):
#[textpieces, heightprev, heightnext, largest space, smallest space, words]
if(int(col[i][1].attrib['textpieces']) > Constants.NUM_TEXT_PIECES and curtag == SparseType.OTHERSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
if(i>1 and int(col[i][1].attrib['height']) < int(col[i-2][1].attrib['height']) and curtag == SparseType.OTHERSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
if(i!=len(col)-1 and int(col[i][1].attrib['height']) < int(col[i+1][1].attrib['height']) and curtag == SparseType.OTHERSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
self.spacelayoutfeatures(featurelist, col, curtag, i)
def otherfeatures(self,featurelist, col, prevtag, curtag, i):
if(i!=0 and prevtag == SparseType.OTHERSPARSE and curtag == SparseType.OTHERSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
if(i!=0 and prevtag == SparseType.OTHERSPARSE and curtag == SparseType.NONSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
if(i!=0 and prevtag == SparseType.NONSPARSE and curtag == SparseType.OTHERSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
if(i!=0 and prevtag == SparseType.NONSPARSE and curtag == SparseType.NONSPARSE):
featurelist.append(1)
else:
featurelist.append(0)
def domainfindfeatureFunction(self, i, col, fontdict, prevtag = None, curtag = None):
featurelist = list()
if(prevtag is None and i!=0):
prevtag = int(col[i-1][0])
if(curtag is None and i!=0):
curtag = int(col[i][0])
self.orthographicfeatures(featurelist, col, prevtag, curtag, i, fontdict)
#featurelist.append(self.lexicalfeatures(featurelist, col, prevtag, curtag, i))
self.layoutfeatures(featurelist, col, prevtag, curtag, i)
self.otherfeatures(featurelist, col, prevtag, curtag, i)
return featurelist | true |
fc6707ea1a47ac29ff7b75849b32e8321702c23d | Python | PosoSAgapo/next_word_prediction | /data_preparation/prep_exp_data.py | UTF-8 | 4,381 | 2.765625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 4 11:27:09 2019
This script add the training data logfrequency and the SUBTLEX log frequency to
the human reading data files. It also fixes a small mistake in the original
data where somehow the word Scott was replaced with Sott leading to an oov case.
@author: danny
"""
import pandas as pd
import numpy as np
import os
import pickle
from collections import defaultdict
eeg = '/home/danny/Documents/databases/next_word_prediction/data/data_EEG.csv'
et = '/home/danny/Documents/databases/next_word_prediction/data/data_ET.csv'
spr = '/home/danny/Documents/databases/next_word_prediction/data/data_SPR.csv'
# spr_et are the spr data files split by whether sentences occur in the ET data
# or not
spr_et = '/home/danny/Documents/databases/next_word_prediction/data/data_SPR_ET.csv'
spr_et2 = '/home/danny/Documents/databases/next_word_prediction/data/data_SPR_ET2.csv'
freq_dict_loc = os.path.join('/home/danny/Documents/databases/next_word_prediction/data',
'word_freq')
subtlex_loc = '/home/danny/Downloads/SUBTLEXusfrequencyabove1.xls'
def load_obj(loc):
with open(f'{loc}.pkl', 'rb') as f:
obj = pickle.load(f)
return obj
# load the training data frequency, this is created by prep_nextword.py
freq_dict = load_obj(freq_dict_loc)
# load subtlex word frequencies
subtlex = pd.read_excel(subtlex_loc)
subtlex_dict = {str(subtlex.iloc[idx].Word).lower(): subtlex.iloc[idx].Lg10WF for idx in range(len(subtlex))}
subtlex_dict = defaultdict(int, subtlex_dict)
# load the human reading data
eeg_data = pd.read_csv(eeg, sep = ',')
et_data = pd.read_csv(et, sep = ',')
spr_data = pd.read_csv(spr, sep = ',')
spr_et_data = pd.read_csv(spr_et, sep = ',')
spr_et2_data = pd.read_csv(spr_et2, sep = ',')
# for some reason the test sentence 'Scott got up and washed his plate', turned
# into 'Sott got up ...' in the data files and there is no frequency count for Sott
def rep_word(data):
for idx, line in enumerate(data.word):
if line == 'Sott':
data.set_value(idx, 'word', 'Scott')
rep_word(eeg_data)
rep_word(et_data)
rep_word(spr_data)
rep_word(spr_et_data)
rep_word(spr_et2_data)
# get log frequencies based on the used training data.
def get_log_freq(data, freq_dict):
log_freq = pd.Series(dtype='float64')
for idx, word in enumerate(data.word):
# ignore punctuation, these words will be rejected based on reject_word column,
# but we might as well get the log frequency count for them
if word[-1]== '.' or word[-1]== '?' or word[-1]== '!' or word[-1]== ',':
word = word[:-1]
log_freq = log_freq.append(pd.Series(freq_dict[word.lower()]), ignore_index = True)
data['log_freq'] = log_freq
# get log frequencies from subtlex
def get_subtlex_freq(data, subtlex):
subtlex_freq = pd.Series(dtype='float64')
for idx, word in enumerate(data.word):
word = word.replace('\'', '').lower()
# ignore punctuation
if word[-1]== '.' or word[-1]== '?' or word[-1]== '!' or word[-1]== ',':
word = word[:-1]
#convert 10log to word counts and add 1 to each word count to prevent
# missing words leading to log(0)
freq = 10**subtlex[word]
if freq != 1:
freq += 1
subtlex_freq = subtlex_freq.append(pd.Series(-np.log(freq)), ignore_index = True)
data['subtlex_freq'] = subtlex_freq
get_log_freq(eeg_data, freq_dict)
get_log_freq(et_data, freq_dict)
get_log_freq(spr_data, freq_dict)
get_subtlex_freq(eeg_data, subtlex_dict)
get_subtlex_freq(et_data, subtlex_dict)
get_subtlex_freq(spr_data, subtlex_dict)
get_subtlex_freq(spr_et_data, subtlex_dict)
get_subtlex_freq(spr_et2_data, subtlex_dict)
# convert booleans to ints so that the values are compatible with julia
eeg_data.reject_data = eeg_data.reject_data * 1
eeg_data.reject_word = eeg_data.reject_word * 1
et_data.reject_data = et_data.reject_data * 1
et_data.reject_word = et_data.reject_word * 1
spr_data.reject_data = spr_data.reject_data * 1
spr_data.reject_word = spr_data.reject_word * 1
eeg_data.to_csv(f'{eeg}_new', index = False)
et_data.to_csv(f'{et}_new', index = False)
spr_data.to_csv(f'{spr}_new', index = False)
spr_et_data.to_csv(f'{spr_et}_new', index = False)
spr_et2_data.to_csv(f'{spr_et2}_new', index = False)
| true |
f2c18e5c8bffdfb141fbd8fb2e902f765d050b98 | Python | boralad56/Programming101-2 | /week8/1-Generating-Tests/is_prime_test.py | UTF-8 | 370 | 3.0625 | 3 | [
"MIT"
] | permissive | import unittest
from is_prime import is_prime
class IsPrimeTests(unittest.TestCase):
"""This is a test class for testing is_prime funciton"""
def testCase1(self):
self.assertTrue(is_prime(7), "7 should noot be prime")
def testCase2(self):
self.assertFalse(is_prime(8), "8 should be prime")
if __name__ == '__main__':
unittest.main()
| true |
10147ef5bf7ccf2de75c6d04f68b8661ba739ce0 | Python | OBIGOGIT/etch | /binding-python/runtime/src/main/python/etch/binding/msg/Message.py | UTF-8 | 3,624 | 2.546875 | 3 | [
"Apache-2.0",
"BSD-4-Clause-UC",
"Zlib",
"BSD-4-Clause",
"LicenseRef-scancode-other-permissive",
"ISC"
] | permissive | """
# Licensed to the Apache Software Foundation (ASF) under one *
# or more contributor license agreements. See the NOTICE file *
# distributed with this work for additional information *
# regarding copyright ownership. The ASF licenses this file *
# to you under the Apache License, Version 2.0 (the *
# "License"); you may not use this file except in compliance *
# with the License. You may obtain a copy of the License at *
# *
# http://www.apache.org/licenses/LICENSE-2.0 *
# *
# Unless required by applicable law or agreed to in writing, *
# software distributed under the License is distributed on an *
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
# KIND, either express or implied. See the License for the *
# specific language governing permissions and limitations *
# under the License.
"""
from __future__ import absolute_import
from ...python.Exceptions import *
from .StructValue import *
from .ValueFactory import *
class Message(StructValue):
"""
A message is modeled as a command and some arguments. The command is an
arbitrary integer value, and the arguments are key/value pairs, where the
key is an arbitrary integer value and the value is any one of the standard
python objects, a StructValue, or any type that may be serialized by the
ValueFactory.
"""
serialVersionUID = 1
"""A bogus serial version ID"""
def __init__(self, messageType, valueFactory, length=None):
"""
Constructs the message
@param messageType The type of the message (command)
@param valueFactory The value factory
@param length Suggested length (ignored)
"""
super(StructValue, self).__init__(messageType, valueFactory, length)
if not isinstance(valueFactory, ValueFactory):
raise IllegalArgumentException, "valueFactory must be of type msg.ValueFactory"
self.__vf = valueFactory
def vf(self):
"""
Return the 'valueFactory'
"""
return self.__vf
def reply(self, rType = None):
"""
Creates a message which is a reply to the current message. The current
message's value factory is copied to the new message. The message-id
of the current message (if any) is copied into the in-reply-to field
of the new message.
@param rType The type of the reply.
@return A reply message.
"""
if not rType:
rType = self.type().getResult()
rmsg = Message(rType, self.__vf)
rmsg.setInReplyTo( self.getMessageId() )
return rmsg
def getMessageId(self):
"""
Return the connection specific unique identifier of this message.
"""
return self.__vf.getMessageId(self)
def setMessageId(self, msgid):
"""
Sets the message-id field of this message
@param msgid The connection specific unique identifier.
"""
self.__vf.setMessageId(self, msgid)
def getInReplyTo(self):
"""
Return the message-id of the message that this is a response to.
"""
return self.__vf.getInReplyTo(self)
def setInReplyTo(self, msgid):
"""
Sets the in-reply-to field of this message.
@param msgid the message-id of the message that this is a response to.
"""
self.__vf.setInReplyTo(self, msgid)
| true |
6d36d327b8fffb54cfd67e6d39ef4a8b785cf723 | Python | Cui-Ryu/awaysaway_- | /requests爬虫05.py | UTF-8 | 2,309 | 2.96875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# @Time : 2020/9/1 21:17
# @Author : AWAYASAWAY
# @File : requests爬虫05.py
# @IDE : PyCharm
import requests
import json
import xlwt
if __name__ == '__main__':
url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.41'
}
kw = input('输入查询地点:')
param = {
'cname': '',
'pid': '',
'keyword': kw, # 地点查询参数
'pageIndex': '1',
'pageSize': '100', # 更改页面列表长度
}
response = requests.post(url=url, params=param, headers=headers)
page_status_code = response.status_code
print(page_status_code)
page_text = response.json()
fileName = kw + '.json'
fp = open(fileName, 'w', encoding='utf-8')
json.dump(page_text, fp=fp, ensure_ascii=False)
print('保存成功!!!')
print(page_text)
# 解析json数据
# 创建excel工作表
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('sheet1')
# 设置表头
ws.write(0, 0, label='rownum')
ws.write(0, 1, label='storeName')
ws.write(0, 2, label='addressDetail')
ws.write(0, 3, label='pro')
ws.write(0, 4, label='provinceName')
ws.write(0, 5, label='cityName')
# 读取json文件
with open(fileName, mode='r', encoding='utf-8') as fp:
data = json.load(fp)['Table1']
# 将json字典写入excel
val = 1
for data_item in data:
for key, value in data_item.items():
if key == 'rownum':
ws.write(val, 0, value)
if key == 'storeName':
ws.write(val, 1, value)
if key == 'addressDetail':
ws.write(val, 2, value)
if key == 'pro':
ws.write(val, 3, value)
if key == 'provinceName':
ws.write(val, 4, value)
if key == 'cityName':
ws.write(val, 5, value)
print(u'......正在写入第%s行' % val)
val += 1
# 保存csv文件
print(u'......保存成功!!!')
wb.save(kw + '.csv')
| true |
e2ecc5f96f4127b381e296f6fd37977e00078b8c | Python | thortoyo/study | /ABC179/B.py | UTF-8 | 166 | 2.984375 | 3 | [] | no_license | N=int(input())
f = 0
ans = "No"
for i in range(N):
d1,d2=map(int,input().split())
if d1==d2:
f+=1
if f == 3:
ans = "Yes"
else:
f=0
print(ans)
| true |
37481b3ea3d69a87da2697868ecc4ee27868fc7c | Python | savadev/pysparktestingexample | /tests/test_cast_arraytype.py | UTF-8 | 487 | 2.71875 | 3 | [] | no_license | import pytest
from chispa import assert_column_equality, assert_approx_column_equality
import pyspark.sql.functions as F
from pyspark.sql.types import *
def test_cast_arraytype(spark):
data = [
(['200', '300'], [200, 300]),
(['400'], [400]),
(None, None)
]
df = spark.createDataFrame(data, ["nums", "expected"])\
.withColumn("actual", F.col("nums").cast(ArrayType(IntegerType(), True)))
assert_column_equality(df, "actual", "expected")
| true |
e08ce9df37f52cb02db2314b47f4cf8495076fe1 | Python | cbuie/dsp | /python/q6_strings.py | UTF-8 | 2,747 | 3.453125 | 3 | [] | no_license | # Based on materials copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
def donuts(count):
'''
input must be an int
:param count:
'''
if int(count) < 10:
print "Number of dounts: %s" % count
else:
print "Number of donuts: many"
# test it out:
for i in range(1, 20, 2):
donuts(i)
########################################################################
def both_ends(s):
'''
:param s: input a string
:return: first 2 chars and last 2 chars
'''
try:
if len(s) > 2:
return s[:2] + s[-2:]
elif len(s) <= 2:
return ''
except:
raise NotImplementedError('input was not an int')
# test it out:
for i in str('here are a bunch of words to test').split(): print both_ends(i)
########################################################################
def fix_start(s):
s0 = s[0]
return s0 + s[1:].replace(s[0], '*')
print fix_start('babble')
print fix_start('aardvark')
print fix_start('google')
print fix_start('donut')
########################################################################
def mix_up(a, b):
if len(a) + len(b) > 4:
a0 = (a[:2]);
b0 = (b[:2])
return a.replace(a0, b0) + ' ' + b.replace(b0, a0)
else:
raise ValueError('both arguments be at least 2 chars long')
print mix_up('mix', 'pod')
print mix_up('dog', 'dinner')
print mix_up('gnash', 'sport')
print mix_up('pezzy', 'firm')
print mix_up('a', 'b')
########################################################################
def verbing(s):
if len(s) > 2:
if s[3:] == 'ing':
return s.__add__('ly')
else:
return s.__add__('ing')
else:
return s
print verbing('hail')
print verbing('swiming')
print verbing('do')
########################################################################
def not_bad(s):
try:
n = s.rindex('not');
b = s.rindex('bad') + 3
if n < b:
return s.replace(s[n:b], 'good')
else:
return s
except:
return s
print not_bad('This movie is not so bad')
print not_bad('This dinner is not that bad!')
print not_bad('This tea is not hot')
print not_bad("It's bad yet not")
########################################################################
def split_it(s):
if len(s) % 2 > 0:
return s[:len(s) / 2 + 1], s[len(s) / 2 + 1:]
else:
return s[:len(s) / 2], s[len(s) / 2:]
def front_back(a, b):
l = []
for i in (a, b):
l.append(split_it(i))
return l[0][0] + l[1][0] + l[0][1] + l[1][1]
print front_back('abcd', 'xy')
print front_back('abcde', 'xyz')
print front_back('Kitten', 'Donut')
| true |
fe3e01d755fc3b08dbeb487f8362741f021c69d6 | Python | zmcgrath96/hypedsearch | /src/runner.py | UTF-8 | 2,993 | 2.609375 | 3 | [] | no_license | '''
exec.py
Author: Zachary McGrath
Date: 6 April 2020
Executor for the program
In charge of the flow of the program
'''
import os
from src import identification
from src.postprocessing import summary, review
import multiprocessing as mp
def run(args: dict) -> None:
'''
Executing function for the program
Inputs:
args: object arguments from main. Should be validated in main. Attributes of args:
spectra_folder: (str) full path the the directory containing all spectra files
database_file: (str) full path to the .fasta database file
output_dir: (str) full path the the directory to save output to
min_peptide_len: (int) minimum peptide length to consider
max_peptide_len: (int) maximum peptide length to consider
tolerance: (int) the ppm tolerance to allow in search
precursor_tolerance: (int) the ppm tolerance to allow when matching precursors
peak_filter: (int) the number of peaks to filter by
relative_abundance_filter: (float) the percentage of the total abundance a peak must
be to pass the filter
digest: (str) the digest performed
missed_cleavages: (int) the number of missed cleavages allowed in digest
verbose: (bool) extra printing
cores: (int) the number of cores allowed to use
n: (int) the number of alignments to keep per spectrum
DEBUG: (bool) debuging print messages. Default=False
Outputs:
None
'''
# get all the spectra file names
spectra_files = []
for (root, _, filenames) in os.walk(args['spectra_folder']):
for fname in filenames:
spectra_files.append(os.path.join(root, fname))
# make sure cores is: 1 <= cores <= cpu cores
cores = max(1, args['cores'])
cores = min(cores, mp.cpu_count() - 1)
matched_spectra = identification.id_spectra(
spectra_files, args['database_file'],
min_peptide_len=args['min_peptide_len'],
max_peptide_len=args['max_peptide_len'],
ppm_tolerance=args['tolerance'],
precursor_tolerance=args['precursor_tolerance'],
peak_filter=args['peak_filter'],
relative_abundance_filter=args['relative_abundance_filter'],
digest=args['digest'],
n=args['n'] * 10,
verbose=True,
DEBUG=args['DEBUG'],
cores=cores,
truth_set=args['truth_set'],
output_dir=args['output_dir']
)
print('\nFinished search. Writting results to {}...'.format(args['output_dir']))
# matched_spectra = review.tie_breaker(matched_spectra, '', args['n'])
summary.generate(matched_spectra, args['output_dir'])
| true |
a792fb03d2948256322a8ee7c35d3b8465ee8519 | Python | Josip7171/rest_flask_udemy | /kantina_3/test.py | UTF-8 | 628 | 3.34375 | 3 | [] | no_license | import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
create_table = "CREATE TABLE users (" \
"id int, username text, password text" \
")"
cursor.execute(create_table)
user = (1, 'Josip', '123')
insert_query = "INSERT INTO users VALUES (?, ? ,?)"
cursor.execute(insert_query, user)
users = [
(2, 'Ivan', '123'),
(3, 'Pero', '321'),
(4, 'Sara', '123')
]
cursor.executemany(insert_query, users)
select_query = "SELECT * FROM users"
print(cursor.execute(select_query))
for row in cursor.execute(select_query):
print(row)
connection.commit()
connection.close()
| true |
86c29ac42160f91feb35f740644dbc5922e628c8 | Python | cloudspurs/cdm | /src/dina.py | UTF-8 | 2,740 | 2.953125 | 3 | [] | no_license | from cdm import Cdm
import numpy as np
class Dina(Cdm):
def __init__(self, Q, R, g=0.2, s=0.2): # g, s: guess, slip初值
super().__init__(Q, R)
self.theta = np.zeros(shape=self.stu_num) # 属性向量
self.guess = np.zeros(shape=self.prob_num) + g
self.slip = np.zeros(shape=self.prob_num) + s
# EM算法估计模型参数
def train(self, epoch, epsilon):
like = np.zeros(shape=(self.stu_num, self.state_num)) # 似然:每个学生所有题目的似然
post = np.zeros(shape=(self.stu_num, self.state_num)) # 后验概率:每个学生在每个属性向量的概率
theta, slip, guess, R = self.theta.copy(), self.slip.copy(), self.guess.copy(), self.R.copy()
for iteration in range(epoch):
post_tmp, slip_tmp, guess_tmp = post.copy(), slip.copy(), guess.copy()
answer_right = (1 - slip) * self.eta + guess * (1 - self.eta) # 每个属性向量下,每个题目答对的概率
# 每个属性向量下,每个学生的所有题目的似然和
for s in range(self.state_num):
# 当前属性向量下,每个学生每个题目的对数似然
log_like = np.log(answer_right[s, :] + 1e-9) * R + np.log(1 - answer_right[s, :] + 1e-9) * (1 - R)
like[:, s] = np.exp(np.sum(log_like, axis=1)) # 当前属性向量下,每个学生所有题目的似然和
post = like / np.sum(like, axis=1, keepdims=True) # 学生在每个属性向量的后验概率
i_l = np.expand_dims(np.sum(post, axis=0), axis=1) # 每种属性向量下的学生人数
i_jl_0, i_jl_1 = np.sum(i_l * (1 - self.eta), axis=0), np.sum(i_l * self.eta, axis=0) # 每个题eta=0和eta=1的人数
r_jl = np.dot(np.transpose(post), R) # 每种属性向量下每个题目的答对人数
# 每个题目,eta=0答对的人数和eta=1答对的人数
r_jl_0, r_jl_1 = np.sum(r_jl * (1 - self.eta), axis=0), np.sum(r_jl * self.eta, axis=0)
guess, slip = r_jl_0 / i_jl_0, (i_jl_1 - r_jl_1) / i_jl_1 # 更新guess, slip参数
theta = np.argmax(post, axis=1) # 获取后验概率最大的属性向量
change = max(np.max(np.abs(post - post_tmp)), np.max(np.abs(slip - slip_tmp)), np.max(np.abs(guess - guess_tmp)))
if iteration > 20 and change < epsilon:
break
self.theta, self.slip, self.guess = theta, slip, guess
self.know_prob = np.dot(post, self.all_states) # 计算属性掌握概率
if __name__ == '__main__':
q = np.loadtxt('../data/q.csv', dtype=int, delimiter=',') # 读取Q矩阵
d = np.loadtxt('../data/correct_wrong_dina.csv', dtype=int, delimiter=',') # 读取作答对错
dina = Dina(q, d)
dina.train(1000, 0.001)
print('guess', dina.guess)
print('slip', dina.slip)
print('theta')
for i, theta in enumerate(dina.theta[:10]):
print(dina.all_states[theta])
| true |
31784a8fb32fe7f42e1df64a833d8f4bf7c69566 | Python | woshishuishuishuishui/compuational_physics_N2014301020042 | /5.1 V(x,y).py | UTF-8 | 2,303 | 2.6875 | 3 | [] | no_license | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import pylab as pl
class field:
def __init__(self,V0=[],a=[],b=[],V=[]):
self.V0=V0
self.a=a
self.b=b
for i in range(201):
self.a.append(0)
for j in range(50):
self.V0.append(self.a)
for i in range(50):
self.b.append(0)
for i in range(101):
self.b.append(1)
for i in range(50):
self.b.append(0)
for i in range(101):
self.V0.append(self.b)
for i in range(50):
self.V0.append(self.a)
self.V=V
def update_V(self):
Vnew=self.V0
for k in range(100):
Vold=Vnew
Vnew=[self.a]
for i in range(199):
vtemp=[0]
for j in range(199):
vtemp.append((Vold[i][j+1]+Vold[i+2][j+1]+Vold[i+1][j]+Vold[i+1][j+2])/4)
vtemp.append(0)
Vnew.append(vtemp)
Vnew.append(self.a)
for i in range(101):
for j in range(101):
Vnew[i+50][j+50]=1
for k in range(10000):
Vold=Vnew
Vnew=[self.a]
for i in range(199):
vtemp=[0]
for j in range(199):
vtemp.append((Vold[i][j+1]+Vold[i+2][j+1]+Vold[i+1][j]+Vold[i+1][j+2])/4)
vtemp.append(0)
Vnew.append(vtemp)
Vnew.append(self.a)
for i in range(101):
for j in range(101):
Vnew[i+50][j+50]=1
deltaV=[]
for i in range(201):
for j in range(201):
deltaV.append(abs(Vnew[i][j]-Vold[i][j]))
S=sum(deltaV)
if S<0.00001*101*101:
self.V=Vnew
print(k)
break
v=[]
x=[]
y=[]
z=field()
z.update_V()
for i in range(201):
for j in range(201):
v.append(z.V[i][j])
y.append(1-0.01*i)
x.append(-1+0.01*j)
fig=plt.figure()
ax=fig.add_subplot(111, projection='3d')
ax.plot(x,y,v,".")
plt.xlabel("x")
plt.ylabel("y")
plt.zlabel("V")
plt.show()
| true |
00282d4ee0b76a538005a775cf5f7796e922f0b0 | Python | ManuLam/Competition | /Kattis/herman.py | UTF-8 | 91 | 3.21875 | 3 | [] | no_license | import math
r = int(input())
print(math.pi * (r**2))
print(round(float(r**2 + r**2), 6)) | true |
3debaa4b4ac7d441fb64918b2b848985658ed5e5 | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_97/676.py | UTF-8 | 486 | 2.953125 | 3 | [] | no_license | from collections import defaultdict
M = defaultdict(lambda: set())
for j in xrange(1,2000000):
s = str(j)
for k in xrange(1,len(s)):
if s[k] != '0':
recycled = int(s[k:] + s[:k])
if recycled > j:
M[j].add(recycled)
T = int(raw_input())
for i in xrange(T):
total = 0
(A,B) = map(int,raw_input().split())
for j in xrange(A,B+1):
total += len([m for m in M[j] if m <= B])
print 'Case #%d: %d' % (i+1,total)
| true |
c637d10fe22d7a3c14f882e5bde6ef0bb7e2eb5a | Python | bala4rtraining/python_programming | /python-programming-workshop/while/simple_for.py | UTF-8 | 101 | 3.734375 | 4 | [] | no_license |
names = ["Sarah", "Rakesh", "Markus", "Eli"]
# Loop over list.
for name in names:
print(name)
| true |
3883e7cd020c6dd38f54a121c364cb0d7e1dd47a | Python | danielpetterson/trial-database | /scripts/nucleus_trials.py | UTF-8 | 5,724 | 2.546875 | 3 | [] | no_license | import urllib.request
from bs4 import BeautifulSoup
import re
import numpy as np
import pandas as pd
from help_funcs import find_between, strip_post_num, strip_pre_colon, total_days
def study_info_nucleus( study_list ):
study_name, eligibility, recruiting, inpatient, outpatient, payment = [], [], [], [], [], []
study_list = [re.sub('( ?)-( ?)|( ?)–( ?)','-',elem) for elem in study_list]
for elem in study_list:
eligibility.append(elem.split('Eligibility')[1])
study_list = list(map(str.lower,study_list))
for elem in study_list:
study_name.append(find_between(elem.split('\n')[0], 'study name ', ' study').capitalize())
if (match := re.search('currently recruiting', elem) is not None):
recruiting.append(True)
inpatient_str = elem.split('\n')[-3].split('night')[0].strip()
inpatient.append(inpatient_str)
outpatient_str = elem.split('\n')[-2].split('visit')[0].strip()
outpatient.append(outpatient_str)
payment.append('')
df = pd.DataFrame(list(zip(study_name, eligibility, recruiting, inpatient, outpatient, payment)),
columns =['study_name', 'eligibility', 'recruiting', 'inpatient', 'outpatient', 'payment'])
df['inpatient'] = total_days(df['inpatient'])
return df
def requirements( study_list ):
healthy, sex_male, sex_female, age_min, age_max, BMI_min, BMI_max, weight_min, weight_max = [], [], [], [], [], [], [], [], []
study_list = [re.sub('( ?)-( ?)|( ?)–( ?)','-',elem) for elem in study_list]
study_list = [re.sub('\u202f','',elem) for elem in study_list]
study_list = list(map(str.lower,study_list))
for elem in study_list:
healthy.append(any(substring in elem for substring in ['healthy']))
if (match := re.search('(^| )male', elem) is not None):
sex_male.append(True)
if (match := re.search('(^| )female', elem) is not None):
sex_female.append(True)
elem_age_range = elem.split('age ')[1].split('years')[0].strip().split('-')
age_min.append(elem_age_range[0])
if len(elem_age_range) > 1:
age_max.append(elem_age_range[-1])
else:
age_max.append('')
if 'bmi' in elem:
bmi_range = find_between(elem, 'bmi', 'kg').strip().split('-')
BMI_min.append(bmi_range[0])
if len(bmi_range) > 1:
BMI_max.append(bmi_range[-1])
else:
BMI_max.append('')
else:
BMI_min.append('')
BMI_max.append('')
if 'weight' in elem:
elem_weight_range = find_between(elem, 'weight', 'kg').replace('>','').strip().split('-')#[-1].split('-')
weight_min.append(elem_weight_range[0])
if len(elem_weight_range) > 1:
weight_max.append(elem_weight_range[-1])
else:
weight_max.append('')
else:
weight_min.append('')
weight_max.append('')
df = pd.DataFrame(list(zip(healthy, sex_male, sex_female, age_min, age_max, BMI_min, BMI_max, weight_min, weight_max)),
columns =['healthy', 'sex_male', 'sex_female', 'age_min', 'age_max', 'BMI_min', 'BMI_max', 'weight_min', 'weight_max'])
return df
# Melbourne Nucleus Trial List URL
melb_url = 'https://www.nucleusnetwork.com/au/participate-in-a-trial/melbourne-clinical-trials/'
# Brisbane Nucleus Trial List URL
bris_url = 'https://www.nucleusnetwork.com/au/participate-in-a-trial/brisbane-clinical-trials/'
url_list = [melb_url, bris_url]
def nucleus_df( url_list ):
df = pd.DataFrame(columns =['study_name', 'eligibility', 'recruiting', 'inpatient', 'outpatient', 'payment', 'healthy', 'sex_male', 'sex_female', 'age_min', 'age_max', 'BMI_min', 'BMI_max', 'weight_min', 'weight_max'])
for url in url_list:
html = urllib.request.urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
containers = soup.find_all('li')
text = []
for line in containers:
text.append(line.get_text())
# Extract relevant lines minus header
study_lines = [i for i in text if 'Study name' in i][1:]
study_info = study_info_nucleus(study_lines)
study_requirements = requirements(study_lines)
if 'melbourne' in url:
study_info['city'] = 'Melbourne'
study_info['country'] = 'Australia'
df = pd.concat([study_info, study_requirements], axis=1)
else:
study_info['city'] = 'Brisbane'
study_info['country'] = 'Australia'
df_bris = pd.concat([study_info, study_requirements], axis=1)
df = df.append(df_bris, ignore_index = True)
# Formatting
df['eligibility'] = df['eligibility'].replace('Sex','Sex:', regex=True)
df['eligibility'] = df['eligibility'].replace('Age','Age:', regex=True)
df['eligibility'] = df['eligibility'].replace('BMI','BMI:', regex=True)
df['eligibility'] = df['eligibility'].replace('Weight','Weight:', regex=True)
df['eligibility'] = df['eligibility'].replace('Medication','Medication:', regex=True)
df['eligibility'] = df['eligibility'].replace('History','History:', regex=True)
df['eligibility'] = df['eligibility'].replace('Status\s*','', regex=True)
df['eligibility'] = df['eligibility'].replace('Overnight stays\s*\\n\s*','\n Inpatient: ', regex=True)
df['eligibility'] = df['eligibility'].replace('Outpatient visits\s*\\n\s*','\n Outpatient: ', regex=True)
df['eligibility'] = df['eligibility'].replace('View.*\\n','', regex=True)
df['eligibility'] = df['eligibility'].str.strip()
return df
###---Test---
#df = nucleus_df(url_list)
| true |
fc79c491840562a8684abc07ee2d660065e6f5be | Python | ESzabelski/Ciphers-and-code-breaking | /Transposition_Example_For_External_Files.py | UTF-8 | 1,847 | 3.328125 | 3 | [] | no_license | #transposition cipher encrypt and decrypt external files
#switch between encrypt and decrypt modes
import time, os, sys, transpositionEncrypt, transposition_decrypt
def main():
inputFilename= "frankenstein.txt"
outputFilename="frankenstein.encrypted.txt"
#decryptexample:
## inputFilename= "frankenstein.encrypted.txt"
## outputFilename="f_decrypt.txt"
myKey=10
myMode= "encrypt" #switch to encrypt/decrypt if needed
#test if input files is present
if not os.path.exists(inputFilename):
print("the file %s does not exist. Quitting." % (inputFilename))
sys.exit()
#checks if output file already exists and gives a chance to exit
if os.path.exists(outputFilename):
print ("This will overwrite file %s (C)ontinue or (Q)uit?" % (outputFilename))
response=input("> ")
if not response.lower().startswith("c"):
sys.exit()
fileObj=open(inputFilename)
content=fileObj.read()
fileObj.close()
print("%sing..."% (myMode.title()))
#test how long process takes
startTime=time.time()
if myMode=="encrypt":
translated=transpositionEncrypt.encryptMessage(myKey,content)
elif myMode=="decrypt":
translated=transposition_decrypt.decryptMessage(myKey, content)
totalTime=round(time.time() - startTime,2)
print("%sion time: %s second" %(myMode.title(),totalTime))
#write message to output file
outputFileObj=open(outputFilename,"w")
outputFileObj.write(translated)
outputFileObj.close()
print("done %sing %s (%s characters)."%(myMode, inputFilename,len(content)))
print("%sed file is %s. " % (myMode.title(), outputFilename))
#if run instead of as module, call the main
if __name__=="__main__":
main()
| true |
ea543cb61e3bb95b39f80a841cb4c2e96da21187 | Python | wwg377655460/DataStructureToLeetCode | /problem_27.py | UTF-8 | 552 | 3.484375 | 3 | [] | no_license | class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
end = len(nums)
index = 0 # [index...end]
while index < end:
if nums[index] == val:
nums[index], nums[end-1] = nums[end-1], nums[index]
end -= 1
else:
index += 1
return index
solution = Solution()
nums = [0,1,2,2,3,0,4,2]
val = 2
res = solution.removeElement(nums, val)
print(res)
print(nums)
| true |
fe4b7a4144d3578242b783289e5e417c436926a8 | Python | m-rahimi/Phyton | /Basic/set.py | UTF-8 | 3,037 | 3.734375 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 26 00:37:12 2017
@author: Amin
"""
#A set is an unordered collection of elements without duplicate entries.
print set()
print set('HackerRank')
print set([1,2,1,2,3,4,5,6,0,9,12,22,3])
print set((1,2,3,4,5,5))
print set(set(['H','a','c','k','e','r','r','a','n','k']))
print set({'Hacker' : 'DOSHI', 'Rank' : 616 })
print set(enumerate(['H','a','c','k','e','r','r','a','n','k']))
# create a set
myset = {1, 2} # Directly assigning values to a set
myset = set() # Initializing a set
myset = set(['a', 'b']) # Creating a set from a list
print myset
#MODIFYING SETS
myset.add('c')
myset.add('a') # As 'a' already exists in the set, nothing happens
myset.add((5, 4))
print myset
myset.update([1, 2, 3, 4]) # update() only works for iterable objects
print myset
myset.update({1, 7, 8})
print myset
myset.update({1, 6}, [5, 13])
print myset
#Both the discard() and remove() functions take a single value as an argument and removes
#that value from the set. If that value is not present, discard() does nothing,
#but remove() will raise a KeyError exception.
myset.discard(10)
print myset
myset.remove(13)
print myset
#COMMON SET OPERATIONS
a = {2, 4, 5, 9}
b = {2, 4, 11, 12}
print a.union(b) # Values which exist in a or b
print a.intersection(b) # Values which exist in a and b
print a.difference(b) # Values which exist in a but not in b
print a.symmetric_difference(b) # Values which exist in a or b but not in both
a.union(b) == b.union(a)
a.intersection(b) == b.intersection(a)
a.difference(b) == b.difference(a)
#Print symetric difference
# ^ symbol can also be used to compute the symmetric difference of two sets.
m = raw_input().split()
n = raw_input().split()
print "\n".join(sorted(list(set(m) ^ set(n)),key=int))
# if AR elements in AR1 add 1, if in AR2 add -1 to happiness
AR = map(int,raw_input().split())
AR1 = set(map(int,raw_input().split()))
AR2 = set(map(int,raw_input().split()))
inter = [ k for k in AR if k in AR1]
l1 = len(inter)
inter2 = [ k for k in AR if k in AR2]
l2 = len(inter2)
print l1-l2
#You have a non-empty set S, and you have to execute N commands given in N lines.
if __name__ == '__main__':
n = int(input())
s = set(map(int,raw_input().split()))
n = int(input())
for i in xrange(n):
lst = raw_input().split()
eval('s.'+lst[0]+'('+",".join(lst[1:]) +")")
print(sum(s))
# union of two sets
#input format
#9
#1 2 3 4 5 6 7 8 9
#9
#10 1 2 3 11 21 55 6 8
a,b=[set(list(map(int,raw_input().split(" ")))) for _ in range(4)][1::2]
print(len(a.union(b)))
#Set Mutations
H = set("Hacker")
R = set("Rank")
H.update(R)
H.intersection_update(R)
H.difference_update(R)
H.symmetric_difference_update(R)
A = set(map(int, raw_input().split()))
for _ in range(int(raw_input())):
cmd = raw_input().split()
temp = set(map(int, raw_input().split()))
eval("A.{0}(temp)".format(cmd[0]))
print sum(A)
| true |
3c867aa28abdc1586c0d4e94922446459df6e5ad | Python | vinaysankar30/Python-Programs | /untitled29.py | UTF-8 | 337 | 3.453125 | 3 | [] | no_license | class School:
def __init__(self,name,roll,mark):
self.name = name
self.roll = roll
self.mark = mark
def Add(self):
c = []
a = input("name")
b = input("roll")
c = input("marks")
d = School(a,b,c)
c.append(d)
x = School("c",5,6)
x.Add() | true |
4197725b80e15e91535cbb4f66a3a48d7cb793ea | Python | Ranganath395/ds_lab | /Code/speech_scrape.py | UTF-8 | 2,351 | 2.625 | 3 | [] | no_license | from selenium import webdriver
import time
from bs4 import BeautifulSoup, SoupStrainer
from tqdm import tqdm
import requests
import re
import os.path
def cleaned(url):
req = requests.get(url)
#print(req)
content = req.text
first_idx = content.find('<div class=\'news-bg\'>')
#print(first_idx)
end_idx = content.find('</div><div class=\"tweet-container\" >')
if end_idx == -1:
end_idx = content.find('</div><style>.says{display:none;}</style>')
#print(end_idx)
#print(end_idx)
MyText = content[first_idx:end_idx]
CLEANR = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
cleantext = re.sub(CLEANR, '',MyText)
return cleantext
if(os.path.exists('output.txt') == False):
url = 'https://www.pmindia.gov.in/en/mann-ki-baat/'
my_links = []
driver = webdriver.Firefox()
driver.get(url)
driver.implicitly_wait(20)
SCROLL_PAUSE_TIME = 3
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
soup_file = driver.page_source
#print(soup_file)
for link in BeautifulSoup(soup_file,features="lxml", parse_only = SoupStrainer('a') ):
if link.has_attr('href'):
if 'mann-ki-baat' in link['href']:
my_links.append(link['href'])
with open("output.txt", "w") as txt_file:
for line in my_links:
txt_file.write("".join(line) + "\n")
else:
my_links = open('output.txt').readlines()
my_links.reverse()
filename = open("filename.txt").readlines()
mydict = {}
f = open("data.json","w+")
for i in range(len(filename)):
filename[i] = filename[i].replace('\n','')
for i in tqdm(range(0,len(my_links)-1)):
my_text = cleaned(my_links[i])
#file_name = filename[i]+'.txt'
#f = open(file_name, "w", encoding = 'utf-8')
#f.write(my_text)
#f.close()
mydict[filename[i]] = my_text
json.dump(mydict, f)
| true |
41634f6bc9e461d25bd9417cadc741537ce244e7 | Python | kazarinoff/python_nov_2018 | /zach_kaz/mathdojoZK.py | UTF-8 | 723 | 3.90625 | 4 | [] | no_license | # def varargs(arg1, *args):
# print("Got "+arg1+" and "+ ", ".join(args))
# varargs("one") # output: "Got one and "
# varargs("one", "two") # output: "Got one and two"
# varargs("one", "two", "three") # output: "Got one and two, three"
# varargs("one","two","three","four","infinity")
class MathDojo:
def __init__(self):
self.value=0
def add(self,arg1,*args):
self.value+=arg1+sum(args)
return self
def subtract(self,arg1,*args):
self.value-=(arg1+sum(args))
return self
def result(self):
return self.value
md=MathDojo()
x = md.add(2).add(2,5,1).subtract(3,2).result()
print(x)
# print(something.value)
# something.add(3,4,5,6)
# print(something.value) | true |
b77f18bb75275333daf386cf5d364b3f57e1387e | Python | stevenwongso/Python_Fundamental_DataScience | /0 Python Fundamental/31a_json.py | UTF-8 | 408 | 3.890625 | 4 | [] | no_license |
# JSON is a syntax for storing and exchanging data.
# JSON is text, written with JavaScript object notation.
import json
x = '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x) # convert json to python dictionary
print(y)
print(y["age"])
################################
x = {
"name": "John",
"age": 30,
"city": "New York"
}
y = json.dumps(x) # convert python to json
print(y) | true |
aea5ca1a7d3c0f6ce42aa2d6b1ff9431a8934a6b | Python | benjaclaessens/pyGAPS | /src/pygaps/parsing/excel.py | UTF-8 | 11,814 | 2.609375 | 3 | [
"MIT"
] | permissive | """
Parse to and from a Excel format for isotherms.
The _parser_version variable documents any changes to the format,
and is used to check for any deprecations.
"""
import ast
import warnings
import pandas
import xlrd
import xlwt
from pygaps.core.baseisotherm import BaseIsotherm
from pygaps.core.modelisotherm import ModelIsotherm
from pygaps.core.pointisotherm import PointIsotherm
from pygaps.modelling import model_from_dict
from pygaps.utilities.exceptions import ParsingError
from .bel_excel import read_bel_report
from .mic_excel import read_mic_report
_parser_version = "2.0"
_FIELDS = {
'material': {
'text': ['Material name'],
'name': 'material',
'row': 0,
'column': 0,
},
'temperature': {
'text': ['Experiment temperature (K)'],
'name': 'temperature',
'row': 1,
'column': 0,
},
'adsorbate': {
'text': ['Adsorbate used'],
'name': 'adsorbate',
'row': 2,
'column': 0,
},
'pressure_mode': {
'text': ['Pressure mode'],
'name': 'pressure_mode',
'row': 3,
'column': 0,
},
'pressure_unit': {
'text': ['Pressure unit'],
'name': 'pressure_unit',
'row': 4,
'column': 0,
},
'loading_basis': {
'text': ['Loading basis'],
'name': 'loading_basis',
'row': 5,
'column': 0,
},
'loading_unit': {
'text': ['Loading unit'],
'name': 'loading_unit',
'row': 6,
'column': 0,
},
'material_basis': {
'text': ['Material basis'],
'name': 'material_basis',
'row': 7,
'column': 0,
},
'material_unit': {
'text': ['Material unit'],
'name': 'material_unit',
'row': 8,
'column': 0,
},
'isotherm_data': {
'text': ['Isotherm type'],
'name': 'isotherm_data',
'row': 9,
'column': 0,
},
}
_FORMATS = ['bel', 'mic']
def isotherm_to_xl(isotherm, path):
"""
Save an isotherm to an excel file.
Parameters
----------
isotherm : Isotherm
Isotherm to be written to excel.
path : str
Path to the file to be written.
"""
# create a new workbook and select first sheet
wb = xlwt.Workbook()
sht = wb.add_sheet('data')
# get the required dictionaries
iso_dict = isotherm.to_dict()
iso_dict['file_version'] = _parser_version # version
# Add the required named properties
prop_style = xlwt.easyxf(
'align: horiz left; pattern: pattern solid, fore_colour grey25;'
)
for field in _FIELDS.values():
val = iso_dict.pop(field['name'], None)
sht.write(field['row'], field['column'], field['text'][0], prop_style)
if val:
sht.write(field['row'], field['column'] + 1, val, prop_style)
# Get the isotherm type header
type_row = _FIELDS['isotherm_data']['row']
type_col = _FIELDS['isotherm_data']['column']
col_width = 256 * 25 # 25 characters wide (-ish)
sht.col(type_col).width = col_width
sht.col(type_col + 1).width = col_width
if isinstance(isotherm, PointIsotherm):
# Write the type
sht.write(type_row, type_col + 1, 'data', prop_style)
# Get the data row
data_row = type_row + 1
# Generate the headings
headings = [isotherm.loading_key, isotherm.pressure_key]
headings.extend(isotherm.other_keys)
# We also write the branch data
headings.append('branch')
data = isotherm.data_raw[headings]
data['branch'] = data['branch'].replace(False,
'ads').replace(True, 'des')
# Write all data
for col_index, heading in enumerate(headings):
sht.write(data_row, col_index, heading)
for row_index, datapoint in enumerate(data[heading]):
sht.write(data_row + row_index + 1, col_index, datapoint)
if isinstance(isotherm, ModelIsotherm):
# Write the type
sht.write(type_row, type_col + 1, 'model', prop_style)
# Get the model row
model_row = type_row
# Generate the headings (i know it's a lame way to do it)
sht.write(model_row + 1, 0, 'Model name')
sht.write(model_row + 1, 1, isotherm.model.name)
sht.write(model_row + 2, 0, 'RMSE')
sht.write(model_row + 2, 1, isotherm.model.rmse)
sht.write(model_row + 3, 0, 'Pressure range')
sht.write(model_row + 3, 1, str(isotherm.model.pressure_range))
sht.write(model_row + 4, 0, 'Loading range')
sht.write(model_row + 4, 1, str(isotherm.model.loading_range))
sht.write(model_row + 5, 0, 'Model parameters')
model_row = model_row + 5
for row_index, param in enumerate(isotherm.model.params):
sht.write(model_row + row_index + 1, 0, param)
sht.write(
model_row + row_index + 1, 1, isotherm.model.params[param]
)
# Now add the other keys
sht = wb.add_sheet('otherdata')
row = 0
col = 0
for prop in iso_dict:
sht.write(row, col, prop)
sht.write(row, col + 1, iso_dict[prop])
row += 1
wb.save(path)
def isotherm_from_xl(path, fmt=None, **isotherm_parameters):
"""
Load an isotherm from an Excel file.
Parameters
----------
path : str
Path to the file to be read.
fmt : {None, 'mic', 'bel'}, optional
The format of the import for the isotherm.
isotherm_parameters :
Any other options to be overridden in the isotherm creation.
Returns
-------
Isotherm
The isotherm contained in the excel file.
"""
if fmt:
if fmt not in _FORMATS:
raise ParsingError('Format not supported')
# isotherm type (point/model)
isotype = 0
raw_dict = {
'pressure_key': 'pressure',
'loading_key': 'loading',
}
if fmt == 'mic':
meta, data = read_mic_report(path)
isotype = 1
raw_dict.update(meta)
data = pandas.DataFrame(data)
# TODO pyGAPS does not yet handle saturation pressure recorded at each point
# Therefore, we use the relative pressure column as our true pressure,
# ignoring the absolute pressure column
if 'pressure_relative' in data.columns:
data['pressure'] = data['pressure_relative']
data = data.drop('pressure_relative', axis=1)
raw_dict['other_keys'].remove('pressure_relative')
raw_dict['pressure_mode'] = 'relative'
raw_dict['pressure_unit'] = None
elif fmt == 'bel':
meta, data = read_bel_report(path)
isotype = 1
raw_dict.update(meta)
data = pandas.DataFrame(data)
# TODO pyGAPS does not yet handle saturation pressure recorded at each point
# Therefore, we use the relative pressure column as our true pressure,
# ignoring the absolute pressure column
if 'pressure_relative' in data.columns:
data['pressure'] = data['pressure_relative']
data = data.drop('pressure_relative', axis=1)
raw_dict['other_keys'].remove('pressure_relative')
raw_dict['pressure_mode'] = 'relative'
raw_dict['pressure_unit'] = None
else:
# Get excel workbook and sheet
wb = xlrd.open_workbook(path)
if 'data' in wb.sheet_names():
sht = wb.sheet_by_name('data')
else:
sht = wb.sheet_by_index(0)
# read the main isotherm parameters
for field in _FIELDS.values():
raw_dict[field['name']
] = sht.cell(field['row'], field['column'] + 1).value
# find data/model limits
type_row = _FIELDS['isotherm_data']['row']
if sht.cell(type_row, 1).value.lower().startswith('data'):
# Store isotherm type
isotype = 1
header_row = type_row + 1
start_row = header_row + 1
final_row = start_row
while final_row < sht.nrows:
point = sht.cell(final_row, 0).value
if point == '':
break
final_row += 1
# read the data in
header_col = 0
headers = []
experiment_data = {}
while header_col < sht.ncols:
header = sht.cell(header_row, header_col).value
if header == '':
break
headers.append(header)
experiment_data[header] = [
sht.cell(i, header_col).value
for i in range(start_row, final_row)
]
header_col += 1
data = pandas.DataFrame(experiment_data)
raw_dict['loading_key'] = headers[0]
raw_dict['pressure_key'] = headers[1]
raw_dict['other_keys'] = [
column for column in data.columns.values if column not in
[raw_dict['loading_key'], raw_dict['pressure_key'], 'branch']
]
# process isotherm branches if they exist
if 'branch' in data.columns:
data['branch'] = data['branch'].apply(
lambda x: False if x == 'ads' else True
)
else:
raw_dict['branch'] = 'guess'
if sht.cell(type_row, 1).value.lower().startswith('model'):
# Store isotherm type
isotype = 2
model = {
"name": sht.cell(type_row + 1, 1).value,
"rmse": sht.cell(type_row + 2, 1).value,
"pressure_range":
ast.literal_eval(sht.cell(type_row + 3, 1).value),
"loading_range":
ast.literal_eval(sht.cell(type_row + 4, 1).value),
"parameters": {},
}
final_row = type_row + 6
while final_row < sht.nrows:
point = sht.cell(final_row, 0).value
if point == '':
break
model["parameters"][point] = sht.cell(final_row, 1).value
final_row += 1
# read the secondary isotherm parameters
if 'otherdata' in wb.sheet_names():
sht = wb.sheet_by_name('otherdata')
row_index = 0
while row_index < sht.nrows:
namec = sht.cell(row_index, 0)
valc = sht.cell(row_index, 1)
if namec.ctype == xlrd.XL_CELL_EMPTY:
break
if valc.ctype == xlrd.XL_CELL_BOOLEAN:
val = bool(valc.value)
elif valc.ctype == xlrd.XL_CELL_EMPTY:
val = None
else:
val = valc.value
raw_dict[namec.value] = val
row_index += 1
# Put data in order
version = raw_dict.pop("file_version", None)
if not version or float(version) < float(_parser_version):
warnings.warn(
f"The file version is {version} while the parser uses version {_parser_version}. "
"Strange things might happen, so double check your data."
)
raw_dict.pop('isotherm_data') # remove useless field
# version check
raw_dict.pop('iso_id', None) # make sure id is not passed
# Update dictionary with any user parameters
raw_dict.update(isotherm_parameters)
if isotype == 1:
return PointIsotherm(isotherm_data=data, **raw_dict)
if isotype == 2:
return ModelIsotherm(model=model_from_dict(model), **raw_dict)
return BaseIsotherm(**raw_dict)
| true |
575ee8f7f332e0c392e97c1848413c20900e7f92 | Python | himangshupal719/atbswp_python_programming | /practice_questions/chapter_7/watanabeRegex.py | UTF-8 | 324 | 3.4375 | 3 | [] | no_license | import re
nameList = ['Haruto Watanabe', 'Alice Watanabe', 'RoboCop Watanabe',
'haruto Watanabe' , 'Mr. Watanabe', 'Watanabe','Haruto watanabe']
nameRegex = re.compile(r'([A-Z])[a-zA-Z]*\sWatanabe')
for name in nameList:
mo = nameRegex.search(name)
if mo ==None:
print(f'{name} does not match.')
else:
print(f'{name} does match.')
| true |
940b1a1a7d5b09229573741d2ee6a54713f79716 | Python | jbarnoud/omm-top | /potentials.py | UTF-8 | 1,020 | 2.53125 | 3 | [] | no_license | import simtk.openmm as mm
from simtk.unit import Quantity
def create_c6c12(cutoff: Quantity) -> mm.CustomNonbondedForce:
potential = mm.CustomNonbondedForce(
'C12_ij/(r6^2) - C6_ij/r6; '
'r6 = r^6; '
'C6_ij = sqrt(C61*C62); '
'C12_ij = sqrt(C121*C122)'
)
potential.addPerParticleParameter('C6')
potential.addPerParticleParameter('C12')
potential.setCutoffDistance(cutoff)
potential.setNonbondedMethod(potential.CutoffPeriodic)
return potential
def create_epsilon_sigma(cutoff: Quantity) -> mm.CustomNonbondedForce:
potential = mm.CustomNonbondedForce(
'4 * epsilon_ij * (frac6^2 - frac6); '
'frac6 = (sigma_ij/r)^6; '
'epsilon_ij = sqrt(epsilon1*epsilon2); '
'sigma_ij = 0.5 * (sigma1 + sigma2)'
)
potential.addPerParticleParameter('sigma')
potential.addPerParticleParameter('epsilon')
potential.setCutoffDistance(cutoff)
potential.setNonbondedMethod(potential.CutoffPeriodic)
return potential
| true |
343690317e16c4204cadaa473c1da58f36c17c26 | Python | heylimlim/hello-world | /week3/examples/deep-deep-forest.py | UTF-8 | 11,317 | 3.390625 | 3 | [] | no_license | # an object describing our player
player = {
"name": "p1",
"score": 0,
"items" : ["milk"],
"friends" : [],
"location" : "start"
}
rooms = {
"room1" : "a forest clearing",
"room2" : "a forest path",
"room3" : "an alternate path"
}
import random # random numbers
import sys # system stuff for exiting
def rollDice(minNum, maxNum, difficulty):
# any time a chance of something might happen, let's roll a die
result = random.randint(minNum,maxNum)
print "You roll a: " + str(result) + " out of " + str(maxNum)
if result <= difficulty:
print "trying again...."
raw_input("press enter >")
rollDice(minNum, maxNum, difficulty)
return result
def printGraphic(name):
if (name == "fox"):
print ' /\ /\ '
print ' // \_// \ ____ '
print ' \_ _/ / / '
print ' / * * \ /^^^] '
print ' \_\O/_/ [ ] '
print ' / \_ [ / '
print ' \ \_ / / '
print ' [ [ / \/ _/ '
print ' _[ [ \ /_/ '
print ' '
print ' the fox '
if (name == "gem"):
print ' ____ '
print ' /\__/\ '
print ' /_/ \_\ '
print ' \ \__/ / '
print ' \/__\/ '
print ' '
print ' the gem '
if (name == "tree"):
print ' _-_ '
print ' /~~ ~~\ '
print ' /~~ ~~\ '
print ' { } '
print ' \ _- -_ / '
print ' ~ \ // ~ '
print ' _- - | | _- _ '
print ' _ - | | -_. '
print ' // \. '
print ' '
print ' i\'ts a tree ' # this one is escaped!
if (name == "ghost"):
print ' .````. ... '
print ' :o o `....`` ; '
print ' `. O :` '
print ' ``: `. '
print ' `:. `. '
print ' : `. `. '
print ' `..``... `. '
print ' `... `. '
print ' ``... `. '
print ' `````.'
print ' '
print ' not-so-scary ghost '
if (name == "title"):
print '-----------------------------------------------------------------------------'
print ' ______ _______ _______ _______ ______ _______ _______ _______ '
print '| | | || || | | | | || || | '
print '| _ || ___|| ___|| _ | | _ || ___|| ___|| _ | '
print '| | | || |___ | |___ | |_| | | | | || |___ | |___ | |_| | '
print '| |_| || ___|| ___|| ___| | |_| || ___|| ___|| ___| '
print '| || |___ | |___ | | | || |___ | |___ | | '
print '|______| |_______||_______||___| |______| |_______||_______||___| '
print ' '
print ' _______ _______ ______ _______ _______ _______ '
print '| || || _ | | || || | '
print '| ___|| _ || | || | ___|| _____||_ _| '
print '| |___ | | | || |_||_ | |___ | |_____ | | '
print '| ___|| |_| || __ || ___||_____ | | | '
print '| | | || | | || |___ _____| | | | '
print '|___| |_______||___| |_||_______||_______| |___| '
print ' '
print '-----------------------------------------------------------------------------'
def gameOver():
printGraphic("fox")
print "-------------------------------"
print "to be continued!"
print "name: " + player["name"]
print "score: " + str(player["score"])
return
def strangePath():
print "The path looks dark but you move forward anyway..."
print "You stop when you notice something shiny next to a tree."
printGraphic("tree")
raw_input("press enter >")
print "You consider your options."
print "options: [ search tree , keep going , back to clearing]"
pcmd = raw_input(">")
if (pcmd == "search tree"):
print "You search the tree..."
print "Let's roll a dice to see what happens next!"
difficulty = 10
roll = rollDice(0, 20, difficulty)
if (roll >= difficulty):
print "It looks like a magic gem. Right here in the forest!"
print "Do you take the gem?"
printGraphic("gem")
pcmd = raw_input("yes or no >")
if (pcmd == "no"):
print "You leave it there."
strangePath()
elif (pcmd == "yes"):
print "You pick it up and return to the clearing."
player["items"].append("gem")
player["score"] += 100
forestClearing()
else:
print "You leave it there."
forestClearing()
else:
print "Turns out it's nothing... oh well."
strangePath()
elif (pcmd == "keep going"):
print "You keep going forward... you have a strange feeling"
print "that you keep seeing the same trees over and over..."
strangePath()
elif (pcmd == "back to clearing"):
print "You decide to go back."
pcmd = raw_input(">")
forestClearing()
else:
print "You can't do that!"
strangePath()
def forestPath():
print "The forest path leads you down a narrow path of trees."
print "It is a very nice day."
raw_input("press enter >")
printGraphic("fox")
print "You walk for a while and see a small fox jump onto the path"
print "from the trees. 'Who travels in my woods?', says the fox."
print "...He can talk!"
raw_input("press enter >")
print "You consider your options."
if ("gem" in player["items"]):
print "options: [ look around , talk to fox , give gem, run ]"
else:
print "options: [ go back, talk to fox, run ]"
pcmd = raw_input(">")
# option 1: look at the fox
if (pcmd == "go back"):
print "You go back..."
forestClearing() # try again
# option 2: talk to the fox
elif (pcmd == "talk to fox"):
print "You try and talk to the white fox!"
print "Let's roll a dice to see what happens next!"
raw_input("press enter to roll >")
difficulty = 5
chanceRoll = rollDice(0,20,difficulty) # roll a dice between 0 and 20
# if the roll is higher than 5... 75% chance
if (chanceRoll >= difficulty):
print "It's you're lucky day! He want's to be your friend."
player["score"] += 50
else:
print "You try to talk to the fox, but... it looks at you confused."
forestPath() # try again
# nested actions and ifs
pcmd = raw_input("be friends with the white fox? yes or no >")
# yes
if (pcmd == "yes"):
print "The fox becomes your friend!"
player["friends"].append("white fox")
player["score"] = int(player["score"]) + 100 # conversion
print "Your score increased to: " + str(player["score"])
gameOver()
# no
elif (pcmd == "no"):
print "The fox runs away!"
forestPath()
# try again
else:
forestPath()
elif (pcmd == "give gem"):
print "You give the gem to the fox!"
raw_input("press enter>")
printGraphic("gem")
gameOver()
# option 3: run
elif (pcmd == "run"):
print "You run!"
forestClearing() # back to start
# try again
else:
print "I don't understand."
forestPath() # forest path
def forestClearing():
print "You stand in a forest clearing."
print "There is a path ahead of you and another path to the right."
if (("gem" in player["items"]) and not ("fox" in player["friends"])):
print "Your options: [ look around, path, trade gem with the forest ghost]"
elif ("gem" in player["items"]):
print "Your options: [ look around, path, exit ]"
else:
print "Your options: [ look around, path , other path , exit ]"
pcmd = raw_input(">") # user input
# player options
if (pcmd == "look around"):
print "You look around... the path behind you is .... gone?"
raw_input("press enter >")
forestClearing()
# path option
elif (pcmd == "path"):
print "You take the path."
raw_input("press enter >")
forestPath() # path 1
# path2 option
elif (pcmd == "other path"):
print "You take the other path."
raw_input("press enter >")
strangePath() # path 2
# exiting / catching errors and crazy inputs
elif (pcmd == "exit"):
print "you exit."
return # exit the application
elif (pcmd == "trade gem with the forest ghost"):
print "you give the gem to the ghost... hugh?"
printGraphic("ghost")
print "'tooooodaaloooooo'\", he says." # escaped
return # exit the application, secret ending
else:
print "I don't understand that"
forestClearing() # the beginning
def introStory():
# let's introduce them to our world
print "Good to see you gain! What should I call you?"
player["name"] = raw_input("Please enter your name >")
# intro story, quick and dirty (think star wars style)
print "Welcome to the deep deep forest " + player["name"] + "!"
print "The story so far..."
print "You were walking back home from dinner with your friends."
print "On the way home you see a path by your house leading into the woods."
print "You live in the city, so a path and both woods seem strange."
print "Do you decide to go for it?"
pcmd = raw_input("please choose yes or no >")
# the player can choose yes or no
if (pcmd == "yes"):
print "You walk down the path, it leads into a forest clearing..."
raw_input("press enter >")
forestClearing()
else:
print "No? ... That doesn't work here."
pcmd = raw_input("press enter >")
introStory() # repeat over and over until the player chooses yes!
# main! most programs start with this.
def main():
printGraphic("title") # call the function to print an image
introStory() # start the intro
main() # this is the first thing that happens
| true |