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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9d78520ce2125fce87e699aa14d3994d959cbfac | Python | harry1180/aws-ci-cd-lambda | /lambda_code/PreProd_AmazonConnect_DBFunction1/PreProd_AmazonConnect_DBFunction/main.py | UTF-8 | 4,591 | 2.53125 | 3 | [] | no_license |
# A lambda function to interact with AWS RDS MySQL
from __future__ import print_function
from UserHistory import *
from FetchTransactionInfo import *
import pymysql
import sys
import boto3
import os
import time
REGION = ''
rds_host= ""
name = ""
password = ""
db_name = ""
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
def main(event, context):
print ("Event data is :")
print (event)
#functionName='Fetch'
functionName = event["FunctionName"]
if functionName == 'FetchCardBalance':
print("inside fetchbalance")
result = FetchCardBalance(event)
CardBalance=result[0][0]
CardNumber=result[0][1]
response={"CardNumber":CardNumber,"CardBalance":CardBalance}
return response
if functionName == 'FetchAmountSpentOnVendorClass':
print("inside FetchAmountSpentOnVendorClass")
result = FetchAmountSpentOnVendorClass(event)
if not result:
response={"Amount":"0"}
else:
Amount=int(result[0][0])
print (Amount)
response={"Amount":Amount}
return response
elif functionName == 'FetchTransactionList':
print("inside FetchTransactionList")
result = FetchTransactionList(event)
#CardBalance=result[0][0]
responseArray = []
#response={"CardNumber":CardNumber,"CardBalance":CardBalance}
print ('result is :')
print (len(result))
for item in result:
#print ('item is :')
#print (item)
transactionid= item[0]
vendorName = item[1]
amount=item[2]
date=item[3]
card=item[4]
TransactionType=item[5]
response={"transactionId":transactionid,"vendorName":vendorName,"amount":amount,"DT":date,"card":card,"TransactionType":TransactionType}
responseArray.append(response)
print ('responseArray is :------------------------------------')
print (responseArray)
return responseArray
elif functionName == 'FetchTransactionsByType':
result = FetchTransactionsByType(event)
startDate=event["startDate"]
responseArray = []
if (startDate == 'null'):
dateAvailable = False;
else:
dateAvailable = True;
if (dateAvailable==False):
for item in result:
#print ('item is :')
#print (item)
transactionid= item[0]
vendorName = item[1]
amount=item[2]
date=item[3]
card=item[4]
TransactionType=item[5]
response={"transactionId":transactionid,"vendorName":vendorName,"amount":amount,"DT":date,"card":card,"TransactionType":TransactionType}
responseArray.append(response)
else:
print(result)
if not result:
response = {"Amount":"0"}
else:
Amount=result[0]
response = {"Amount":Amount}
responseArray.append(response)
print(responseArray);
print ('responseArray is :------------------------------------')
return responseArray
elif functionName == 'FetchAccountId':
print("inside fetchaccountid")
result = FetchAccountId(event)
AccountId=result[0][0]
response={"AccountId":AccountId}
return response
elif functionName == 'FetchVendorSpent':
#function to fetch the total amount spend on a particular vendor for a period of time
print("inside FetchVendorSpent")
result = FetchAmountSpentOnVendor(event)
if not result:
response={"Amount":"0"}
else:
Amount=int(result[0][0])
print (Amount)
response={"Amount":Amount}
return response
elif functionName == 'FetchNetEarnings':
print("inside FetchNetEarnings")
result = FetchNetEarnings(event)
Amount=int(result[0])
response={"Amount": Amount}
return response
elif functionName == 'FetchEventInfo':
print("inside FetchNetEarnings")
result = FetchInfo(event)
print (result)
return result
elif functionName == 'UpdateEventInfo':
print("inside UpdateEventInfo")
result = UpdateInfo(event)
return result
elif functionName == 'PayCardBalance':
result = PayCardBalance(event)
return {"result":result}
| true |
30630335d660d853020bfef3b1da87f0d785025c | Python | codewithgauri/HacktoberFest | /folders/LinearRegression/LG.py | UTF-8 | 1,640 | 2.921875 | 3 | [] | no_license | import numpy as np
from matplotlib import pyplot as plt
def predictValue(X,theta):
return np.sum(predict(X,theta))
def predict(X,theta):
return X@theta
def hypothesis(X,Y,theta):
X = np.append([[1]]*np.size(X,0),X,1)
return (np.transpose(theta)@X - Y)
def costFunction(X,Y,theta):
cost = X@theta - Y
J = np.sum(np.transpose(cost)@cost)
return J*(1/2*np.size(X,0))
# def valueCostFunction(X,Y,theta):
# X = np.append([[1]]*np.size(X,0),X,1)
# m = np.size((Y,0))
# n = len(X[0,:])
# J = 0
# for i in range(1,m):
# J += np.sum(hypothesis(X,Y,theta)**2)
# J /= 2*m
# return J
# def deritativeCostFunction(X,Y,theta):
# pass
def GradientDescent(X,Y, alpha = 0.003,iter = 5000):
X = np.append([[1]]*np.size(X,0),X,1) #check
m = np.size(X,0) #check
n = np.size(X,1)
J_hist = np.zeros((iter,2))
theta = np.array([[0]]*n)
preCost = costFunction(X,Y,theta)
for i in range(500):
theta = theta - (alpha / m) * (np.transpose(X)@(X@theta - Y))
cost = costFunction(X,Y,theta)
if np.round(cost,15) == np.round(preCost,15):
print('Found optimal value of costFunction at {} is {}'.format(i,cost))
#thêm tất cả các index còn lại sau khi break
J_hist[i:,0] = range(i,iter)
#giá trị J sau khi break sẽ như cũ trong những điểm còn lại
J_hist[i:,1] = cost
break
else:
J_hist[i,1] = cost
J_hist[i,0] = i
preCost = cost
yield theta
yield J_hist
| true |
9405a8ba91e36e9885d1a945a0968fcf26979b76 | Python | AlejandroSantorum/Connect4_HeuristicPrediction | /board_features.py | UTF-8 | 3,341 | 2.984375 | 3 | [] | no_license | ################################################################################
# Authors: #
# · Alejandro Santorum Varela - alejandro.santorum@estudiante.uam.es #
# alejandro.santorum@gmail.com #
# Date: Apr 14, 2019 #
# File: board_features.py #
# Project: Connect4 - Predicting heuristic values #
# Version: 1.1 #
################################################################################
from connect_4 import *
from c4_scrape import *
import threading as thr
NROWS = 6
NCOLS = 7
FEATURES_FILE = "feed_the_beast.csv"
LEGEND_FILE = "N_PIECES ALLY_MEAN_DIST OPP_MEAN_DIST ALLY_#2_BLCK ALLY_#2_EFF OPP_#2_BLCK OPP_#2_EFF ALLY_#3_BLCK ALLY_#3_EFF OPP_#3_BLCK OPP_#3_EFF\n"
lock = thr.Lock() # semaphore
def init_features_file():
f = open(FEATURES_FILE, "a")
f.write(LEGEND_FILE)
f.close()
###########################################################
# It stores in a file the board features and its points
###########################################################
def store_features(filename, features_array):
# Red light
lock.acquire()
# Writing file
f = open(filename, "a")
f.write(str(features_array)[1:len(str(features_array))-1])
f.write("\n")
f.close()
# Green light
lock.release()
###########################################################
# It checks if an array of points is empty
###########################################################
def empty_points(points_array):
for i in range(NCOLS):
if points_array[i] != '':
return False
return True
###########################################################
# It builds a board given a pattern and calculates its
# features, storing them into a file
###########################################################
def features_main(pattern, points_array):
if empty_points(points_array)==True:
board = Board(NROWS, NCOLS)
current_pattern, current_piece = board.build_pattern(pattern)
points = get_points(current_pattern)
for i in range(NCOLS):
if points[i] != '-':
# Getting child board
board.insert(current_piece, i)
# Getting features of this board
features_array = board.get_features(current_piece)
# Getting the father state
board.go_back(i)
# Adding points
features_array.append(int(points[i]))
else:
board = Board(NROWS, NCOLS)
current_pattern, current_piece = board.build_pattern(pattern)
for i in range(NCOLS):
if points_array[i] != '':
# Getting child board
board.insert(current_piece, i)
# Getting features of this board
features_array = board.get_features(current_piece)
# Getting the father state
board.go_back(i)
# Adding points
features_array.append(int(points_array[i]))
# Writing features in a file
store_features(FEATURES_FILE, features_array)
| true |
2c95758b85103d566a62ebb6a8c04ccc1b1958ec | Python | mstfakdgn/python-workouts | /audio/SoundOfAI/tensorflow_mlp.py | UTF-8 | 1,226 | 2.953125 | 3 | [] | no_license | import numpy as np
from random import random
from sklearn.model_selection import train_test_split
import tensorflow as tf
# dataset array([[0.1,0.2], [0.2,0.2]])
# output array([[0.3], [0.4]])
def generate_dataset(num_samples, test_size):
x = np.array([[random()/2 for _ in range(2)] for _ in range(num_samples)])
y = np.array([[i[0] + i[1]] for i in x])
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=test_size)
return X_train, X_test, y_train, y_test
if __name__== '__main__':
X_train, X_test, y_train, y_test = generate_dataset(5000, 0.33)
# print('X_train:',X_train, 'X_test:',X_test,'y_train:', y_train, 'Y_test',y_test)
# build model 2 -> 5 -> 1
model = tf.keras.Sequential([
tf.keras.layers.Dense(5, input_dim=2, activation="sigmoid"),
tf.keras.layers.Dense(1, activation="sigmoid")
])
# compile model
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)
model.compile(optimizer=optimizer, loss="MSE")
# train model
model.fit(X_train, y_train, epochs=100)
# evaluate model
print('\nModel evaluation:')
model.evaluate(X_test, y_test, verbose=1)
# make predictions
data = ([[0.1,0.2], [0.2,0.2]])
y_pred = model.predict(data)
print('Prediction:', y_pred)
| true |
bcf37dbc920c00661870349a26bf43145e20cda8 | Python | PhilAScript826/anime_recommendation_engine | /nlp.py | UTF-8 | 839 | 2.828125 | 3 | [] | no_license | from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
def recommender(name):
anime_df = pd.read_pickle('data.pickle')
tfidf = TfidfVectorizer(stop_words='english')
anime_df['Description']=anime_df['Description'].fillna('')
tfidf_matrix = tfidf.fit_transform(anime_df['Description'].tolist()).toarray()
dt_tfidf = pd.DataFrame(tfidf_matrix,columns = tfidf.get_feature_names()).set_index(anime_df['Title'])
target= [dt_tfidf.loc[name].values.tolist()]
final = dt_tfidf.drop(name)
results_tfidf = [cosine_similarity(target,
[final.loc[a].values.tolist()])[0][0] for a in final.index]
return tuple(anime[1] for anime in sorted(zip(results_tfidf,final.index), reverse=True)[:5]) | true |
628eefa3e3208336e8ad47d96b42738529e6adb7 | Python | audiovisual2018/Juego_Barraco | /Juego_barraco/SomeGuySomeBalls.py | UTF-8 | 19,661 | 3 | 3 | [] | no_license |
#Hecho por Juan Barraco, modificando el pong escrito por Daniel Fuentes B (https://www.pythonmania.net/es/2010/04/07/tutorial-pygame-3-un-videojuego/).
# ---------------------------
# Importacion de los módulos
# ---------------------------
import pygame
from pygame.locals import *
import os
import sys
import random
# -----------
# Constantes
# -----------
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
IMG_DIR = "imagenes"
SONIDO_DIR = "sonidos"
# ------------------------------
# Clases y Funciones utilizadas
# ------------------------------
def load_image(nombre, dir_imagen, alpha=False):
# Encontramos la ruta completa de la imagen
ruta = os.path.join(dir_imagen, nombre)
try:
image = pygame.image.load(ruta)
except:
print ("Error, no se puede cargar la imagen: ", ruta)
sys.exit(1)
# Comprobar si la imagen tiene "canal alpha" (como los png)
if alpha == True:
image = image.convert_alpha()
else:
image = image.convert()
return image
def load_sound(nombre, dir_sonido):
ruta = os.path.join(dir_sonido, nombre)
# Intentar cargar el sonido
try:
sonido = pygame.mixer.Sound(ruta)
except (pygame.error) as message:
print("No se pudo cargar el sonido:", ruta)
sonido = None
return sonido
# -----------------------------------------------
# Creamos los sprites (clases) de los objetos del juego:
class Pelota(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = load_image("bola.png", IMG_DIR, alpha=True)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
self.speed = [3, 3]
def update(self):
if self.rect.left < 0 or self.rect.right > SCREEN_WIDTH:
self.speed[0] = -self.speed[0]
if self.rect.top < 0 or self.rect.bottom > SCREEN_HEIGHT:
self.speed[1] = -self.speed[1]
self.rect.move_ip((self.speed[0], self.speed[1]))
def colision(self, objetivo):
if self.rect.colliderect(objetivo.rect): # con eso mira si choco con el objetivo
self.speed[0] = -self.speed[0]
class PelotaRapida(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = load_image("bola.png", IMG_DIR, alpha=True)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
self.speed = [6, 3]
def update(self):
if self.rect.left < 0 or self.rect.right > SCREEN_WIDTH:
self.speed[0] = -self.speed[0]
if self.rect.top < 0 or self.rect.bottom > SCREEN_HEIGHT:
self.speed[1] = -self.speed[1]
self.rect.move_ip((self.speed[0], self.speed[1]))
def colision(self, objetivo):
if self.rect.colliderect(objetivo.rect): # con eso mira si choco con el objetivo
self.speed[0] = -self.speed[0]
class PelotaRapida1(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = load_image("bola.png", IMG_DIR, alpha=True)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
self.speed = [3, 6]
def update(self):
if self.rect.left < 0 or self.rect.right > SCREEN_WIDTH:
self.speed[0] = -self.speed[0]
if self.rect.top < 0 or self.rect.bottom > SCREEN_HEIGHT:
self.speed[1] = -self.speed[1]
self.rect.move_ip((self.speed[0], self.speed[1]))
def colision(self, objetivo):
if self.rect.colliderect(objetivo.rect): # con eso mira si choco con el objetivo
self.speed[0] = -self.speed[0]
class PelotaCrece(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = load_image("bolacrece.png", IMG_DIR, alpha=True)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
self.speed = [int(random.randrange(1,6)), int(random.randrange(1,6))] #velocidad random
def update(self):
if self.rect.left < 0 or self.rect.right > SCREEN_WIDTH:
self.speed[0] = -(random.randint(7, 15)/10)*self.speed[0] #cambio de velocidad v = 0,7-1,5 v
if self.rect.top < 0 or self.rect.bottom > SCREEN_HEIGHT:
self.speed[1] = -(random.randint(7, 15)/10)*self.speed[1]
self.rect.move_ip((self.speed[0], self.speed[1]))
if self.speed[0]>10:
self.speed[0]=4
if self.speed[1]>10:
self.speed[1]=ACTIVEEVENT
def colision(self, objetivo):
if self.rect.colliderect(objetivo.rect): # con eso mira si choco con el objetivo
self.speed[0] = -(random.randint(7, 15)/10)*self.speed[0]
self.speed[1] = -(random.randint(7, 15)/10)*self.speed[1]
if self.speed[0]>10:
self.speed[0]=4
if self.speed[1]>10:
self.speed[1]=4
class PelotaBuena(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = load_image("bolabuena.png", IMG_DIR, alpha=True)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
self.speed = [int(random.randrange(1,6)), int(random.randrange(1,6))]
def update(self):
if self.rect.left < 0 or self.rect.right > SCREEN_WIDTH:
self.speed[0] = -(random.randint(7, 15)/10)*self.speed[0]
if self.rect.top < 0 or self.rect.bottom > SCREEN_HEIGHT:
self.speed[1] = -(random.randint(7, 15)/10)*self.speed[1]
self.rect.move_ip((self.speed[0], self.speed[1]))
if self.speed[0]>10:
self.speed[0]=4
if self.speed[1]>10:
self.speed[1]=4
def colision(self, objetivo):
if self.rect.colliderect(objetivo.rect): # con eso mira si choco con el objetivo
self.speed[0] = -(random.randint(7, 15)/10)*self.speed[0]
self.speed[1] = -(random.randint(7, 15)/10)*self.speed[1]
if self.speed[0]>10:
self.speed[0]=4
if self.speed[1]>10:
self.speed[1]=4
class PelotaLentaM(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = load_image("bola1.png", IMG_DIR, alpha=True)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
self.speed = [2, 2]
# self.sonido_pop = sonido_pop
def update(self):
if self.rect.left < 0 or self.rect.right > SCREEN_WIDTH:
self.speed[0] = -(random.randint(7, 15)/10)*self.speed[0]
# self.sonido_pop.play()
if self.rect.top < 0 or self.rect.bottom > SCREEN_HEIGHT:
self.speed[1] = -(random.randint(7, 15)/10)*self.speed[1]
# self.sonido_pop.play()
self.rect.move_ip((self.speed[0], self.speed[1]))
if self.speed[0]>10:
self.speed[0]=4
if self.speed[1]>10:
self.speed[1]=4
def colision(self, objetivo):
if self.rect.colliderect(objetivo.rect): # con eso mira si choco con el objetivo
self.speed[0] = -(random.randint(7, 15)/10)*self.speed[0]
self.speed[1] = -(random.randint(7, 15)/10)*self.speed[1]
if self.speed[0]>10:
self.speed[0]=4
if self.speed[1]>10:
self.speed[1]=4
class Guy(pygame.sprite.Sprite):
"Jugador"
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = load_image("guy.png", IMG_DIR, alpha=True)
self.rect = self.image.get_rect()
self.rect.centerx = 40
self.rect.centery = SCREEN_HEIGHT / 2
def humano(self):
# Controlar que la paleta no salga de la pantalla
if self.rect.bottom >= SCREEN_HEIGHT:
self.rect.bottom = SCREEN_HEIGHT
elif self.rect.top <= 0:
self.rect.top = 0
# ------------------------------
# Funcion principal del juego
# ------------------------------
def main():
game = True
pygame.init()
pygame.mixer.init()
# creamos la ventana y le indicamos un titulo:
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Some guy, some balls")
#creo fuentes y mensajes
fuente1= pygame.font.SysFont("Arial",20,True,False)
info1 = fuente1.render("Some Guy...",0,(255,255,255))
fuente2= pygame.font.SysFont("Lucida Console",25,True,False)
fuente3= pygame.font.SysFont("Lucida Console",30,True,False)
info2 = fuente1.render("...Some Balls",0,(255,255,255))
pygame.display.flip()
# cargamos los objetos
sonido_goddam = load_sound("goddamn1.wav", SONIDO_DIR)
sonido_musica = load_sound("musicBG.wav", SONIDO_DIR)
sonido_mygod = load_sound("mygod.wav", SONIDO_DIR)
sonido_big = load_sound("big.wav", SONIDO_DIR)
sonido_pop = load_sound("pop.wav", SONIDO_DIR)
sonido_woho = load_sound("woohoo.wav", SONIDO_DIR)
sonido_comeon = load_sound("comeon.wav", SONIDO_DIR)
sonido_yes = load_sound("yes.wav", SONIDO_DIR)
sonido_no = load_sound("no.wav", SONIDO_DIR)
sonidos_buenos = [sonido_woho, sonido_comeon, sonido_yes] #listas con sonidos para usar random
sonidos_malos = [sonido_goddam, sonido_mygod, sonido_goddam, sonido_mygod, sonido_no]
fondo = load_image("fondo1.png", IMG_DIR, alpha=False)
bola = Pelota(50,50)
bola2 = PelotaRapida(25,25)
bola3 = PelotaRapida(100,300)
bolam = PelotaLentaM(500,100)
bola5 = PelotaRapida1(25,25)
bolac = PelotaCrece(70,110)
bolab = PelotaBuena(150,70)
bb = Pelota(200,50)
bb1 = Pelota(400,400)
bb2 = Pelota(345,123)
player = Guy()
clock = pygame.time.Clock()
pygame.key.set_repeat(1, 25) # Activa repeticion de teclas
pygame.mouse.set_visible(False)
sonido_musica.play(10) #reproduce musica fondo
size = 1
vidas = 10
score = 0
GameOver = False #para un segundo while true (menu)
lastscore = [0] #hago una lista vacia para ir añadiendo todos los scores
lasttime = [0]
# el bucle principal del juego
while game == True:
#la intro + ultimo score
while GameOver == False:
fondo = load_image("fondo1.png", IMG_DIR, alpha=False)
infoscore = fuente2.render("Last score: "+str(lastscore[-1]),0,(255,255,255))
infotime = fuente2.render("Last time: "+str(lasttime[-1])+" sec.",0,(255,255,255))
infoplayer = fuente2.render("That's You",0,(10,10,10))
infoballm = fuente2.render("Avoid these balls",0,(10,10,10))
infoballb = fuente2.render("Get this one",0,(10,10,10))
infoPLAY = fuente3.render("press spacebar to PLAY",0,(10,10,10))
reloj= [0] #lista para los tiempos
segundos3 = pygame.time.get_ticks()/1000
player = Guy()
player.humano()
pos_mouse = pygame.mouse.get_pos()
mov_mouse = pygame.mouse.get_rel()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
GameOver = True
reloj.append(segundos3) #agrego para que empiece a contar de cero
size = 1 #resetea los parametros iniciales
vidas = 10
score = 0
pygame.mouse.set_pos([40,SCREEN_HEIGHT/2]) #te lleva el mouse a donde esta el guy
elif event.key == K_ESCAPE:
pygame.quit()
sys.exit(0)
elif event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
elif mov_mouse[1] != 0:
player.rect.centery = pos_mouse[1]
player.rect.centerx = pos_mouse[0]
bola = Pelota(50,50) #los cargo devuelta pq dps de perder no empezaban del mismo lugar
bola2 = PelotaRapida(25,25)
bola3 = PelotaRapida(100,300)
bolam = PelotaLentaM(200,50)
bola5 = PelotaRapida1(25,25)
bolac = PelotaCrece(70,110)
bolab = PelotaBuena(150,370)
bb = Pelota(500,50)
bb1 = Pelota(400,400)
bb2 = Pelota(345,123)
player = Guy()
clock = pygame.time.Clock()
screen.blit(fondo, (0, 0))
screen.blit(infoscore, (330,50))
screen.blit(infoPLAY, (320,450))
screen.blit(infotime, (330,70))
screen.blit(infoballb,(170,365))
screen.blit(infoballm,(60,60))
screen.blit(infoplayer,(60,480/2))
screen.blit(bb.image, bb.rect)
screen.blit(bb1.image, bb1.rect)
screen.blit(bb2.image, bb2.rect)
screen.blit(bola.image, bola.rect)
screen.blit(bola2.image, bola2.rect)
screen.blit(bola3.image, bola3.rect)
screen.blit(bolam.image, bolam.rect)
screen.blit(bola5.image, bola5.rect)
screen.blit(bolac.image, bolac.rect)
screen.blit(bolab.image, bolab.rect)
screen.blit(player.image, player.rect)
screen.blit(bolac.image, bolac.rect)
pygame.display.flip()
pygame.display.update()
clock.tick(60)
# Obtenemos la posicon del mouse
pos_mouse = pygame.mouse.get_pos()
mov_mouse = pygame.mouse.get_rel()
# Actualizamos los obejos en pantalla
player.humano()
bola.update()
bola2.update()
bola3.update()
bolam.update()
bola5.update()
bolac.update()
bolab.update()
bb.update()
bb1.update()
bb2.update()
# Comprobamos si colisionan los objetos
bola.colision(player)
bola2.colision(player)
bola3.colision(player)
bolam.colision(player)
bolac.colision(player)
bola5.colision(player)
bolab.colision(player)
bb.colision(player)
bb1.colision(player)
bb2.colision(player)
if bolab.rect.colliderect(player.rect):
score += 1
bolab = PelotaBuena(int(random.randrange(50,590)),int(random.randrange(50,400)))
sonidos_buenos[int(random.randrange(3))].play()
if bola.rect.colliderect(player.rect):
vidas -= 1
sonidos_malos[int(random.randrange(3))].play()
if bolac.rect.colliderect(player.rect):
size += 1
bolac = PelotaCrece(int(random.randrange(50,590)),int(random.randrange(50,400)))
sonido_big.play()
if bola3.rect.colliderect(player.rect):
vidas -= 1
sonidos_malos[int(random.randrange(3))].play()
if bola2.rect.colliderect(player.rect):
vidas -= 1
sonidos_malos[int(random.randrange(3))].play()
if bola5.rect.colliderect(player.rect):
vidas -= 1
sonidos_malos[int(random.randrange(3))].play()
if bolam.rect.colliderect(player.rect):
vidas -= 2
sonido_no.play()
killchance = int(random.randrange(10)) # 5/11 chances que te mate de una
if killchance >= 6:
vidas = 0
if bb.rect.colliderect(player.rect):
vidas -= 1
sonidos_malos[int(random.randrange(3))].play()
if bb1.rect.colliderect(player.rect):
vidas -= 1
sonidos_malos[int(random.randrange(3))].play()
if bb2.rect.colliderect(player.rect):
vidas -= 1
sonidos_malos[int(random.randrange(3))].play()
if size%2 ==0:
player.image = load_image("guy1.png", IMG_DIR, alpha=True)
else: player.image = load_image("guy.png", IMG_DIR, alpha=True)
if score == 100:
print("You win")
print("Score: ",score)
print("life/s left: ",vidas)
print("Time: ",segundos2)
GameOver = False
lastscore.append(score)
lasttime.append(int(segundos)-int(segundos3)) #tiempo desde q abrio el programa - tiempo de que juego
print(lastscore)
if vidas == 0 or vidas < 0:
print("You lose")
print("Score: ",score)
print("life/s left: ",vidas)
GameOver = False
lastscore.append(score)
lasttime.append(int(segundos)-int(segundos3))
print(lastscore)
segundos = pygame.time.get_ticks()/1000
segundos2 = pygame.time.get_ticks()/1000
tiempo = str(int(segundos)-int(segundos3)) #hago la resta tiempo que inicio el programa- tiempo que estoy jugando
segundos2 =int(segundos2)
cronometro = fuente1.render("Time: "+tiempo,0,(1,1,1))
puntaje = fuente2.render("Score: "+str(score),0, (20,20,20))
health = fuente2.render("Health: "+str(vidas),0,(20,20,20))
# Posibles entradas del teclado y mouse
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
elif event.type == pygame.KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit(0)
# Si el mouse no esta quieto mover la paleta a su posicion
elif mov_mouse[1] != 0:
player.rect.centery = pos_mouse[1]
player.rect.centerx = pos_mouse[0]
# actualizamos la pantalla
screen.blit(fondo, (0, 0))
screen.blit(info1,(5,5))
screen.blit(info2,(540,5))
screen.blit(cronometro,(300,5))
screen.blit(puntaje,(540,450))
screen.blit(health,(2,450))
screen.blit(bb.image, bb.rect)
screen.blit(bb1.image, bb1.rect)
screen.blit(bb2.image, bb2.rect)
screen.blit(bola.image, bola.rect)
screen.blit(bola2.image, bola2.rect)
screen.blit(bola3.image, bola3.rect)
screen.blit(bolam.image, bolam.rect)
screen.blit(bola5.image, bola5.rect)
screen.blit(bolac.image, bolac.rect)
screen.blit(bolab.image, bolab.rect)
screen.blit(player.image, player.rect)
pygame.display.flip()
if __name__ == "__main__":
main()
| true |
eba0eaaf2c8b11dbfe646a8b81f4ff548dd9b0e8 | Python | berleon/theano-nets | /test/test_cost.py | UTF-8 | 2,719 | 2.734375 | 3 | [
"MIT"
] | permissive | from unittest import TestCase
import math
import numpy as np
import theano
import theano.tensor as TT
from theanets.cost import NegativeLogLikelihood, QuadraticCost
class SupervisedCostTest(object):
def setUp(self):
nn_out = TT.matrix("nn_out")
self.cost_fn = theano.function([nn_out] + self.cost.inputs,
self.cost.cost(nn_out))
def test_regularization(self):
params = [TT.matrix()]
self.cost.l1 = 0.
self.cost.l2 = 0.
self.assertEqual(self.cost._regularization(params), 0.)
self.cost.l1 = 0.5
self.cost.l2 = 0.5
self.assertNotEqual(self.cost._regularization(params), 0.)
self.cost.l1 = 0.
self.cost.l2 = 0.
def test_inputs(self):
self.assertEqual(type(self.cost.inputs), list)
self.assertEqual(type(self.cost.inputs[0]), type(TT.matrix()))
def test_cost(self):
identity = np.identity(10, dtype=np.int32)
self.assertEqual(self.cost_fn(identity.astype(np.float32),
np.arange(10, dtype=np.int32)), 0)
rand = np.random.random((10, 10))
rand /= np.sum(rand, axis=1)
self.assertNotEqual(self.cost_fn(rand, np.arange(10, dtype=np.int32)), 0)
def test_accuracy(self):
output = TT.matrix("output")
acc = self.cost.accuracy(output)
acc_fn = theano.function([output] + self.cost.inputs, acc)
rand = np.random.random((1000, 10))
target = np.asarray(np.argmax(np.random.random((1000, 10)), axis=1),
dtype=np.int32)
self.assertLess(acc_fn(rand, target), 20.)
output = np.asarray([[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0],
[1, 0, 0]], dtype=np.float32)
target = np.asarray([4] * 5, dtype=np.int32)
self.assertEqual(acc_fn(output, target), 0.)
target = np.asarray([0] * 5, dtype=np.int32)
self.assertEqual(acc_fn(output, target), 100.)
class TestNegativeLogLikelihood(TestCase, SupervisedCostTest):
def setUp(self):
self.cost = NegativeLogLikelihood()
SupervisedCostTest.setUp(self)
def test_NLL(self):
p_y_given_x = np.asarray(
[[0.8, 0.2, 0],
[0.5, 0.5, 0],
[0.001, 0, 0]])
y = np.asarray( [0, 0, 0], dtype=np.int32)
self.assertEqual(self.cost_fn(p_y_given_x, y),
1.0/3.0*(-math.log(0.8) + -math.log(0.5)
+ -math.log(0.001)))
#
# class TestQuadraticCost(TestCase, SupervisedCostTest):
# def setUp(self):
# self.cost = QuadraticCost()
# SupervisedCostTest.setUp(self)
| true |
1ab8b58c742d50913793fc898ee9482a4fd1e0a7 | Python | sofrone7/Lab-de-redes-sistemas-y-servicios | /p1.2/cliente-servidor/servidor.py | ISO-8859-1 | 1,893 | 2.78125 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: cp1252 -*-
import sys
import socket
import select
if len(sys.argv) != 2:
print('Usage:', sys.argv[0], '<Server Port>\n')
ServPort = sys.argv[1]
# Socket TCP del servidor
ServSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Configurarlo para que no se bloquee
ServSock.setblocking(0)
# Unimos (bind) socket al puerto
ServSock.bind(('', int(ServPort)))
# Escucha conexiones entrantes
ServSock.listen(10) # N de conexiones posibles
# Sockets que van a ready_to_read
entrantes = [ServSock]
# Sockets que van a ready_to_write
salientes = []
try:
while entrantes:
ready_to_read, ready_to_write, error = select.select(entrantes, salientes, entrantes)
for s in ready_to_read:
if s is ServSock: #Si s es el socket del servidor aceptamos las conexiones de los clientes que entran al chat
connection, clntAddr = ServSock.accept()
print( 'Conexin con:', clntAddr)
entrantes.append(connection) # Aadimos a la lista de entrantes el nuevo cliente
else:
datos = s.recv(1024) # Cuando se reciba un mensaje
if datos:
for cliente in entrantes: # Para todos los clientes en la lista de entrantes
if cliente != ServSock and cliente != s: # Excepto el servidor y el cliente que ha mandado el mensaje
cliente.sendall(datos) #El servidor reenva el mensaje de s a cada cliente
else:
print('Ya no hay conexin con:',s.getpeername())
entrantes.remove(s) #En caso de perderse la conexin con algn cliente se le expulsa de la lista
s.close() #Y se cierra su socket asociado
except KeyboardInterrupt:
for s in ready_to_read: #Se cierran todas las conexiones en caso de cerrar el servidor
if s != ServSock:
entrantes.remove(s)
s.close() | true |
0fb6de503fae565df6fa020515ac9624b70a8731 | Python | jagadeesh1414/assignment9_note.py | /assign9_prog3.py | UTF-8 | 175 | 3.265625 | 3 | [] | no_license | a = [35,23,35,20,10,20,40,50]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items) | true |
4753fe7a28290340cc5c8dc6c8232ade67044d45 | Python | atrukhanov/routine_python | /23_nxopen_refactoring/8_check_background_color.py | UTF-8 | 2,268 | 2.640625 | 3 | [] | no_license | import NXOpen
import NXOpen.UF
import subprocess
class NXJournal:
def __init__(self):
self.session = NXOpen.Session.GetSession()
self.work_part = self.session.Parts.Work
self.lw = self.session.ListingWindow
self.uf_session = NXOpen.UF.UFSession.GetUFSession()
self.python_path = "D:\\Programs\\Python\\Python35\\python.exe"
self.script_path = "C:\\Users\\PopovAV\\Desktop\\tempWF\\Разработка\\_test_7-5-2-DONE_checkPixels.py"
self.save_part_image_path = "C:\\temp\\view-{}.jpg"
def check_background_color(self):
work_views = self.work_part.ModelingViews
bad_views = []
for i, item in enumerate(work_views):
layout = self.work_part.Layouts.FindObject("L1")
layout.ReplaceView(
self.work_part.ModelingViews.WorkView, item, True)
item.Orient(item.Name, NXOpen.View.ScaleAdjustment.Fit)
self.uf_session.Disp.CreateImage(
self.save_part_image_path.format(i),
self.uf_session.Disp.ImageFormat.BMP,
self.uf_session.Disp.BackgroundColor.ORIGINAL
)
sub_proc = subprocess.Popen(
[
self.python_path.format(i),
self.script_path,
self.save_part_image_path
]
)
sub_proc.wait()
bad_color_flag = sub_proc.communicate()
sub_proc.kill()
self.lw.WriteLine(str(bad_color_flag))
if bad_color_flag:
bad_views.append(item.Name)
if len(bad_views) == 0:
return "Закраска фона соответствует требованиям"
elif len(bad_views) == 1:
return "Закраска фона {} не соответствует требованиям".format(
"\n".join(bad_views))
elif len(bad_views) > 1:
return "Закраска фона не соответствует требованиям:\n{}".format(
"\n".join(bad_views))
def main():
app = NXJournal()
app.lw.Open()
app.lw.WriteLine(app.check_background_color())
if __name__ == "__main__":
main()
| true |
67eb3fb87f43e7c924074a240d244a559e09e8b2 | Python | ConnorJRob/Codeclan_Karaoke | /tests/room_test.py | UTF-8 | 6,661 | 3.625 | 4 | [] | no_license | import unittest
from src.room import *
from src.guest import *
from src.song import *
class TestRoom(unittest.TestCase):
def setUp(self):
self.room1 = Room(1, 6, 4.00)
self.room2 = Room(1, 3, 5.00)
def test_room_has_number(self):
#This test checks that given the Room object created above, the room.name property has been correctly setup matching 1
self.assertEqual(1, self.room1.room_number)
def test_room_has_capacity(self):
#This test checks that given the Room object created above, the room.cpacity property has been correctly setup matching 6
self.assertEqual(6, self.room1.capacity)
def test_room_starts_with_0_guest(self):
#This test checks that given the Room object created above, the room.guests_in_room property has been correctly setup as an empty list
self.assertEqual([], self.room1.guests_in_room)
def test_room_starts_with_no_songs_in_track(self):
#This test checks that given the Room object created above, the room.guests_in_room property has been correctly setup as an empty list
self.assertEqual([], self.room1.soundtrack)
def test_room_can_check_in_guests(self):
#This test checks that the check_in_guest() function is working correctly, by appending a guest object onto the guests in room list
guest_1 = Guest("Loki", 15.00, "It's my life")
guest_2 = Guest("Thor", 20.00, "The Eye of the Tiger")
self.room1.check_in_guest(guest_1)
self.room1.check_in_guest(guest_2)
self.assertEqual(2, len(self.room1.guests_in_room))
self.assertEqual("Loki", self.room1.guests_in_room[0].name)
self.assertEqual("Thor", self.room1.guests_in_room[1].name)
def test_room_can_add_songs_to_soundtrack(self):
#This test checks that add_song_to_room_soundtrack() function is working correctly, by appending a song object onto the soundtrack list
song_1 = Song("The Eye of the Tiger")
song_2 = Song("It's my life")
self.room1.add_song_to_room_soundtrack(song_1)
self.room1.add_song_to_room_soundtrack(song_2)
self.assertEqual(2, len(self.room1.soundtrack))
self.assertEqual("The Eye of the Tiger", self.room1.soundtrack[0].song_name)
self.assertEqual("It's my life", self.room1.soundtrack[1].song_name)
def test_find_guest_by_name_in_room(self):
#This test checks the function find_guest_by_name_in_room which will be called by other functions, the function should take a string and if this matches a guest.name property that is
##curretly in the room.guests_in_room[] list then it returns that guest object
guest_1 = Guest("Loki", 15.00, "It's my life")
guest_2 = Guest("Thor", 20.00, "The Eye of the Tiger")
self.room1.check_in_guest(guest_1)
self.room1.check_in_guest(guest_2)
searched_guest = self.room1.find_guest_by_name_in_room("Thor")
self.assertEqual("Thor", searched_guest.name)
def test_check_out_guest(self):
#This test checks that the check_out_guest function is working correctly, when given a name string it uses the find_guest_by_name_in_room function to locate a matching guest, then removes them from
## the guests_in_room list
guest_1 = Guest("Loki", 15.00, "It's my life")
guest_2 = Guest("Thor", 20.00, "The Eye of the Tiger")
self.room1.check_in_guest(guest_1)
self.room1.check_in_guest(guest_2)
self.room1.check_out_guest("Thor")
self.assertEqual(1, len(self.room1.guests_in_room))
def test_check_out_all_guests_in_room(self):
#This test checks that the check_out_all_guests_in_room() function is working correctly, when this is called for a room, it clears the entire guests_in_room list
guest_1 = Guest("Loki", 15.00, "It's my life")
guest_2 = Guest("Thor", 20.00, "The Eye of the Tiger")
guest_3 = Guest("Odin", 19.00, "American Idiot")
self.room1.check_in_guest(guest_1)
self.room1.check_in_guest(guest_2)
self.room1.check_in_guest(guest_3)
self.room1.check_out_all_guests_in_room()
self.assertEqual(0, len(self.room1.guests_in_room))
def test_room_will_not_go_over_capacity(self):
#This test checks that the updated "check_in_guest" functionality is working - it checks if the room is at the established capacity, if so it returns a string and does not append the guest
guest_1 = Guest("Loki", 15.00, "It's my life")
guest_2 = Guest("Thor", 20.00, "The Eye of the Tiger")
guest_3 = Guest("Odin", 19.00, "American Idiot")
guest_4 = Guest("Tyr", 13.00, "Wonderwall")
self.room2.check_in_guest(guest_1)
self.room2.check_in_guest(guest_2)
self.room2.check_in_guest(guest_3)
self.room2.check_in_guest(guest_4)
self.assertEqual(3, len(self.room2.guests_in_room))
self.assertEqual("I'm sorry, this room is at full capacity", self.room2.check_in_guest(guest_4))
def test_check_guest_in_and_take_payment(self):
#This test checks that the guests wallet reduces by the entry fee value of the room they are checking into
guest_1 = Guest("Loki", 15.00, "It's my life")
self.room2.check_in_guest(guest_1)
self.assertEqual(10, guest_1.wallet)
def test_deny_guest_check_in_due_to_insufficient_funds(self):
#This test checks that if the guest has insufficient funds to pay the entry fee, they are not checked in and it instead returns a failure string
guest_1 = Guest("Thor", 4.00, "The Eye of the Tiger")
self.assertEqual("I'm sorry, you do not have sufficient funds to pay the entry fee", self.room2.check_in_guest(guest_1))
self.assertEqual([],self.room2.guests_in_room)
def test_if_guest_celebrates_that_room_has_their_song(self):
#This test checks that the check_in_guest function returns the string "Awesome, this room has my favourite song!" if the room the guest is checking into has their favourite song
#on the soundtrack - in addition to adding them to the guest_list and taking their entry fee
guest_1 = Guest("Thor", 12.00, "The Eye of the Tiger")
song_1 = Song("The Eye of the Tiger")
song_2 = Song("It's my life")
self.room1.add_song_to_room_soundtrack(song_1)
self.room1.add_song_to_room_soundtrack(song_2)
result = self.room1.check_in_guest(guest_1)
self.assertEqual("Awesome, this room has my favourite song!", result)
self.assertEqual(1, len(self.room1.guests_in_room))
self.assertEqual(8, guest_1.wallet)
| true |
e66e8373cb4b8d8bffa2855c088e6ee20cea133a | Python | alfarih31/SK-FIX | /Test/test_move2.py | UTF-8 | 10,623 | 2.640625 | 3 | [] | no_license | from time import sleep, time
import math
import dronekit
from pymavlink import mavutil
print("HERE")
vehicle = dronekit.connect("/dev/ttyUSB0", baud=57600, wait_ready=False)
print("CONNECTED")
# while not vehicle.is_armable:
# print("WAITING INITIALIZING")
# sleep(1)
vehicle.mode = dronekit.VehicleMode("GUIDED")
print(vehicle.mode)
vehicle.armed = True
while not vehicle.armed:
vehicle.armed = True
print("WAITING FOR ARMED")
sleep(1)
vehicle.mode = dronekit.VehicleMode("GUIDED")
#vehicle.airspeed = 5
vehicle.simple_takeoff(alt=1)
sleep(5)
# alt_global = vehicle.location.global_frame.alt
# print(alt_global)
# alt = vehicle.location.global_relative_frame.alt
# while alt < 0.8:
# alt = vehicle.location.global_relative_frame.alt
# alt_global = vehicle.location.global_frame.alt
# print(alt_global)
# print('Altitude: %.2f'%vehicle.location.global_relative_frame.alt)
# sleep(0.5)
def condition_yaw(heading, relative=False):
if relative:
is_relative = 1 #yaw relative to direction of travel
else:
is_relative = 0 #yaw is an absolute angle
# create the CONDITION_YAW command using command_long_encode()
msg = vehicle.message_factory.command_long_encode(
0, 0, # target system, target component
mavutil.mavlink.MAV_CMD_CONDITION_YAW, #command
0, #confirmation
heading, # param 1, yaw in degrees
0, # param 2, yaw speed deg/s
1, # param 3, direction -1 ccw, 1 cw
is_relative, # param 4, relative offset 1, absolute angle 0
0, 0, 0) # param 5 ~ 7 not used
# send command to vehicle
vehicle.send_mavlink(msg)
def get_point_distance(point1, point2):
# approximate radius of earth in km
R = 6378137.0
lat1 = math.radians(point1[0])
lon1 = math.radians(point1[1])
lat2 = math.radians(point2[0])
lon2 = math.radians(point2[1])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance
def llg_from_distance(d, lat, lon, brng):
R = 6378137.0 #Radius of the Earth in Meters
brng = math.radians(brng)
lat = math.radians(lat) #Current lat point converted to radians
lon = math.radians(lon) #Current long point converted to radians
lat2 = math.asin(math.sin(lat)*math.cos(d/R) +
math.cos(lat)*math.sin(d/R)*math.cos(brng))
lon2 = lon + math.atan2(math.sin(brng)*math.sin(d/R)*math.cos(lat),
math.cos(d/R)-math.sin(lat)*math.sin(lat2))
lat2 = math.degrees(lat2)
lon2 = math.degrees(lon2)
return (lat2, lon2)
def send_attitude_target(roll_angle=0.0, pitch_angle=0.0,
yaw_angle=None, yaw_rate=0.0, use_yaw_rate=False,
thrust=0.5):
if yaw_angle is None:
# this value may be unused by the vehicle, depending on use_yaw_rate
yaw_angle = vehicle.attitude.yaw
# Thrust > 0.5: Ascend
# Thrust == 0.5: Hold the altitude
# Thrust < 0.5: Descend
msg = vehicle.message_factory.set_attitude_target_encode(
0, # time_boot_ms
1, # Target system
1, # Target component
0b00000000 if use_yaw_rate else 0b00000100,
to_quaternion(roll_angle, pitch_angle, yaw_angle), # Quaternion
0, # Body roll rate in radian
0, # Body pitch rate in radian
math.radians(yaw_rate), # Body yaw rate in radian/second
thrust # Thrust
)
vehicle.send_mavlink(msg)
def set_attitude(roll_angle = 0.0, pitch_angle = 0.0,
yaw_angle = None, yaw_rate = 0.0, use_yaw_rate = False,
thrust = 0.5, duration = 0):
send_attitude_target(roll_angle, pitch_angle,
yaw_angle, yaw_rate, False,
thrust)
start = time()
while time() - start < duration:
send_attitude_target(roll_angle, pitch_angle,
yaw_angle, yaw_rate, False,
thrust)
sleep(0.1)
# Reset attitude, or it will persist for 1s more due to the timeout
send_attitude_target(0, 0,
0, 0, True,
thrust)
def to_quaternion(roll = 0.0, pitch = 0.0, yaw = 0.0):
t0 = math.cos(math.radians(yaw * 0.5))
t1 = math.sin(math.radians(yaw * 0.5))
t2 = math.cos(math.radians(roll * 0.5))
t3 = math.sin(math.radians(roll * 0.5))
t4 = math.cos(math.radians(pitch * 0.5))
t5 = math.sin(math.radians(pitch * 0.5))
w = t0 * t2 * t4 + t1 * t3 * t5
x = t0 * t3 * t4 - t1 * t2 * t5
y = t0 * t2 * t5 + t1 * t3 * t4
z = t1 * t2 * t4 - t0 * t3 * t5
return [w, x, y, z]
# print("MISI YAWING 45")
# heading = vehicle.heading
# #target_heading = heading + 45
# #@current_yaw = math.degrees(vehicle.attitude.yaw)
# current_yaw = heading
# target_heading = current_yaw + 45
# send_attitude_target(yaw_angle=target_heading)
# d_yaw = abs(target_heading-current_yaw)
# print("Current heading: %d, target: %d"%(heading, target_heading))
# while d_yaw > 5:
# heading = vehicle.heading
# #current_yaw = math.degrees(vehicle.attitude.yaw)
# current_yaw = heading
# print("Current heading: %d, target: %d, Yaw: %.2f"%(heading, target_heading, current_yaw))
# d_yaw = abs(target_heading-current_yaw)
# attitude = vehicle.attitude
# pitch = math.degrees(attitude.pitch)
# roll = math.degrees(attitude.roll)
# send_attitude_target(yaw_angle=target_heading, pitch_angle=pitch, roll_angle=roll)
# sleep(0.1)
# print("MISI YAW")
# heading = vehicle.heading
# print(heading)
# target_heading = heading + 45
# condition_yaw(target_heading)
# sleep(4)
# print("HOVER 3 Detik 1")
# set_attitude(duration=2)
# print("MISI MAJU NO GPS")
# start_lat = vehicle.location.global_relative_frame
# print(start_lat)
# set_attitude(pitch_angle = -10, thrust = 0.5, duration = 4, yaw_angle=vehicle.heading)
# end_lat = vehicle.location.global_relative_frame
# print(end_lat)
print("HOVER 3 Detik 2")
set_attitude(duration=2)
print("MISI MAJU 2M")
location = vehicle.location.global_relative_frame
heading = vehicle.heading
while not heading:
heading = vehicle.heading
print(heading)
sleep(0.5)
targetDistance = 1
target = llg_from_distance(1, location.lat, location.lon, heading)
lat_target, lon_target = target
vehicle.simple_goto(dronekit.LocationGlobalRelative(lat_target, lon_target, alt=1))
while vehicle.mode.name == "GUIDED":
location = vehicle.location.global_relative_frame
remainingDistance = get_point_distance((lat_target, lon_target), (location.lat, location.lon))
print("Distance to target: %.3f, Heading %d, Target %.2f"%(remainingDistance, vehicle.heading,vehicle.location.global_frame.alt))
if remainingDistance <= targetDistance*0.3: #Just below target, in case of undershoot.
print("Reached target")
break
elif remainingDistance >= targetDistance*0.3:
vehicle.simple_goto(dronekit.LocationGlobalRelative(lat_target, lon_target, alt=1))
sleep(0.5)
condition_yaw(90)
sleep(3)
print("MISI MAJU 2M")
location = vehicle.location.global_relative_frame
heading = vehicle.heading
targetDistance = 3
target = llg_from_distance(3, location.lat, location.lon, heading)
lat_target, lon_target = target
vehicle.simple_goto(dronekit.LocationGlobalRelative(lat_target, lon_target, alt=1.5))
while vehicle.mode.name == "GUIDED":
location = vehicle.location.global_relative_frame
remainingDistance = get_point_distance((lat_target, lon_target), (location.lat, location.lon))
print("Distance to target: %.3f, Heading %d, Target %.2f"%(remainingDistance, vehicle.heading,vehicle.location.global_frame.alt))
if remainingDistance <= targetDistance*0.25: #Just below target, in case of undershoot.
print("Reached target")
break
elif remainingDistance >= targetDistance*0.3:
send_attitude_target(yaw_angle=heading+90)
vehicle.simple_goto(dronekit.LocationGlobalRelative(lat_target, lon_target, alt=1.5))
sleep(0.5)
print("HOVER 3 Detik 3")
set_attitude(duration=2)
print("MISI MAJU 3M")
location = vehicle.location.global_relative_frame
heading = vehicle.heading
targetDistance = 3
condition_yaw(180)
sleep(3)
location = vehicle.location.global_relative_frame
heading = vehicle.heading
target = llg_from_distance(3, location.lat, location.lon, heading)
lat_target, lon_target = target
vehicle.simple_goto(dronekit.LocationGlobalRelative(lat_target, lon_target, alt=1.5))
while vehicle.mode.name == "GUIDED":
location = vehicle.location.global_relative_frame
remainingDistance = get_point_distance((lat_target, lon_target), (location.lat, location.lon))
print("Distance to target: %.3f, Heading %d, Target %.2f"%(remainingDistance, vehicle.heading,vehicle.location.global_frame.alt))
if remainingDistance <= targetDistance*0.25: #Just below target, in case of undershoot.
print("Reached target")
break
elif remainingDistance >= targetDistance*0.3:
send_attitude_target(yaw_angle=heading+90)
vehicle.simple_goto(dronekit.LocationGlobalRelative(lat_target, lon_target, alt=1.5))
sleep(0.5)
set_attitude(duration=2)
print("MISI MAJU 3M")
location = vehicle.location.global_relative_frame
heading = vehicle.heading
targetDistance = 3
condition_yaw(90)
sleep(3)
location = vehicle.location.global_relative_frame
heading = vehicle.heading
target = llg_from_distance(3, location.lat, location.lon, heading)
lat_target, lon_target = target
vehicle.simple_goto(dronekit.LocationGlobalRelative(lat_target, lon_target, alt=1.5))
while vehicle.mode.name == "GUIDED":
location = vehicle.location.global_relative_frame
remainingDistance = get_point_distance((lat_target, lon_target), (location.lat, location.lon))
print("Distance to target: %.3f, Heading %d, Target %.2f"%(remainingDistance, vehicle.heading,vehicle.location.global_frame.alt))
if remainingDistance <= targetDistance*0.25: #Just below target, in case of undershoot.
print("Reached target")
break
elif remainingDistance >= targetDistance*0.3:
send_attitude_target(yaw_angle=heading+90)
vehicle.simple_goto(dronekit.LocationGlobalRelative(lat_target, lon_target, alt=1.5))
sleep(0.5)
set_attitude(duration=3)
print("LANDING")
vehicle.mode = dronekit.VehicleMode("LAND")
for _ in range(2):
vehicle.mode = dronekit.VehicleMode("LAND")
sleep(0.2)
| true |
99c21b5f443d0f5ae5222924db61f36383b1044d | Python | axelthorstein/university-projects | /Old Classes/Computer Science/108/A3/text_check_rhyme_scheme.py | UTF-8 | 4,161 | 2.890625 | 3 | [] | no_license | import unittest
import poetry_functions
class TestCheck_Rhyme_Scheme(unittest.TestCase):
def test_check_rhyme_scheme_example_1(self):
# Test if rhyme scheme matches poem
poem_lines = ['The first line leads off,', \
'With a gap before the next.', 'Then the poem ends.']
actual = ['The first line leads off,', \
'With a gap before the next.', 'Then the poem ends.']
actual_return = poetry_functions.check_rhyme_scheme(poem_lines, \
([5, 7, 5], ['A', 'B', 'C']), word_to_phonemes)
expected = ['The first line leads off,', \
'With a gap before the next.', 'Then the poem ends.']
expected_return = []
self.assertEqual(actual, expected)
self.assertEqual(actual_return, expected_return)
def test_check_rhyme_scheme_example_2(self):
# Test if rhyme scheme matches all but one is the same as others
poem_lines = ['The off,', \
'With next.', 'Then off.', 'Then off.']
actual = ['The off,', \
'With next.', 'Then off.', 'Then off.']
actual_return = poetry_functions.check_rhyme_scheme(poem_lines, \
([5, 7, 5], ['A', 'B', 'A', 'C']), word_to_phonemes)
expected = ['The off,', \
'With next.', 'Then off.', 'Then off.']
expected_return = [['The off,', 'Then off.', 'Then off.']]
self.assertEqual(actual, expected)
self.assertEqual(actual_return, expected_return)
def test_check_rhyme_scheme_example_3(self):
# Test if rhyme scheme matches some but not multiple
poem_lines = ['The off,', \
'With next.', 'Then ends.', 'Then ends.']
actual = ['The off,', \
'With next.', 'Then ends.', 'Then ends.']
actual_return = poetry_functions.check_rhyme_scheme(poem_lines, \
([5, 7, 5], ['A', 'B', 'A', 'C']), word_to_phonemes)
expected = ['The off,', \
'With next.', 'Then ends.', 'Then ends.']
expected_return = [['The off,', 'Then ends.'], ['Then ends.']]
self.assertEqual(actual, expected)
self.assertEqual(actual_return, expected_return)
def test_check_rhyme_scheme_example_4(self):
# Test if rhyme scheme none match
poem_lines = ['The off,', \
'With next.', 'Then ends.', 'Then ends.']
actual = ['The off,', \
'With next.', 'Then ends.', 'Then ends.']
actual_return = poetry_functions.check_rhyme_scheme(poem_lines, \
([5, 7, 5], ['A', 'B', 'A', 'B']), word_to_phonemes)
expected = ['The off,', \
'With next.', 'Then ends.', 'Then ends.']
expected_return = [['The off,', 'Then ends.'], \
['With next.', 'Then ends.']]
self.assertEqual(actual, expected)
self.assertEqual(actual_return, expected_return)
#def test_check_rhyme_scheme_example_5(self):
# Test if none are given
#poem_lines = []
#actual = []
#actual_return = poetry_functions.check_rhyme_scheme(poem_lines, \
#([], ['*', '*', '*']), word_to_phonemes)
#expected = []
#expected_return = []
#self.assertEqual(actual, expected)
#self.assertEqual(actual_return, expected_return)
word_to_phonemes = {'NEXT': ['N', 'EH1', 'K', 'S', 'T'], \
'GAP': ['G', 'AE1', 'P'], \
'BEFORE': ['B', 'IH0', 'F', 'AO1', 'R'], \
'LEADS': ['L', 'IY1', 'D', 'Z'], \
'WITH': ['W', 'IH1', 'DH'], \
'LINE': ['L', 'AY1', 'N'], \
'THEN': ['DH', 'EH1', 'N'], \
'THE': ['DH', 'AH0'], \
'A': ['AH0'], \
'FIRST': ['F', 'ER1', 'S', 'T'], \
'ENDS': ['EH1', 'N', 'D', 'Z'], \
'POEM': ['P', 'OW1', 'AH0', 'M'], \
'OFF': ['AO1', 'F']}
if __name__ == '__main__':
unittest.main(exit=False) | true |
be0cd60d399e3078a68cf03086aa8a979933088d | Python | mfrankovic0/pythoncrashcourse | /Chapter 9/9-1_restaurant.py | UTF-8 | 614 | 3.921875 | 4 | [] | no_license | class Restaurant:
"""A restaurant model."""
def __init__(self, name, kind):
"""Initialize name and type."""
self.restaurant_name = name
self.cuisine_kind = kind
def describe_restaurant(self):
"""Describes restaurant name and type."""
print(f"{self.restaurant_name} is a restaurant that serves {self.cuisine_kind}.")
def open_restaurant(self):
"""Indicates if restaurant is open."""
print(f"{self.restaurant_name} is open.")
restaurant = Restaurant('Taco Bell', 'Mexican')
restaurant.describe_restaurant()
restaurant.open_restaurant() | true |
9fc74366cf2f61150133631f0c4d13183ab18ce3 | Python | GorillaFu/holbertonschool-higher_level_programming | /0x0A-python-inheritance/10-square.py | UTF-8 | 1,161 | 3.421875 | 3 | [] | no_license | #!/usr/bin/python3
"""
square + rectangle subclass of basegeometry class
"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
"""
rectanngle class that inherits attributes from BaseGeometry
"""
def __init__(self, width, height):
self.__width = width
self.__height = height
super().integer_validator("width", width)
super().integer_validator("height", height)
def __str__(self):
"""
return string representation
"""
return "[Rectangle] {}/{}".format(self.__width, self.__height)
def area(self):
"""
return rect area
"""
return self.__width * self.__height
class Square(Rectangle):
"""
square class based on rectangle class
"""
def __init__(self, size):
"""
constructor
"""
self.__size = size
def area(self):
"""
return area
"""
return self.__size * self.__size
def __str__(self):
"""
return str representation
"""
return "[Rectangle] {}/{}".format(self.__size, self.__size)
| true |
4ee355b6bf941df86f9743d3dd7cc5faf9ae916d | Python | QUER01/FinanceModule | /src/app.py | UTF-8 | 767 | 3.015625 | 3 | [] | no_license | import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
import numpy as np
import pandas as pd
data = pd.read_csv(r'data/etf_20200217/df_backtest_portfolio.csv', sep = ';')
# LAYING OUT THE TOP SECTION OF THE APP
row1_1, row1_2 = st.beta_columns((2,3))
with row1_1:
st.title("ETF Portfolio")
portfolio_type_selected = st.selectbox(
'Portfolio Type',
data['portfolio_type'].unique())
with row1_2:
st.write(
"""
##
text
text
""")
# FILTERING DATA FOR THE HISTOGRAM
filtered = data[data['portfolio_type'] == portfolio_type_selected]
st.bar_chart(filtered[['profit','annual_volatility']])
with st.echo():
def calculation1():
print('hello')
| true |
66bf6ab5d68cfeab850235fc52b69ae7abc09c76 | Python | VibhuJawa/custrings | /python/tests/test_rmm.py | UTF-8 | 1,654 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | from librmm_cffi import librmm as rmm
from librmm_cffi import librmm_config as rmm_cfg
# setup rmm to use memory pool
rmm_cfg.use_pool_allocator = True
rmm_cfg.initial_pool_size = 2<<30 # set to 2GiB. Default is 1/2 total GPU memory
rmm_cfg.use_managed_memory = False # default is false
rmm_cfg.enable_logging = True
rmm.initialize()
import nvstrings
#
strs = nvstrings.to_device(["Hello","there","world",None,"1234","-123.4","accénted",""])
print(strs)
# case
print(".lower():",strs.lower())
print(".upper():",strs.upper())
print(".swapcase():",strs.swapcase())
print(".capitalize():",strs.capitalize())
print(".title():",strs.title())
# combine
print(".cat([1,2,3,4,5,6,é,nil]:",strs.cat(["1","2","3","4","5","6","é",None]))
print(".join(:):",strs.join(sep=':'))
# compare
print(".compare(there):",strs.compare("there"))
print(".find(o):",strs.find('o'))
print(".rfind(e):",strs.rfind('e'))
# convert
print(".stoi():",strs.stoi())
print(".stof():",strs.stof())
print(".hash():",strs.hash())
# pad
print(".pad(8):",strs.pad(8))
print(".zfill(7):",strs.zfill(7))
print(".repeat(2):",strs.repeat(2))
# strip
print(".strip(e):",strs.strip('e'))
# slice
print(".slice(2,4):",strs.slice(2,4))
print(".slice_replace(2,4,z):",strs.slice_replace(2,4,'z'))
print(".replace(e,é):",strs.replace('e','é'))
# split
nstrs = strs.split("e")
print(".split(e):")
for s in nstrs:
print(" ",s)
nvstrings.free(s) # very important
nstrs = None
# this will free the strings object which deallocates from rmm
# this is important because rmm may be destroyed before the strings are
strs = None
#print(rmm.csv_log())
# not necessary here
#rmm.finalize() | true |
a2c8170fbd7fa0512cbf443b3e4e5383397dc437 | Python | MaximusKorea/data_structure | /Stack/Stack1.py | UTF-8 | 631 | 4.03125 | 4 | [
"MIT"
] | permissive | # Stack은 나중에 들어간 것이 먼저 나온다.
# push : 데이터 스택에 쌓임, pop : 데이터 스택에서 꺼냄
# 스택은 최대로 쌓을 수 있는 공간을 정해두어야 하기 때문에 공간의 낭비가 발생할 수 있다.
# list로 stack 구현해보기(원래 list에는 append와 pop 메서드가 있어 그것을 통해서 stack을 구현할 수 있다.)
test_stack = list()
def push(num):
test_stack.append(num)
def pop():
num = test_stack[-1]
del test_stack[-1]
return num
for i in range(5):
push(i)
for i in range(len(test_stack)):
print(test_stack.pop(),end=" ") | true |
d0022e87bd887c889c6b86a228f043b925fa8c0b | Python | ToLoveToFeel/LeetCode | /Python/_0342_Power_of_Four/Solution.py | UTF-8 | 532 | 3.1875 | 3 | [] | no_license | # coding=utf-8
# Date: 2021/5/31 8:50
# 执行用时:36 ms, 在所有 Python3 提交中击败了89.43%的用户
# 内存消耗:14.7 MB, 在所有 Python3 提交中击败了79.74%的用户
class Solution:
def isPowerOfFour(self, n: int) -> bool:
if n <= 0:
return False
r = int(n ** 0.5)
if r * r != n:
return False
return (1 << 30) % n == 0
if __name__ == "__main__":
print(Solution().isPowerOfFour(16)) # True
print(Solution().isPowerOfFour(8)) # False
| true |
20dd7830c483ca5d9bbb33ca4acaac22565c72d0 | Python | nguyendachungphu/Mediapipe-With-CNN | /processingData.py | UTF-8 | 433 | 2.71875 | 3 | [] | no_license | import numpy as np
import cv2
original_image = cv2.imread('IMG1.jpg', cv2.IMREAD_COLOR)
gray_original = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
background_image = cv2.imread('IMG2.jpg', cv2.IMREAD_COLOR)
gray_background = cv2.cvtColor(background_image, cv2.COLOR_BGR2GRAY)
foreground = np.absolute(gray_original - gray_background)
foreground[foreground > 0] = 255
cv2.imshow('Original Image', foreground)
cv2.waitKey(0)
| true |
b4787d4e9244cf380d64918b8bde4a1c69fb0434 | Python | microsoft/aerial_wildlife_detection | /modules/FileServer/app.py | UTF-8 | 2,433 | 2.6875 | 3 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | '''
Serves files, such as images, from a local directory.
2019-21 Benjamin Kellenberger
'''
import os
from bottle import static_file, abort
from util.cors import enable_cors
from util import helpers
class FileServer():
def __init__(self, config, app, dbConnector, verbose_start=False):
self.config = config
self.app = app
if verbose_start:
print('FileServer'.ljust(helpers.LogDecorator.get_ljust_offset()), end='')
if not helpers.is_fileServer(config):
if verbose_start:
helpers.LogDecorator.print_status('fail')
raise Exception('Not a valid FileServer instance.')
self.login_check = None
try:
self.staticDir = self.config.getProperty('FileServer', 'staticfiles_dir')
self.staticAddressSuffix = self.config.getProperty('FileServer', 'staticfiles_uri_addendum', type=str, fallback='').strip()
self._initBottle()
except Exception as e:
if verbose_start:
helpers.LogDecorator.print_status('fail')
raise Exception(f'Could not launch FileServer (message: "{str(e)}").')
if verbose_start:
helpers.LogDecorator.print_status('ok')
def loginCheck(self, project=None, admin=False, superuser=False, canCreateProjects=False, extend_session=False):
return self.login_check(project, admin, superuser, canCreateProjects, extend_session)
def addLoginCheckFun(self, loginCheckFun):
self.login_check = loginCheckFun
def _initBottle(self):
''' static routing to files '''
@enable_cors
@self.app.route(os.path.join('/', self.staticAddressSuffix, '/<project>/files/<path:path>'))
def send_file(project, path):
return static_file(path, root=os.path.join(self.staticDir, project))
@enable_cors
@self.app.get('/getFileServerInfo')
def get_file_server_info():
'''
Returns immutable parameters like the file directory
and address suffix.
User must be logged in to retrieve this information.
'''
if not self.loginCheck(extend_session=True):
abort(401, 'forbidden')
return {
'staticfiles_dir': self.staticDir,
'staticfiles_uri_addendum': self.staticAddressSuffix
} | true |
b8b948b48b953fbe30fbba71aa48ea20e8a16705 | Python | YoupengLi/leetcode-sorting | /Solutions/0062_uniquePaths.py | UTF-8 | 1,387 | 3.953125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
# @Time : 2019/4/16 0016 08:40
# @Author : Youpeng Li
# @Site :
# @File : 0062_uniquePaths.py
# @Software: PyCharm
'''
62. Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
'''
class Solution:
def uniquePaths(self, m: 'int', n: 'int') -> 'int':
if n == 0 and m == 0:
return 0
if n == 1 and m == 1:
return 1
res = [[1 for _ in range(m)] for _ in range(n)]
for i in range(1, n):
for j in range(1, m):
res[i][j] = res[i-1][j] + res[i][j-1]
return res[n-1][m-1]
if __name__ == "__main__":
a = Solution()
m = 7
n = 3
res = a.uniquePaths(m, n)
print(res) | true |
8bac45cf1001f6a58060ef5a69be3f1b0e151ad1 | Python | ContinuumIO/enaml | /enaml/widgets/menu.py | UTF-8 | 2,257 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | #------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#------------------------------------------------------------------------------
from atom.api import Bool, Typed, ForwardTyped, Unicode, observe
from enaml.core.declarative import d_
from .action import Action
from .action_group import ActionGroup
from .toolkit_object import ToolkitObject, ProxyToolkitObject
class ProxyMenu(ProxyToolkitObject):
""" The abstract definition of a proxy Menu object.
"""
#: A reference to the Menu declaration.
declaration = ForwardTyped(lambda: Menu)
def set_title(self, title):
raise NotImplementedError
def set_enabled(self, enabled):
raise NotImplementedError
def set_visible(self, visible):
raise NotImplementedError
def set_context_menu(self, context):
raise NotImplementedError
class Menu(ToolkitObject):
""" A widget used as a menu in a MenuBar.
"""
#: The title to use for the menu.
title = d_(Unicode())
#: Whether or not the menu is enabled.
enabled = d_(Bool(True))
#: Whether or not the menu is visible.
visible = d_(Bool(True))
#: Whether this menu should behave as a context menu for its parent.
context_menu = d_(Bool(False))
#: A reference to the ProxyMenu object.
proxy = Typed(ProxyMenu)
def items(self):
""" Get the items defined on the Menu.
A menu item is one of Action, ActionGroup, or Menu.
"""
allowed = (Action, ActionGroup, Menu)
return [c for c in self.children if isinstance(c, allowed)]
#--------------------------------------------------------------------------
# Observers
#--------------------------------------------------------------------------
@observe(('title', 'enabled', 'visible', 'context_menu'))
def _update_proxy(self, change):
""" An observer which updates the proxy when the menu changes.
"""
# The superclass implementation is sufficient.
super(Menu, self)._update_proxy(change)
| true |
b65fed2785f85cf2156c76ec3ff470db6a302c10 | Python | dongyn/UI-Test | /testSmoke/test_tab.py | UTF-8 | 1,745 | 2.578125 | 3 | [] | no_license | # -*- coding:utf-8 -*-
#@Time : 2019/9/16 16:02
#@Author: dongyani
#@Function: 首页的标签
import unittest
import comm.common as common
from comm.webDriver import webDriver
from pageElement.base_element_operate import base
from comm.readConfig import ReadConfig
appPackage = ReadConfig().get_config("appPackage")
list_home_tabs = ["推荐(固定)", "70年", "电影", "热剧", "财经", "综艺", "动漫", "娱乐", "知宿", "体育", "纪录", "汽车",
"文艺院线", "CRI", "真实影像", "青少", "生活", "音乐", "文化中国", "中国城市"]
class Home_tab(unittest.TestCase):
@classmethod
def setUpClass(cls):
#打开应用,进入首页
cls.driver = webDriver().get_driver()
base(cls.driver).start_app()
pass
@classmethod
def tearDownClass(cls):
cls.driver.remove_app(appPackage)
pass
# 7-14
def switch_home_tabs(self, tab):
"""在首页推荐页面,点击顶部tabs列表按钮,在列表中点击要切换的tab,等待页面刷新完成后,点击顶部tabs列表按钮,循环以上操作"""
base(self.driver).switch_home_tab(tab)
common.delayed_get_element(self.driver, 60, ("id", "dopool.player:id/image"))
page_elements = self.driver.find_elements_by_class_name("android.widget.ImageView")
self.assertTrue(len(page_elements) > 1, f"首页-{tab}页面的元素未刷新出来")
@staticmethod
def getTestFunc(tab):
def func(self):
self.switch_home_tabs(tab)
return func
def __generateTestCases():
for tab in list_home_tabs:
setattr(Home_tab, 'test_switch_home_%s' % (tab),
Home_tab.getTestFunc(tab))
__generateTestCases()
| true |
5c45d60a564752c7d9fb5c4070d7bbf9a37411f1 | Python | RashikAnsar/everyday_coding | /python_exercises/basics/11_functions.py | UTF-8 | 1,349 | 4.03125 | 4 | [] | no_license | from types import BuiltinFunctionType
########################################
###### Built-in Functions #######
########################################
# `isinstance`: it is used to check instance of variable/literal
x = ['Python', 3.9]
print(isinstance(x, list))
print(isinstance(x[0], str))
print(isinstance(x[1], float))
# `eval`: to evaluate expression from string
x = 3
print(eval('x * 2 + 5 '))
# `min`, `max`
a = [1, 8, 4, 2, 0, 6]
print(min(a))
print(max(a))
# check all elements of iterable object return logical True
all([1, 2, 3, 4, 5]) # True
all((1, 2, 3, 4, 5)) # True
all([0, 1]) # False
# check any elements of iterable object return logical True
any([0, "", 2]) # True
any([0, ""]) # False
# get the ascii value of a character
print(ord('a'))
# absolute value
print(abs(8))
print(abs(-8))
# `bin`: converts and returns the binary equivalent string of a given integer
print(bin(8))
# chr: return ascii character at given value
print(chr(97))
# CHECK DOCUMENTATION FOR MORE BUILT-IN functions
########################################
###### Custom Functions #######
########################################
# function to sum first n natural numbers
def sum_of_n(n):
return (n * (n + 1))/2
# Factorial function
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
| true |
0ff701e97dc93e7a19952c79cbc1d1e0517eb112 | Python | durgesh-agrhari/coderspree | /check_submissions.py | UTF-8 | 6,102 | 2.765625 | 3 | [] | no_license | import os
from pathlib import Path
from typing import List
from mdutils.mdutils import MdUtils
import requests
home = os.path.abspath(Path(__file__).parent)
submission_architecture = {"GettingStarted": 5}
domains = ["AR-VR", "IOT", "ML", "Android", "Web"]
class Student:
def __init__(self, name, githubID, lilbraryid, domain, year):
self.name = name
self.githubID = githubID
self.libraryid = lilbraryid
self.solved = 0
self.domain = domain
self.completed = True
self.logs = ""
self.year = year
self.fetch_img_url()
def add_questions_solved(self, count):
self.solved += count
def __repr__(self) -> str:
return f"""
Name: {self.name}
GitHubID: {self.githubID}
LibraryID: {self.libraryid}
Domain: {self.domain}
Year: {self.year}
Questions Solved: {self.solved}
Logs: {self.logs}
"""
def log_value(self, val):
self.logs += val
def fetch_img_url(self):
resp = requests.get(url=f"https://api.github.com/users/{self.githubID}")
data = resp.json()
try:
self.url = data["avatar_url"] + "&s=100"
except KeyError:
self.url = "https://avatars.githubusercontent.com/u/84376218?v=4&s=100"
def check_structure(path, student: Student):
folderName = os.listdir(path)
folderNameLowered = [x.lower() for x in folderName]
for key, value in submission_architecture.items():
if key.lower() in folderNameLowered:
solved = len(
os.listdir(
os.path.join(path, folderName[folderNameLowered.index(key.lower())])
)
)
if solved < value:
student.completed = False
student.add_questions_solved(solved)
student.log_value(
f"Completed `{solved}` with minimum `{value}` in `{key}`, "
)
else:
student.completed = False
student.log_value(f"`{key}` Folder not found, ")
def write_to_readme(filename, students_list):
mdFile = MdUtils(file_name=filename, title="Coderspree")
mdFile.new_paragraph(
mdFile.new_inline_image(
text="Status badge",
path="https://github.com/InnogeeksOrganization/coderspree/actions/workflows/checkSubmission.yml/badge.svg",
)
)
mdFile.new_line()
mdFile.new_paragraph('Please visit the [Guide](./Guide/README.md)')
mdFile.new_line()
mdFile.new_paragraph(
"Minimum problems to complete | "
+ "".join(
f"**{key}**: `{value}` | " for key, value in submission_architecture.items()
)
)
list_of_strings = ["No", "Profile", "Name", "Domain", "Year", "Solved"]
cols_count = len(list_of_strings)
mdFile.new_line()
count = 0
for x in range(len(students_list)):
student = students_list[x]
count += 1
list_of_strings.extend(
[
count,
mdFile.new_inline_image(
text=student.name,
path=student.url,
),
student.name,
student.domain,
student.year,
str(student.solved),
]
)
mdFile.new_header(level=1, title="Stats")
mdFile.new_line()
mdFile.new_table(
columns=cols_count,
rows=len(students_list) + 1,
text=list_of_strings,
text_align="center",
)
mdFile.create_md_file()
def write_to_pendingReadme(filename, students_list):
mdFile = MdUtils(file_name=filename, title="Coderspree")
list_of_strings = ["Profile", "Name", "Domain", "Solved", "Year", "logs"]
cols_count = len(list_of_strings)
mdFile.new_line()
for x in range(len(students_list)):
student = students_list[x]
list_of_strings.extend(
[
mdFile.new_inline_image(
text=student.name,
path=student.url,
),
student.name,
student.domain,
str(student.solved),
student.year,
student.logs,
]
)
mdFile.new_line()
mdFile.new_table(
columns=cols_count,
rows=len(students_list) + 1,
text=list_of_strings,
text_align="center",
)
mdFile.create_md_file()
completed_student_list: List[Student] = []
incompleted_student_list: List[Student] = []
for domain in domains:
for filename in os.listdir(os.path.join(home, domain)):
year = "Invalid Foldername"
name = "Invalid Foldername"
libId = "Invalid Foldername"
githubid = "Invalid Foldername"
try:
[githubid, name, lidID, year] = filename.split("_")
except ValueError:
print(filename, "is not correct")
if name == "Invalid Foldername":
try:
[githubid, name, lidID] = filename.split("_")
except ValueError:
print(filename, "is not correct")
student = Student(name, githubid, lidID, domain, year)
check_structure(os.path.join(home, os.path.join(domain, filename)), student)
if student.completed:
completed_student_list.append(student)
else:
incompleted_student_list.append(student)
incompleted_student_list.sort(key=lambda x: x.solved, reverse=True)
completed_student_list.sort(key=lambda x: x.solved, reverse=True)
write_to_readme("README.md", completed_student_list)
write_to_pendingReadme("PendingStudents.md", incompleted_student_list)
print("============================COMPLETE STUDENTS LOGS============================")
for student in completed_student_list:
print(student)
# print to github actions
print(
"============================INCOMPLETE STUDENTS LOGS============================"
)
for student in incompleted_student_list:
print(student)
| true |
74f00b6d23721d1e0c8481876ae9dc3d3370a08b | Python | noronhafamily/noronhafamily.github.io | /pythonprograms/firstprogram.py | UTF-8 | 546 | 3.984375 | 4 | [] | no_license | import random
def main():
program2()
def program2():
secret_number = random.randint(1,9)
turns=3
while turns>0:
print("You have ",turns, "turn(s)")
num = int(input("Guess a number between one to ten"))
if num == secret_number:
print("good job! the number is ",num,",")
break
else:
print("incorrect. guess again")
turns = turns-1
if turns==0:
print("ooops the number is ",secret_number)
if __name__ == "__main__":
main()
| true |
f79d2a0206cddd9d3c58b23b3ec1a230cce7889e | Python | Myeishamadkins/What_Do_You_do | /what_do_you_do.py | UTF-8 | 2,438 | 3.390625 | 3 | [] | no_license | def main():
# if name == 'Glen Evens' or name == 'Kagan Coughlin':
# print('Co-Founder')
# elif name == 'Bethany Copper' or name == 'Sage Nichols' or name == 'John Marsalis':
# print('Founding Trustee')
# elif name == 'Caral Lewis':
# print('Trustee')
# elif name == 'Sean Anthony':
# print('Director')
# elif name == 'Nate Clark':
# print('Technical Director')
# elif name == 'Cole Anderson' or name == 'Timothy Bowling' or name == 'Logan Harrell' or name == 'Desma Hervey' or name == 'Ginger Keys' or name == 'Matt Lipsey' or name == 'Myeisha Madkins' or name == 'Henry Moore' or name == 'John Morgan' or name == 'Irma Patton' or name == 'Danny Peterson' or name == 'Jakylan Standifer' or name == 'Justice Taylor' or name == 'Ray Turner' or name == 'Cody van der Poel' or name == 'Andrew Wheeler':
# print('Current Student')
# elif name == 'Alexandra Fortner' or name == 'Edgar Guzman' or name == "Jo'Tavious Smith" or name == 'Jose Vargas' or name == 'Lizeth Buenrostro' or name == 'Maegan Avant' or name == 'Osvaldo Quinonez' or name == 'Sara Hester' or name == 'Shedlia Freeman' or name == 'Trey Shelton' or name == 'Valente Alvarez' or name == 'Angel Zapata':
# print('Graduated 2018')
# elif name == 'Adam Tutor' or name == 'Addey Welch' or name == 'Dustin Buice' or name == 'Eddrick Butler' or name == 'Jacob Spence' or name == 'James Hakim' or name == 'James Sibert' or name == 'Keegan Faustin' or name == 'Martin Guzman' or name == 'Milttreonna Owens' or name == 'Nicole Shelton' or name == 'Ricky Keisling':
# print('Graduated 2017')
# else:
# print('This is not a member of Base Camp. ')
person = {
'Co-Founder': {'Glen Evens', 'Kagan Coughlin'},
'Founding Trustee':
{'Bethany Cooper', 'Sage Nichols', 'John Marsalis'},
'Trustee': {'Caral Lawis'},
'Director': {'Sean Anthony'},
'Technical Director': {'Nate Clark'},
'Current Student': {
'Cole Anderson', 'Timothy Bowling', 'Logan Harrell',
'Desma Hervey', 'Ginger Keys', 'Matt Lipsey', 'Myeisha Madkins',
'Henry Moore', 'John Morgan', 'Irma Patton', 'Danny Peterson',
'Jakylan Standifer', 'Justice Taylor', 'Ray Turner',
'Cody van der Poel', 'Andrew Wheeler'
},
'Graduated 2018': {
'Alexandra Fortner', 'Edgar Guzman', "Jo'Tavious Smith",
'Jose Vargas', 'Lizeth Buenrostro', 'Maegan Avant',
'Osvaldo Quinonez', 'Sara Hester', 'Shedlia Freeman',
'Trey Shelton', 'Valente Alvarez', 'Angel Zapata'
},
'Graduated 2017': {
'Adam Tutor', 'Addey Welch', 'Dustin Buice', 'Eddrick Butler',
'Jacob Spence', 'James Hakim', 'James Sibert', 'Keegan Faustin',
'Martin Guzman', 'Milttreonna Owens', 'Nicole Shelton',
'Ricky Keisling'
}
}
name = input("Name: ")
for job, people in person.items():
if name in people:
print(job)
if __name__ == '__main__':
main()
| true |
784576394ab7c3d1e6ec6c693c37e198b9aaa0ab | Python | poseidon078/CS641 | /Level5/find_matrix.py | UTF-8 | 1,964 | 2.828125 | 3 | [] | no_license | from utils import *
A = [[84, 0, 0, 0, 0, 0, 0, 0],
[119, 70, 0, 0, 0, 0, 0, 0],
[0, 30, 43, 0, 0, 0, 0, 0],
[0, 0, 1, 12, 0, 0, 0, 0],
[0, 0, 0, 104, 112, 0, 0, 0],
[0, 0, 0, 0, 96, 11, 0, 0],
[0, 0, 0, 0, 0, 88, 27, 0],
[0, 0, 0, 0, 0, 0, 2, 38]]
exponents = [23, 118, 38, 76, 92, 45, 24, 23]
plaintexts = open("plaintexts.txt", "r")
ciphers = open("refined_outputs.txt", "r")
inputs = []
outputs = []
for _ in range(8):
inputs.append(plaintexts.readline().split())
outputs.append(ciphers.readline().split())
plaintexts.close()
ciphers.close()
for off_d in range(2,8):
for c in range(8-off_d):
i = c + off_d
ins = [16*(ord(inputs[c][j][2*c]) - ord('f')) + (ord(inputs[c][j][2*c+1]) - ord('f')) for j in range(128)]
outs = [16*(ord(outputs[c][j][2*(i)]) - ord('f')) + (ord(outputs[c][j][2*(i)+1]) - ord('f')) for j in range(128)]
for k in range(1,128):
A[i][c] = k
f = 1
for index, (x, y) in enumerate(zip(ins, outs)):
p = [0,0,0,0,0,0,0,0]
p[c] = x
cipher = EAEAE(A,exponents,p)
if y != cipher[i]:
f = 0
A[i][c] = 0
break
if f:
A[i][c] = k
break
# Finding the two candidates for (7,0)
# c=0
# i=7
# ins = [16*(ord(inputs[c][j][2*c]) - ord('f')) + (ord(inputs[c][j][2*c+1]) - ord('f')) for j in range(128)]
# outs = [16*(ord(outputs[c][j][2*(i)]) - ord('f')) + (ord(outputs[c][j][2*(i)+1]) - ord('f')) for j in range(128)]
# for k in range(1,128):
# A[i][c] = k
# f = 1
# for index, (x, y) in enumerate(zip(ins, outs)):
# p = [0,0,0,0,0,0,0,0]
# p[c] = x
# cipher = EAEAE(A,exponents,p)
# if y != cipher[i]:
# f = 0
# A[i][c] = 0
# break
# if f:
# A[i][c] = k
# print("Hi", k)
print(A)
print(exponents) | true |
7fcdd121f1660cfcd3a463cc4ab7674ae7406aaa | Python | msemikin/distributed-sudoku | /src/client/networking/connection.py | UTF-8 | 508 | 2.671875 | 3 | [] | no_license | class Connection():
def __init__(self, out_queue):
'''
:param out_queue: queue to publish updates pushed from server
'''
self.out_queue = out_queue
def shutdown(self):
raise NotImplementedError()
def connect(self, server):
'''
:param server: server address
:return: port of local listening socket
'''
raise NotImplementedError()
def blocking_request(self, type, **kwargs):
raise NotImplementedError()
| true |
567c80a1fbda761b3f06281dad1673d7553acf4a | Python | rajesh612/Problem-solving-in-BioInformatics-Using-Python | /BioInformaticsSolutions/BioArmoryPb2/dnacount.py | UTF-8 | 416 | 2.703125 | 3 | [] | no_license | from Bio.Seq import Seq
if __name__== "__main__":
dna_file = open('C:/Users/Rajesh/PycharmProjects/BioArmoryPb2/dna_seq.txt').read().strip().split()
for line in dna_file:
dna_seq = Seq(str(line))
print dna_seq
a_count = dna_seq.count('A')
c_count = dna_seq.count('C')
g_count = dna_seq.count('G')
t_count = dna_seq.count('T')
print a_count,' ',c_count,' ',g_count,' ',t_count
| true |
47c7e8307d6ad248661d55c004a26055cf593ba6 | Python | HongbinW/learn_python | /learn_python/03_OOP/oop_04___del__方法.py | UTF-8 | 267 | 3.953125 | 4 | [] | no_license | class Cat:
def __init__(self,new_name):
self.name = new_name
print("%s 来了"%self.name)
def __del__(self):
print("%s 去了"%self.name)
#tom是一个全局变量
tom = Cat("Tom")
print(tom.name)
#del关键字 可删除一个对象
# del tom
print("-"*50) | true |
3a42b91dbc010c9328fa6955ed22063c4e500196 | Python | surtich/TFG_Manuel_R | /Tema_6_1_Patrones_de_resumen/counter.py | UTF-8 | 745 | 3.296875 | 3 | [] | no_license | #!/usr/bin/env python
from mrjob.job import MRJob
class counter(MRJob):
def mapper_init(self):
#Creamos un diccionario con los que serán los contadores a 0
self.contadores={"Netherlands":0,"France":0,"Australia":0}
def mapper(self, _, line):
linea=line.split(";")
# Estudiamos cada token de la línea recogido
for token in linea:
# Si el token está en el diccionario
if token in self.contadores:
# Contamos con el contador definido en diccionario
self.contadores[token]=self.contadores[token]+1
def mapper_final(self):
yield "Bloque: ",self.contadores
if __name__ == '__main__':
counter.run()
| true |
1f9dfef72dff666599ae16c48b3b685f4a08db1b | Python | ges0531/TIL | /Algorithm/개념정리/순열/프로그래머스_소수찾기/소수찾기.py | UTF-8 | 993 | 2.84375 | 3 | [] | no_license | def solution(numbers):
answer = 0
a = list(str(numbers))
result = []
def prime_num(num):
for k in range(2, num):
if num % k == 0:
return 0
else:
return 1
def comb(n, r, arr, t):
if r == 0:
ans = int(''.join(t))
prime = prime_num(ans)
if (ans not in result) and (ans != 1) and prime and ans:
result.append(ans)
elif r > n:
return
else:
t[r - 1] = arr[n - 1]
comb(n - 1, r - 1, arr, t)
comb(n - 1, r, arr, t)
def perm(k, n, arr):
if k == n:
for ii in range(1, len(arr)+1):
comb(len(arr), ii, arr, [0]*ii)
else:
for i in range(k, n):
arr[i], arr[k] = arr[k], arr[i]
perm(k+1, n, arr)
arr[i], arr[k] = arr[k], arr[i]
perm(0, len(a), a)
return len(result)
print(solution('17')) | true |
3285775da4f3c0401767d778b834db6c94dad85e | Python | chrishefele/kaggle-sample-code | /ReverseGameOfLife/src-old-approaches/atabot/readBoards.py | UTF-8 | 3,143 | 3.09375 | 3 | [] | no_license | import pandas
import numpy as np
from tools import create_blank, print_board, board_rows_str
from search import Search
import copy
TEST_FILE = '../../download/test.csv'
TRAIN_FILE = '../../download/train.csv'
BOARD_ROWS = 20
BOARD_COLS = 20
BOARD_SHAPE = (BOARD_ROWS, BOARD_COLS)
BOARD_CELLS = BOARD_ROWS * BOARD_COLS
def colNames(tag):
return [ tag+'.{col}'.format(col=col) for col in xrange(1,BOARD_CELLS+1)]
def boardDiffs(board1, board2):
diffs = 0
for x in range(BOARD_ROWS):
for y in range(BOARD_COLS):
if board1[x][y] != board2[x][y]:
diffs += 1
return diffs
def boardFromArray(arr):
# creates board from numpy 1/0 array
y, x = arr.shape
board = create_blank(x,y) # includes 1-cell border set to 0
for j in range(y):
for i in range(x):
board[j][i] = arr[j][i] == 1
return board
def boardFromRowCols(row, cols):
boardArray = np.array(row[cols]).reshape(BOARD_SHAPE, order='F')
return boardFromArray(boardArray)
def rowColsFromBoard(board, cols):
pass # TODO
def readBoards(filename, includeStartBoard=False):
df = pandas.read_csv(filename)
nrows, ncols = df.shape
rows = (df.irow(r) for r in xrange(nrows))
for row in rows:
if includeStartBoard:
startBoard = boardFromRowCols(row, colNames('start'))
stopBoard = boardFromRowCols(row, colNames('stop' ))
yield (row['id'], row['delta'], startBoard, stopBoard)
else:
stopBoard = boardFromRowCols(row, colNames('stop' ))
yield (row['id'], row['delta'], stopBoard)
def ataviseBoard(stopBoard, startBoard):
candidate = copy.deepcopy(stopBoard)
search = Search(stopBoard, candidate=candidate)
needy_initial = search.total_needy
needy_min = needy_initial
loops = 0
while search.total_needy >0:
search.use_jittery()
#search.use_pogo()
needy_min = min(needy_min, search.total_needy)
loops += 1
if loops > 1000:
break
needy_final = search.total_needy
print "[ataviseBoard] ",
#print "initial_needy: %6i" % needy_initial,
print "final_needy: %6i" % needy_final,
print "min_needy: %6i" % needy_min,
print "loops: %8i" % loops,
print "initialDiffs: %6i" % boardDiffs(startBoard, search.candidate),
print "endingDiffs: %6i" % boardDiffs(startBoard, stopBoard)
def main():
print 'reading:', TRAIN_FILE
for rid, delta, start_board, stop_board in readBoards(TRAIN_FILE, includeStartBoard=True):
print "\n***", "id:", rid, "delta:", delta,"***\n"
print "START BOARD"
print_board(start_board)
start_rows = board_rows_str(start_board)
print
print "STOP BOARD"
print_board(stop_board)
stop_rows = board_rows_str(stop_board)
print
for row in zip(start_rows, stop_rows):
print row
print
if delta == 1:
print "DELTA==1"
print "id:", rid,
ataviseBoard(stop_board, start_board)
main()
| true |
4892106532338e1db258998458877620b5bb9648 | Python | wang-sj16/Intro2DL | /homework-3/criterion/softmax_cross_entropy.py | UTF-8 | 1,597 | 3.421875 | 3 | [] | no_license | """ Softmax Cross-Entropy Loss Layer """
import numpy as np
# a small number to prevent dividing by zero, maybe useful for you
EPS = 1e-11
class SoftmaxCrossEntropyLossLayer():
def __init__(self):
self.acc = 0.
self.loss = np.zeros(1, dtype='f')
def forward(self, logit, gt):
"""
Inputs: (minibatch)
- logit: forward results from the last FCLayer, shape(batch_size, 10)
- gt: the ground truth label, shape(batch_size, 1)
"""
############################################################################
# TODO: Put your code here
# Calculate the average accuracy and loss over the minibatch, and
# store in self.accu and self.loss respectively.
# Only return the self.loss, self.accu will be used in solver.py.
self.gt = gt
self.prob = np.exp(logit) / (EPS + np.exp(logit).sum(axis=1, keepdims=True))
# calculate the accuracy
predict_y = np.argmax(self.prob, axis=1) # self.prob, not logit.
gt_y = np.argmax(gt, axis=1)
self.acc = np.mean(predict_y == gt_y)
# calculate the loss
loss = np.sum(-gt * np.log(self.prob + EPS), axis=1)
self.loss = np.mean(loss)
############################################################################
return self.loss
def backward(self):
############################################################################
# TODO: Put your code here
# Calculate and return the gradient (have the same shape as logit)
return self.prob - self.gt
############################################################################
| true |
813a00c4578e06d650cd857e191af4b0a4dde8a6 | Python | 5l1v3r1/UAB-Projects | /Labyrinth/Brain_4.py | UTF-8 | 2,442 | 3.171875 | 3 | [] | no_license | # -*- coding: latin-1 -*- # Comentari per permetre que s'utilitzin accents i caràcters especials als comentaris i les cadenes de text.
"""
Daniel Martos Tornay - 1369988
Hector De Armas Padron - 1369599
"""
from pyrobot.brain import Brain
from LinkedList import * # Es suposa que LinkedList està implementada correctament.
import StackList
reload(StackList) # 'reload' serveix per forçar a Python a carregar l'arxiu StackList i actualitzar-ne les possibles modificacions.
import Pilot
reload(Pilot) # 'reload' serveix per forçar a Python a carregar l'arxiu Pilot i actualitzar-ne les possibles modificacions.
class WB(Brain):
def setup(self):
self.stack = StackList.StackList()
self.pilot = Pilot.Pilot()
self.robot.move('reset')
def step(self):
if not self.robot.getItem('win'):
self.pilot.setSonar(self.robot.getItem('sonar')) # utilizamos el sonar para saber a donde podemos movernos
if self.pilot.isCrossRoad(): # comprueba si hay una bifurcacion de ida
if (len(self.stack)==0): # comprueba si la pila esta vacia
self.pilot.setCulDeSac(False) # hay salida
if(self.pilot.getCulDeSac()==True): # comprueba si estamos en un callejon sin salida
(culdesac, movimiento) = self.stack.pop() # devuelve el movimiento de la pila
self.pilot.setCulDeSac(culdesac) # ponemos el callejon sin salida al valor que toque
else:
actions = self.pilot.possibleActions() # utilizamos el possibleActions para saber a donde podemos ir
while (len(actions)>0): # mientras possibleActions no este vacio
self.stack.push(actions.pop()) # devolvemos el valor del movimiento que insertamos
(culdesac, movimiento) = self.stack.pop() # devolvemos el movimiento con su booleano
self.robot.move(self.pilot.moveTo(movimiento)) # nos movemos hacia el movimiento que toque
self.robot.move('grab') # cogemos el oro cuando estemos en una casilla gold
else:
siguienteMov=self.pilot.moveTo(self.pilot.nextMove()) # siguiente movimiento
self.robot.move(siguienteMov) # si no hay bifurcacion utilizamos el piloto para movernos
self.robot.move('grab') # cuando lleguemos a la casilla gold cogemos el oro
def INIT(engine):
return WB('WB', engine)
| true |
51ee99599d6ee7d348d848352c58bc82af602d40 | Python | Kartikei-12/Pyrunc | /main.py | UTF-8 | 2,696 | 3.796875 | 4 | [
"GPL-3.0-only"
] | permissive | """main.py file representingcomparison statistics for Pyrunc module"""
# Python module(s)
from timeit import timeit
# Project module(s)
from Pyrunc import Pyrunc
def main():
"""Main Method"""
pr_c = Pyrunc()
# --------------------------------------------------------------------------------
# ----------------Example 1: 2 Number adder---------------------------------------
# --------------------------------------------------------------------------------
print("Example 1:-")
obj_id, obj = pr_c.build(
"""int two_number_adder(int a, int b) {
return a+b;
}"""
)
print(
"\tTwo number adder demonstrating sum of 5 and 3, result:",
obj.two_number_adder(5, 3),
)
# Comparison Example 1
psetup = """def padder(a,b):
return a+b"""
csetup = """
from Pyrunc import Pyrunc
pr_c = Pyrunc()
obj_id, obj = pr_c.build('''int cadder(int a, int b) {
return a+b;
}''')
cadder = obj.cadder
"""
print("Comparison:-")
print(
"\tC code:", timeit(stmt="cadder(30, 10)", setup=csetup, number=1000) * 10 ** 5
)
print(
"\tPython:", timeit(stmt="padder(30, 10)", setup=psetup, number=1000) * 10 ** 5
)
# ---------------------------------------------------------------------------------
# ----------------Example 2: Sum of first n natural number calculator--------------
# ---------------------------------------------------------------------------------
print("\n\nExample 2:-")
obj_id2, obj2 = pr_c.build(
"""int sum_n_natural_numbers(int a)
{
int i,ans=0;
for(i=1; i<=a; ++i)
ans += i;
return ans;
}"""
)
print(
"\tSum of first n natural numbers with nuber 30, result:",
obj2.sum_n_natural_numbers(30),
)
# Comparison
c_setup = """
from Pyrunc import Pyrunc
pr_c = Pyrunc()
obj_id, obj = pr_c.build('''int csummer(int a) {
int i, ans=0;
for(i=0; i<=a; ++i)
ans += i;
return ans;
}''')
csummer = obj.csummer
"""
psetup1 = """def psummer(a):
ans = 0
for i in range(a):
ans += i
return ans"""
psetup2 = """def psummer(a):
return sum(list(range(a)))"""
psetup3 = """def psummer(a):
return sum([i for i in range(a)])"""
print("Comparison:-")
print("\tC code:", timeit(stmt="csummer(30)", setup=c_setup, number=1000))
print("\tPython1:", timeit(stmt="psummer(30)", setup=psetup1, number=1000))
print("\tPython2:", timeit(stmt="psummer(30)", setup=psetup2, number=1000))
print("\tPython3:", timeit(stmt="psummer(30)", setup=psetup3, number=1000))
if __name__ == "__main__":
main()
| true |
590fb6211dab2833ea4251649eb197a13a831ffa | Python | KelvinUbaechu/tic-tac-toe | /logic/game.py | UTF-8 | 2,231 | 3.4375 | 3 | [] | no_license | from typing import Optional
from errors import CellOccupiedError
from models.board import NonOverlappingBoard, BoardView
from models.chips import BoardChip
from models.player import Player, Human, Computer
from logic.judge import BoardJudge
class TicTacToe:
def __init__(self) -> None:
self.initialize()
@property
def board(self) -> BoardView:
return self._board.get_view()
def initialize(self) -> None:
self._board = NonOverlappingBoard(3, 3)
self._human = Human(self._board.get_view(), BoardChip.X)
self._computer = Computer(self._board.get_view(), BoardChip.O)
def set_human_placement(self, x: int, y: int) -> None:
"""Allows for an external interface to set a pair
of coordinates for the human chip"""
if self._board.get(x, y) != BoardChip.EMPTY:
raise CellOccupiedError
self._human.selected_x, self._human.selected_y = x, y
def are_valid_coords(self, x: int, y: int) -> bool:
"""Returns True if the given coordinates are both
within the bounds of the board and is unoccupied"""
try:
return self._board.get(x, y) == BoardChip.EMPTY
except IndexError:
return False
def place_chips(self) -> None:
"""Places chips of each player on board,
Raises CellOccupiedError if either player tries to place a chip
on an already played on cell"""
for player in [self._human, self._computer]:
self._board.set(*player.get_chip_placement(), player.chip)
if self.is_game_over():
return
def get_winner(self) -> Optional[Player]:
"""Returns the player who has three consecutive chips
in a row on the board (can be a row, column, or diagonal)
Returns None if there is no winner"""
winning_chip = BoardJudge.get_winning_chip(self._board)
if winning_chip == BoardChip.EMPTY:
return None
for player in [self._human, self._computer]:
if player.chip == winning_chip:
return player
def is_game_over(self) -> bool:
return self._board.is_full() or self.get_winner() is not None | true |
a8a95ca0358798636165e601350f220a453e6ddc | Python | rafalp/misago_docker | /wizard/sentry.py | UTF-8 | 1,653 | 2.625 | 3 | [
"MIT"
] | permissive | import re
from config import misago
from utils import input_bool, input_choice, print_setup_changed_message
SENTRY_DSN_REGEX = re.compile(r"^https://[0-9a-z]+(:[0-9a-z]+)?@sentry\.io/[0-9]+$")
def run_sentry_wizard(env_file):
if input_bool("Enable Sentry logging?"):
run_dsn_wizard(env_file)
else:
disable_sentry(env_file)
def disable_sentry(env_file):
env_file["SENTRY_DSN"] = ""
def run_dsn_wizard(env_file):
sentry_dsn_prompt = "Enter your Sentry DSN: "
sentry_dsn = None
while not sentry_dsn:
sentry_dsn = input(sentry_dsn_prompt).strip().lower()
try:
if not sentry_dsn:
raise ValueError("You have to enter a Sentry DSN.")
if not SENTRY_DSN_REGEX.match(sentry_dsn):
raise ValueError("Entered value is not a valid Sentry DSN.")
except ValueError as e:
sentry_dsn = None
print(e.args[0])
print()
env_file["SENTRY_DSN"] = sentry_dsn
def print_sentry_setup(env_file):
if env_file.get("SENTRY_DSN"):
print("Logging to Sentry is enabled:")
print()
print("DSN: %s" % env_file.get("SENTRY_DSN"))
else:
print("Logging to Sentry is disabled.")
def change_sentry_setup(env_file):
print_sentry_setup(misago)
print()
if input_bool("Change Sentry logging?", default=False):
run_sentry_wizard(env_file)
env_file.save()
print_setup_changed_message()
if __name__ == "__main__":
if misago.is_file():
try:
change_sentry_setup(misago)
except KeyboardInterrupt:
print()
| true |
d641f5eb8e618fabf6593db0c59a08ad06636aaa | Python | clairessmileyworld/Class4finally | /rockpaperscissors.py | UTF-8 | 1,957 | 3.625 | 4 | [] | no_license | import random
computer_win_counter = 0
player_win_counter = 0
print("Welcome. The Rock, Paper, Scissors tournament is starting now. Best of 5.")
print("\n")
name = input("Player 1, please enter your name: ")
def print_result():
global computer_win_counter, player_win_counter
print (name + " won: " + str(player_win_counter) + ": " + " computer won: " + str(computer_win_counter))
def game(name):
global computer_win_counter, player_win_counter
options = ["rock", "paper", "scissors"]
player1 = input(name+", Rock, Paper, Scissors shoot:").lower()
computerrobotplayer23876 = random.choice(options)
print(name+" has chosen " +player1)
print("computerrobotplayer23876, has chosen " +computerrobotplayer23876)
if player1==computerrobotplayer23876:
print("tie")
print_result()
elif player1=="rock" and computerrobotplayer23876=="scissors":
print(name+" wins this round")
player_win_counter = player_win_counter + 1
print_result()
elif player1=="rock" and computerrobotplayer23876=="paper":
print("computerrobotplayer23876 wins.")
computer_win_counter = computer_win_counter + 1
print_result()
elif player1=="paper" and computerrobotplayer23876=="rock":
print(name+" wins this round.")
player_win_counter = player_win_counter + 1
print_result()
elif player1=="paper" and computerrobotplayer23876=="scissors":
print("computerrobotplayer23876 wins this round.")
computer_win_counter = computer_win_counter + 1
print_result()
elif player1=="scissors" and computerrobotplayer23876=="rock":
print("computerrobotplayer23876 wins this round.")
computer_win_counter = computer_win_counter + 1
print_result()
elif player1=="scissors" and computerrobotplayer23876=="paper":
print(name+" wins this round.")
player_win_counter = player_win_counter + 1
print_result()
for items in range(3):
game(name)
print("\n")
| true |
249d540e026ae50833e440ed221f1882a03ea650 | Python | sansseriff/caltech-ee148-spring2020-hw03 | /main.py | UTF-8 | 22,052 | 2.53125 | 3 | [] | no_license | from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torch.utils.data.sampler import SubsetRandomSampler
import matplotlib.pyplot as plt
import numpy as np
import random
import PIL
import pickle
import sklearn
from sklearn.metrics import confusion_matrix
from sklearn.manifold import TSNE
import seaborn as sn
import pandas as pd
from math import log
import math
random.seed(2020)
torch.manual_seed(2020)
import os
'''
This code is adapted from two sources:
(i) The official PyTorch MNIST example (https://github.com/pytorch/examples/blob/master/mnist/main.py)
(ii) Starter code from Yisong Yue's CS 155 Course (http://www.yisongyue.com/courses/cs155/2020_winter/)
'''
class fcNet(nn.Module):
'''
Design your model with fully connected layers (convolutional layers are not
allowed here). Initial model is designed to have a poor performance. These
are the sample units you can try:
Linear, Dropout, activation layers (ReLU, softmax)
'''
def __init__(self):
# Define the units that you will use in your model
# Note that this has nothing to do with the order in which operations
# are applied - that is defined in the forward function below.
super(fcNet, self).__init__()
self.fc1 = nn.Linear(in_features=784, out_features=20)
self.fc2 = nn.Linear(20, 10)
self.dropout1 = nn.Dropout(p=0.5)
def forward(self, x):
# Define the sequence of operations your model will apply to an input x
x = torch.flatten(x, start_dim=1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout1(x)
x = F.relu(x)
output = F.log_softmax(x, dim=1)
return output
class ConvNet(nn.Module):
'''
Design your model with convolutional layers.
'''
def __init__(self):
super(ConvNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=8, kernel_size=(3,3), stride=1)
self.conv2 = nn.Conv2d(8, 8, 3, 1)
self.dropout1 = nn.Dropout2d(0.5)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(200, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout2(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
'''
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=8, kernel_size=(3,3), stride=1)
self.conv2 = nn.Conv2d(8, 8, 3, 1)
self.dropout1 = nn.Dropout2d(0.5)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(200, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout2(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
'''
class Net(nn.Module):
'''
COmpared with teh convnet, this has a 3rd linear layer and doubles the number of the convolution in the 2nd convolution layer
'''
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, out_channels=8, kernel_size=(3, 3), stride=1)
self.conv15 = nn.Conv2d(8, out_channels=16, kernel_size=(3, 3), stride=1)
#self.conv2 = nn.Conv2d(8, 16, 3, 1)
self.conv2 = nn.Conv2d(16, 32, 3, 1)
#self.dropout1 = nn.Dropout2d(0.5)
#self.dropout2 = nn.Dropout2d(0.5)
# follow dimensions:
# conv1 takes 28 to 26
# maxpool takes 26 to 13
# conv2 takes 13 to 11
# maxpool takes 11 to 5
#self.fc1 = nn.Linear(16 * 5 * 5, 120)
#self.fc1 = nn.Linear(32 * 4 * 4, 120)
self.fc1 = nn.Linear(32 * 22 * 22, 3000)
self.fc15 = nn.Linear(3000, 600)
self.fc16 = nn.Linear(600, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
self.dropout1 = nn.Dropout2d(0.3)
self.dropout2 = nn.Dropout2d(0.3)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
#x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = self.conv15(x)
x = F.relu(x)
x = self.dropout2(x)
#x = F.max_pool2d(x, 2)
x = self.conv2(x)
x = F.relu(x)
#x = F.max_pool2d(x, 2)
size = x.size()[1:]
dims = 1
for s in size:
dims *= s
x = x.view(-1, dims)
x = self.fc1(x)
x = F.relu(x)
x = self.fc15(x)
x = F.relu(x)
x = self.fc16(x)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
xf = self.fc3(x)
output = F.log_softmax(xf, dim=1)
return output, x
class Net2(nn.Module):
'''
COmpared with the convnet, this has a 3rd linear layer and doubles the number of the convolution in the 2nd convolution layer
'''
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, out_channels=8, kernel_size=(3, 3), stride=1)
self.conv15 = nn.Conv2d(8, out_channels=16, kernel_size=(3, 3), stride=1)
#self.conv2 = nn.Conv2d(8, 16, 3, 1)
self.conv2 = nn.Conv2d(16, 32, 3, 1)
#self.dropout1 = nn.Dropout2d(0.5)
#self.dropout2 = nn.Dropout2d(0.5)
# follow dimensions:
# conv1 takes 28 to 26
# maxpool takes 26 to 13
# conv2 takes 13 to 11
# maxpool takes 11 to 5
#self.fc1 = nn.Linear(16 * 5 * 5, 120)
#self.fc1 = nn.Linear(32 * 4 * 4, 120)
self.fc1 = nn.Linear(32 * 22 * 22, 3000)
self.fc15 = nn.Linear(3000, 600)
self.fc16 = nn.Linear(600, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
self.dropout1 = nn.Dropout2d(0.2)
self.dropout2 = nn.Dropout2d(0.2)
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
#x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = self.conv15(x)
x = F.relu(x)
x = self.dropout2(x)
#x = F.max_pool2d(x, 2)
x = self.conv2(x)
x = F.relu(x)
#x = F.max_pool2d(x, 2)
size = x.size()[1:]
dims = 1
for s in size:
dims *= s
x = x.view(-1, dims)
x = self.fc1(x)
x = F.relu(x)
x = self.fc15(x)
x = F.relu(x)
x = self.fc16(x)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
xf = self.fc3(x)
output = F.log_softmax(xf, dim=1)
return output, x
def train(args, model, device, train_loader, optimizer, epoch):
'''
This is your training function. When you call this function, the model is
trained for 1 epoch.
'''
model.train() # Set the model to training mode
total_loss = 0
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad() # Clear the gradient
output, hidden_layer = model(data) # Make predictions
loss = F.nll_loss(output, target) # Compute loss
loss.backward() # Gradient computation
optimizer.step() # Perform a single optimization step
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.sampler),
100. * batch_idx / len(train_loader), loss.item()))
total_loss = total_loss + loss.item()
#train loss for each epoch is an average of the loss over all mini-batches
train_loss = total_loss/batch_idx
return train_loss
def test(model, device, test_loader, evaluate = False):
model.eval() # Set the model to inference mode
test_loss = 0
correct = 0
test_num = 0
images = []
allimages = []
master_preds = []
master_truths = []
master_hidden_layers = []
with torch.no_grad(): # For the inference step, gradient is not computed
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output, hidden_layer = model(data)
#feature_extractor = torch.nn.Sequential(*list(model.children())[:-1])
test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
print(len(hidden_layer))
print(len(hidden_layer[0]))
#print(hidden_layer[0])
correct += pred.eq(target.view_as(pred)).sum().item()
test_num += len(data)
if evaluate:
for i in range(len(pred)):
master_preds.append(pred[i][0].item())
master_truths.append(target[i].item())
layer = hidden_layer[i].cpu()
master_hidden_layers.append(layer.numpy())
image = data[i][0].cpu()
allimages.append(image.numpy())
if pred[i][0] == target[i]:
continue
else:
#print("not equal")
#print("pred is ", pred[i][0].item(), "and target is ", target[i].item())
image = data[i][0].cpu()
images.append([image.numpy(),pred[i][0].item(),target[i].item()])
if evaluate:
#print(len(master_hidden_layers))
#print(master_hidden_layers[0])
distances = np.zeros(len(master_hidden_layers))
#x0 = master_hidden_layers[0]
for i in range(len(distances)):
length = 0
for dim in range(len(master_hidden_layers[0])):
length = length + (master_hidden_layers[i][dim] - master_hidden_layers[15][dim])**2
length = math.sqrt(length)
distances[i] = length
sorted_distance_index = np.argsort(distances)
figa = plt.figure()
print("test")
for i in range(9):
sub = figa.add_subplot(9, 1, i + 1)
sub.imshow(allimages[sorted_distance_index[i]], interpolation='nearest', cmap='gray')
X = master_hidden_layers
y = np.array(master_truths)
tsne = TSNE(n_components=2, random_state=0)
X_2d = np.array(tsne.fit_transform(X))
target_ids = range(10)
cdict = {0: 'orange', 1: 'red', 2: 'blue', 3: 'green', 4: 'salmon', 5:'c', 6: 'm', 7: 'y', 8: 'k', 9: 'lime'}
fig, ax = plt.subplots()
for g in np.unique(y):
ix = np.where(y == g)
ax.scatter(X_2d[ix, 0], X_2d[ix, 1], c=cdict[g], label=g, s=5)
ax.legend()
plt.show()
#i = 1
#plt.figure(figsize=(6, 5))
#plt.scatter(X_2d[10*i:10*i+10,0],X_2d[:10,1])
CM = confusion_matrix(master_truths,master_preds)
CMex = CM
#for i in range(len(CM)):
# for j in range(len(CM)):
# if CM[i][j] > 0:
# CMex[i][j] = log(CM[i][j])
# else:
# CMex[i][j] = CM[i][j]
print(CM)
print(CMex)
df_cm = pd.DataFrame(CM, range(10), range(10))
#plt.figure(figsize=(10,7))
fig0,ax0 = plt.subplots(1)
sn.set(font_scale=1) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 11}) # font size
#ax0.set_ylim(len(CMex) - 0.5, 0.5)
plt.xlabel("predicted")
plt.ylabel("ground truth")
plt.show()
fig = plt.figure()
for i in range(9):
sub = fig.add_subplot(3, 3, i + 1)
sub.imshow(images[i + 10][0], interpolation='nearest', cmap='gray')
title = "Predicted: " + str(images[i+ 10][1]) + " True: " + str(images[i+ 10][2])
sub.set_title(title)
kernels = model.conv1.weight.cpu().detach().clone()
kernels = kernels - kernels.min()
kernels = kernels / kernels.max()
kernels = kernels.numpy()
print(np.shape(kernels))
fig2 = plt.figure()
for i in range(8):
sub = fig2.add_subplot(2, 4, i + 1)
sub.imshow(kernels[i][0], interpolation='nearest', cmap='gray')
title = "Kernel #" + str(i + 1)
sub.set_title(title)
#fig, axs = plt.subplots(3, 3, constrained_layout=True)
#for i in range(9):
# fig[i].imshow(images[i][0], interpolation='nearest', cmap='gray')
# axs[i].set_title("all titles")
test_loss /= test_num
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.4f}%)\n'.format(
test_loss, correct, test_num,
100. * correct / test_num))
return test_loss
def main():
# Training settings
# Use the command line to modify the default settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=14, metavar='N',
help='number of epochs to train (default: 14)')
parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
help='learning rate (default: 1.0)')
parser.add_argument('--step', type=int, default=1, metavar='N',
help='number of epochs between learning rate reductions (default: 1)')
parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
help='Learning rate step gamma (default: 0.7)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--evaluate', action='store_true', default=False,
help='evaluate your model on the official test set')
parser.add_argument('--load-model', type=str,
help='model file path')
parser.add_argument('--save-model', action='store_true', default=True,
help='For Saving the current Model')
args = parser.parse_args()
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
# Evaluate on the official test set
if args.evaluate:
assert os.path.exists(args.load_model)
# Set the test model
model = Net().to(device)
model.load_state_dict(torch.load(args.load_model))
test_dataset = datasets.MNIST('../data', train=False,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]))
test_loader = torch.utils.data.DataLoader(
test_dataset, batch_size=args.test_batch_size, shuffle=True, **kwargs)
test(model, device, test_loader, evaluate = True)
return
# Pytorch has default MNIST dataloader which loads data at each iteration
train_dataset = datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([ # Data preprocessing
transforms.ToTensor(), # Add data augmentation here
transforms.Normalize((0.1307,), (0.3081,))
]))
train_dataset_augmented = datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([ # Data preprocessing
#transforms.RandomCrop(28, padding=(1, 1, 1, 1)),
#transforms.RandomRotation(4, resample=PIL.Image.BILINEAR),
#transforms.RandomResizedCrop(28, scale=(0.85, 1.0), ratio=(1, 1),
# interpolation=2),
transforms.RandomAffine(8, translate=(.065, .065), scale=(0.80, 1.1),
resample=PIL.Image.BILINEAR),
transforms.ToTensor(), # Add data augmentation here
transforms.Normalize((0.1307,), (0.3081,))
]))
print(type(train_dataset))
print(len(train_dataset), type(train_dataset[0][0]), type(train_dataset[0][1]), type(train_dataset[0]))
print("the int is: ", train_dataset[2][1])
print(np.shape(train_dataset[0][0][0].numpy()))
idx = [[] for i in range(10)]
#each row of indexes is a list of indexes in the train_dataset
#e.g. row 5 containes a list of indexes for the places in train_dataset with images of 5
print(idx[4])
for i, img in enumerate(train_dataset):
#if False:
if i < 5:
fig = plt.figure()
plt.imshow(img[0][0].numpy(), cmap='gray')
fig = plt.figure()
plt.imshow(train_dataset_augmented[i][0][0].numpy(), cmap='gray')
for number in range(10):
if img[1] == number:
idx[number].append(i)
val_idx = [[] for i in range(10)]
train_idx = [[] for i in range(10)]
#print(idx[0][1:100])
for i, number_indx in enumerate(idx):
random.shuffle(number_indx)
l = len(number_indx)
idx_lim = int(l*0.15)
val_idx[i] = number_indx[0:idx_lim]
train_idx[i] = number_indx[idx_lim:]
subset_indices_train = [j for sub in train_idx for j in sub]
subset_indices_valid = [j for sub in val_idx for j in sub]
# for adjusting size of train set
train_length = int(len(subset_indices_train))
#train_length = int(len(subset_indices_train)/2)
#train_length = int(len(subset_indices_train) / 4)
#train_length = int(len(subset_indices_train) / 8)
#train_length = int(len(subset_indices_train) / 16)
# You can assign indices for training/validation or use a random subset for
# training by using SubsetRandomSampler. Right now the train and validation
# sets are built from the same indices - this is bad! Change it so that
# the training and validation sets are disjoint and have the correct relative sizes.
train_loader = torch.utils.data.DataLoader(
train_dataset_augmented, batch_size=args.batch_size,
sampler=SubsetRandomSampler(subset_indices_train[:train_length])
)
val_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=args.test_batch_size,
sampler=SubsetRandomSampler(subset_indices_valid)
)
# Load your model [fcNet, ConvNet, Net]
model = Net().to(device)
# Try different optimzers here [Adam, SGD, RMSprop]
optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
# Set your learning rate scheduler
scheduler = StepLR(optimizer, step_size=args.step, gamma=args.gamma)
# Training loop
train_losses = []
test_losses = []
x = []
fig, ax = plt.subplots(1)
if True:
for epoch in range(1, args.epochs + 1):
#train and test each epoch
train_loss = train(args, model, device, train_loader, optimizer, epoch)
test_loss = test(model, device, val_loader)
scheduler.step() # learning rate scheduler
train_losses.append(train_loss)
test_losses.append(test_loss)
x.append(epoch - 1)
ax.plot(x, test_losses, label='test_losses', markersize=2)
ax.plot(x, train_losses, label='train_losses', markersize=2)
plt.pause(0.05)
# You may optionally save your model at each epoch here
if args.save_model:
print(train_losses)
with open("train_losses_one.txt", "wb") as fp: # Pickling
pickle.dump(train_losses, fp)
print(test_losses)
with open("test_losses_one.txt", "wb") as fp: # Pickling
pickle.dump(test_losses, fp)
torch.save(model.state_dict(), "mnist_model_onef.pt")
if __name__ == '__main__':
main()
| true |
ee1ae22e16c43bba68f6adfaff8621939416abe7 | Python | hevi9/etc-python | /fragtext/parser1.py | UTF-8 | 1,723 | 2.609375 | 3 | [] | no_license | from scanner import Scanner
import logging
import re
from texts import *
log = logging.getLogger()
D = log.debug
class Parser:
def __init__(self):
# define scanners
flags = re.MULTILINE
# flags = 0
self.s1 = Scanner((
(r'\n\n', self.on_nl2),
(r'\n', self.on_nl),
(r'@@', self.on_frag),
(r'{{{', self.on_begin),
), flags)
self.s2 = Scanner((
(r'}}}', self.on_end),
), flags)
# states
self.scanner = self.s1
self.linenro = 0
def write_all(self, text):
start_pos = 0
while True:
mo, action = self.scanner.scan(text, start_pos)
if mo:
# D("MM %r,%r", mo.start(), mo.end())
if mo.start() > start_pos:
self.on_nomatch(text[start_pos:mo.start()])
action(mo.group())
start_pos = mo.end()
else:
self.on_nomatch(text[start_pos:])
break
def on_frag(self, text):
D("on_frag %r", text)
def on_emptyline(self, text):
D("on_emptyline %r", text)
def on_nl(self, text):
# D("NL")
self.linenro += 1
def on_nl2(self, text):
# D("NLNL")
self.linenro += 2
def on_begin(self, text):
D("on_begin %r", text)
self.scanner = self.s2
def on_end(self, text):
D("on_end %r", text)
self.scanner = self.s1
def on_nomatch(self, text):
D("on_nomatch %r", text)
def main():
parser = Parser()
parser.write_all(text_01)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
main()
| true |
e080bffce33114f21ac41691a2eeb1b0f5a236d1 | Python | kamyu104/LeetCode-Solutions | /Python/find-players-with-zero-or-one-losses.py | UTF-8 | 495 | 3.34375 | 3 | [
"MIT"
] | permissive | # Time: O(nlogn)
# Space: O(n)
import collections
# hash, sort
class Solution(object):
def findWinners(self, matches):
"""
:type matches: List[List[int]]
:rtype: List[List[int]]
"""
lose = collections.defaultdict(int)
players_set = set()
for x, y in matches:
lose[y] += 1
players_set.add(x)
players_set.add(y)
return [[x for x in sorted(players_set) if lose[x] == i] for i in xrange(2)]
| true |
292ad25a5915870484b03bb138c335b9f72880eb | Python | Ilyiad/PATI | /conftest.py | UTF-8 | 7,823 | 2.640625 | 3 | [] | no_license | #!/usr/local/bin/python3.5
#
# Copyright 2016, Dan Malone, All rights reserved
#
import util.globals
import testlink.tltrack
import control.netem
#########################################################################################
#
# MODULE : conftest.py()
#
# DESCRIPTION: This module contains methods specific to running py.test and includes preparsing the
# command line, setting up the test, a stub for test reporting (currently has Testlink
# hook) and file checking as the test run traverses.
#
# AUTHOR : Dan Malone
#
# CREATED : 01/03/2016
#
#########################################################################################
#########################################################################################
#
# METHOD: pytest_cmdline_preparse(config, args)
#
# DESCRIPTION: This method is called automatically by pytest before executing tests but after
# globals.py has been imported globals.py is our local module which parses through
# the command line args for any parameters of the form KEY=VALUE It will take a command
# line argument like DEBUG=1 and put it into the "global options" dictionary Tests or
# Objects can then access those options via: getOpt('DEBUG') for example.
#
# NOTE: While parsing now we have to remove those arguments from the command line argument
# list or else pytest will throw a fit
#
#########################################################################################
def pytest_cmdline_preparse(config, args):
"""pytest_cmdline_preparse(config, args) - This method is called automatically by pytest before executing tests but after
globals.py has been imported globals.py is our local module which parses through
the command line args for any parameters of the form KEY=VALUE.
"""
# Build up argv which will contain only the "pytest acceptable" args
argv = []
for arg in args:
if not '=' in arg:
# This is not one of our args. All of our args are of the form KEY=VALUE
argv.append(arg)
continue
# Update the args which pytest will continue to parse
args[:] = argv
#########################################################################################
#
# METHOD: pytest_runtest_setup(item)
#
# DESCRIPTION: This method is a hook function called by py.test before each test run. It basically
# sets up the log data for the run into a nice pretty header.
#
#########################################################################################
def pytest_runtest_setup(item):
"""pytest_runtest_setup(item) - This method is a hook function called by py.test before each test run. It basically
sets up the log data for the run into a nice pretty header.
"""
# Get the name of the test
test_function = item.name
# Get the description of the test
test_description = item.function.__doc__
# Get the name of the path/file.py that contains the script
script = item.fspath
# Store info about this current testcase in globals
util.globals.setOpt("TESTCASE_NAME", str(test_function))
util.globals.setOpt("TESTCASE_DESC", str(test_description))
print("")
util.globals.log("###########################################################################################")
util.globals.log("# Test Module: " + util.globals.getOpt("TESTCASE_FILE"))
util.globals.log("# Test Name: " + str(test_function))
util.globals.log("# Description: " + str(test_description))
util.globals.log("###########################################################################################")
# This is an inner method to get all the methods of a class. Call inspect_class(<class>) to see all of it's methods
# This function is buried inside of pytest_runtest_setup() because I was using it to examine the availble attributes of "item"
# It had to be inside of pytest_runtest_setup because you can only have defined hook functions in conftest.py
# but it appears conftest.py cannot access any modules outside of itself (as far as I know)
def inspect_class(klass):
verbose=1
attrs = dir(klass)
print("------------------------------------------------------")
print(str(klass))
print("")
if "__doc__" in attrs:
print(klass.__doc__)
print("Class: " + str(klass.Class))
print("File: " + str(klass.File))
print("Function: " + str(klass.Function))
print("Instance: " + str(klass.Instance))
print("Item: " + str(klass.Item))
print("Module: " + str(klass.Module))
print("location: " + str(klass.location))
print("name: " + str(klass.name))
print("function: " + str(klass.function))
print("fspath: " + str(klass.fspath))
print("_getfslineno: " + str(klass._getfslineno()))
print("------------------------------------------------------")
for attr in attrs:
if verbose:
print(str(attr))
print("")
# Inspect the item object
if 0:
inspect_class(item)
#########################################################################################
#
# METHOD: pytest_runtest_makereport(item, call, __multicall__)
#
# DESCRIPTION: This method is a hook of hooks function called by py.test after each test run.
# It basically executes the passed reporting hook and any other exiting hooks (in
# this case Testlink) for test case reporting.
#
#########################################################################################
def pytest_runtest_makereport(item, call, __multicall__):
"""pytest_runtest_makereport(item, call, __multicall__) - This method is a hook of hooks
function called by py.test after each test run.It basically executes the passed
reporting hook and any other exiting hooks (in this case Testlink) for test case reporting.
"""
# execute all other hooks to obtain the report object
rep = __multicall__.execute()
# ################################
# TESTLINK Reporting Setup (active by CLI Arg request only)
# ################################
tl = testlink.tltrack.tl_track()
tl.tl_project = util.globals.getOpt('TESTLINK_PROJECT')
tl.tl_platform = util.globals.getOpt('TESTLINK_PLATFORM')
tl.tl_build = util.globals.getOpt('TESTLINK_BUILD')
tl.tl_testplan = util.globals.getOpt('TESTLINK_TESTPLAN')
tl.tl_testid = util.globals.getOpt('TESTLINK_TESTID')
# we only look at actual failing test calls, not setup/teardown
if rep.when == "call" and rep.failed:
tl.tl_teststatus_update("f")
elif rep.when == "call":
tl.tl_teststatus_update("p")
return rep
#########################################################################################
#
# METHOD: pytest_collect_file(path, parent)
#
# DESCRIPTION: This method is called everytime a file is encontered by pytest as it traverses
# the test directories.
#
#########################################################################################
def pytest_collect_file(path, parent):
"""pytest_collect_file(path, parent) - This method is called everytime a file is encontered
by pytest as it traverses the test directories.
"""
# Store info about this current testcase in globals
util.globals.setOpt("TESTCASE_FILE", str(path))
util.globals.setLogFileName(1)
util.globals.log("Entered test module: " + str(path))
| true |
117de10ae0facf1565398b69aa2dc6b8c0e8e355 | Python | smiley16479/AI_bootcamp | /week_0/Day00/ex04/operations.py | UTF-8 | 863 | 3.6875 | 4 | [] | no_license | import sys
def usage():
print ("Usage: python operations.py\nExample:\n python operations.py 10 3")
def inputError():
print ("InputError: too many arguments\n")
def inputError1():
print("InputError: only numbers\n")
num1 = 0
num2 = 0
del sys.argv[0]
if len(sys.argv) < 2:
usage()
sys.exit(0)
elif len(sys.argv) > 2:
inputError()
usage()
sys.exit(0)
else :
try:
num1 = int(sys.argv[0])
num2 = int(sys.argv[1])
except:
inputError1()
usage()
sys.exit(0)
print("Sum:\t" + str(num1 + num2))
print("Difference:\t" + str(num1 - num2))
print("Product:\t" + str(num1 * num2))
try:
print("Quotient:\t" + str(num1 / num2))
except:
print("Quotient:\t ERROR (div by zero)")
try:
print("Remainder:\t" + str(num1 % num2))
except:
print("Remainder:\t ERROR (modulo by zero)")
| true |
202b290562552023d17235432c7e33c6737d2723 | Python | MarioActuationTeam/SuperMarioPlayer | /src/SuperMarioMovement.py | UTF-8 | 11,881 | 3.140625 | 3 | [
"MIT"
] | permissive | import random
import numpy as np
import src.SuperMarioImages as SuperMarioImages
import src.SuperMarioMap as SuperMarioMap
import src.EnumMovement as EnumMovement
##
# This class is responsible for every kind of movement the player makes. It also implements different
# movement strategies.
#
# @author Wolfgang Mair, Florian Weiskirchner, Emmanuel Najfar
# @version 18. January 2021
##
class Movement:
# List of all possible (rational) inputs the player can make
COMPLEX_MOVEMENT = [
['NOOP'],
['right'],
['right', 'A'],
['right', 'B'],
['right', 'A', 'B'],
['A'],
['left'],
['left', 'A'],
['left', 'B'],
['left', 'A', 'B'],
['down'],
['up'],
]
# The players X coordinate
positionMarioRow = 0
# The players Y coordinate
positionMarioCole = 0
# Value to calculate velocity of the player (falling or rising)
oldYPositionMario = 16
# True if player is falling
isFalling = False
def __init__(self):
self.sm_images = SuperMarioImages.Images()
# Needed for better action distribution
# jumpright 25
# runright 10
# jumprunright 65
# else 0
self.basicWeights = [0, 0, 25, 10, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0]
self.movement = EnumMovement.Movement
##
# DEPRECATED
# This method lets the player jump the highest he can possibly can.
# @author Wolfgang Mair
#
# @param env The current game environment
# @param reward Integer which specifies the benefit of an action
# @param done Boolean which specifies if the game is finished
# @param info Dictionary which contains information about the environment
##
def bigJump(self, env, reward, done, info):
height = 0
# print("Prepare!\n")
state, reward, done, info = env.step(3)
env.render()
while height <= info['y_pos']:
if done:
state = env.reset()
height = info['y_pos']
state, reward, done, info = env.step(4)
env.render()
# print("Jump!\n")
while height != info['y_pos']:
if done:
state = env.reset()
height = info['y_pos']
state, reward, done, info = env.step(3)
env.render()
# print("Wait!\n")
return state, reward, done, info
##
# DEPRECATED
# This method chooses random actions for the player based on a weighted array
# @author Wolfgang Mair
#
# @param weightArray Array of weights to all possible actions the player can take
##
def weightedRandom(self, weightArray):
listOfValidActionsWithCountOfItemsInferedByWeights = []
for idx, weight in enumerate(weightArray):
listOfValidActionsWithCountOfItemsInferedByWeights += [
idx] * weight # inserts "weight"-times an action (= index of operation; see: COMPLEX_MOVEMENT)
return random.choice(listOfValidActionsWithCountOfItemsInferedByWeights)
##
# DEPRECATED
# This method tries to identify Goombas and Pits and avoid them with a big jump
# @author Wolfgang Mair
#
# @param state State array provided by the gym-super-mario-bros class of type ndarray:(240, 256, 3)
# @param env The current game environment
# @param reward Integer which specifies the benefit of an action
# @param done Boolean which specifies if the game is finished
# @param info Dictionary which contains information about the environment
##
def badSearchMovement(self, state, reward, done, info, env):
maskGoomba = (state[194] == self.sm_images.goombaColor).all(axis=1)
maskPit = (state[210] == self.sm_images.skyColor).all(axis=1)
if np.any(maskGoomba):
return self.bigJump(env, reward, done, info)
else:
if np.any(maskPit):
return self.bigJump(env, reward, done, info)
else:
return env.step(self.weightedRandom(self.basicWeights))
##
# Based on the position of Mario, this method looks around him and tries too find other objects
# @author Florian Weiskirchner
#
# @param oldYPositionMario is the Y Position from Mario in the last Move
# @param doMove Which move should be used from the COMPLEX_MOVEMENT array
# @param charForMario Which Char Mario has in the array
# @param isFalling is a bool which is true when Mario is falling and false when he is jumping or running
# @return doMove gets returned.
##
def goodMovement(self, sm_env):
self.oldYPositionMario = self.positionMarioRow
doMove = self.movement.right.value
self.marioSearch(sm_env)
self.isFalling = self.checkIfFalling()
# check whether the square in the same row as and two column in front of mario contains
# the letter "G" in the array
# if yes, there is a Goomba in front of mario, therefore the respective function will be called
if sm_env.environment[self.positionMarioRow, self.positionMarioCole + 2] == "G":
return self.movementBygoomba()
# check whether the square in one row under and the same column mario contains
# the letter "P" in the array
# if yes, there is a Pipe under mario, therefore the respective function will be called
if sm_env.environment[self.positionMarioRow + 1, self.positionMarioCole] == "P":
return self.movementOntopOfPipe()
# check whether the square in the any row as and one column in front of mario contains
# the letter "P" in the array
# if yes, there is a Pipe in front of mario, therefore the respective function will be called
if (sm_env.environment[:, self.positionMarioCole + 1] == "P").any():
return self.movementByPipe()
if sm_env.environment[self.positionMarioRow, self.positionMarioCole + 2] == "C":
return self.movementByCooper()
# check whether the square one column in front and one row below mario is empty in the array
# if yes, there is a pit in front of mario, therefore the respective function will be called
if sm_env.environment[self.positionMarioRow + 1, self.positionMarioCole + 1] == " ":
return self.movementByPit()
# check whether the square in the same row as and one column in front of mario contains
# the letter "S" in the array
# if yes, there is a stair in front of mario, therefore the respective function will be called
if sm_env.environment[self.positionMarioRow, self.positionMarioCole + 1] == "S":
return self.movementByAscendingStairs()
# check whether the square in any row and one column in front of mario contains
# the letter "S" in the array
# if yes, there is a stair in front of mario, therefore the respective function will be called
if (sm_env.environment[:, self.positionMarioCole + 1] == "S").any():
return self.movementByDescendingStairs()
if self.isFalling:
doMove = self.movement.left.value
return doMove
##
# This function search Mario (M) in the Array and saves his position.
# @author Florian Weiskirchner
#
# @param charForMario Which Char Mario has in the array
# @param positionMarioRow Y position of Mario in the array
# @param positionMarioCole X position of Mario in the array
##
def marioSearch(self, sm_env):
charForMario = "M"
positionMario = np.where(sm_env.environment == charForMario)
self.positionMarioRow = positionMario[0]
self.positionMarioCole = positionMario[1]
return
##
# Checks if Mario is falling based on his current Y position and the last Y position
# @author Florian Weiskirchner
#
# @param oldYPositionMario is the Y Position from Mario in the last Move
# @param positionMarioRow Y position of Mario in the array
# @return True or False for isFalling
##
def checkIfFalling(self):
if self.positionMarioRow > self.oldYPositionMario:
return True
return False
##
# Movement from Mario when there is a Gommba in front of him
# @author Florian Weiskirchner
#
# @param movement this is a Enum with the movementoptions from COMPLEX_MOVEMENT
# @param isFalling is a bool which is true when Mario is falling and false when he is jumping or running
# @return a value from movement gets returned
##
def movementBygoomba(self):
if self.isFalling:
return self.movement.NOOP.value
return self.movement.rightA.value
##
# NOT USED
# Movement from Mario when there is a Gommba under him and tries to avoid him
# @author Florian Weiskirchner
#
# @param movement this is a Enum with the movementoptions from COMPLEX_MOVEMENT
# @return a value from movement gets returned
##
# def avoidGoomba(self):
# return self.movement.left.value
##
# Movement from Mario when there is a Pipe in front of him
# @author Florian Weiskirchner
#
# @param movement this is a Enum with the movementoptions from COMPLEX_MOVEMENT
# @param isFalling is a bool which is true when Mario is falling and false when he is jumping or running
# @return a value from movement gets returned
##
def movementByPipe(self):
if self.isFalling:
return self.movement.NOOP.value
return self.movement.rightAB.value
##
# Movement from Mario when he is on a Pipe
# @author Florian Weiskirchner
#
# @param movement this is a Enum with the movementoptions from COMPLEX_MOVEMENT
# @param isFalling is a bool which is true when Mario is falling and false when he is jumping or running
# @return a value from movement gets returned
##
def movementOntopOfPipe(self):
if self.isFalling:
return self.movement.NOOP.value
return self.movement.right.value
##
# Movement from Mario when there is a Cooper in front of him
# @author Florian Weiskirchner
#
# @param movement this is a Enum with the movementoptions from COMPLEX_MOVEMENT
# @param isFalling is a bool which is true when Mario is falling and false when he is jumping or running
# @return a value from movement gets returned
##
def movementByCooper(self):
if self.isFalling:
return self.movement.NOOP.value
return self.movement.rightA.value
##
# This method returns the appropriate value for the action that is suited to handling a bottomless pit
# @author Emmanuel Najfar
#
# @param self obligatory parameter
# @return the value that corresponds to the "jumprunright" action
##
def movementByPit(self):
return self.movement.rightAB.value
##
# This method returns the appropriate value for the action that is suited to handling the stairs
# which are made up of "Hard Blocks". These stairs appear in all level types, except for Castle levels.
# @author Emmanuel Najfar
#
# @param self obligatory parameter
# @return the value that corresponds to the "jumpright" action
##
def movementByAscendingStairs(self):
if self.isFalling:
return self.movement.NOOP.value
return self.movement.rightA.value
##
# This method returns the appropriate value for the action that is suited to handling the descending stairs
# which are made up of "Hard Blocks". These stairs appear in all level types, except for Castle levels.
# @author Emmanuel Najfar
#
# @param self obligatory parameter
# @return the value that corresponds to the "jumprunright" action
##
def movementByDescendingStairs(self):
if self.isFalling:
return self.movement.NOOP.value
return self.movement.rightAB.value
| true |
8e86641fc710c5bdb05866889cccd20e9ca9c30a | Python | Stanleyli1984/myscratch | /lc/prob_44.py | UTF-8 | 840 | 3.25 | 3 | [] | no_license | class Solution:
# @param {string} s
# @param {string} p
# @return {boolean}
def isMatch(self, s, p):
array = [1] + [0] * len(s)
for p_char in p:
if not any(array):
return False
new_array = [0] * (len(s) + 1)
if p_char == '*':
for i in xrange(array.index(1), len(array)):
new_array[i] = 1
if p_char == '?':
for i in xrange(array.index(1), len(array)-1):
if array[i] == 1:
new_array[i+1] = 1
else:
for i in xrange(array.index(1), len(array)-1):
if array[i] == 1 and s[i] == p_char:
new_array[i+1] = 1
array = new_array
return True if array[-1] else False
| true |
c39f6b66522fe90414868ccd8639a91662b31b4e | Python | CiprianBodnar/CLM-laboratories | /laborator2/laborator2.py | UTF-8 | 5,160 | 3.375 | 3 | [] | no_license | from nltk.tokenize import word_tokenize, casual_tokenize
import re
corpusName = "corpus.txt"
startWithBigLettter = "^([A-Z])"
listOfAbrv = ["Mr", "Dr", "Lect"]
listOfName = ["a priori", "San Francisco"]
listOfHyphens = ["dati-i-l","dati-m-il","da-mi","s-a","i-am","mi-ai","l-ai","m-ai","m-a","te-a"]
def readCorpusFromFile(corpusName):
file = open(corpusName,"r")
return file.read()
#Task 1
def tokenizeText(text):
return casual_tokenize(text)
#Task 2
def checkIpAddresses(token):
#Se verifica daca token-ul gasit este de forma unei adrese IP
check = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",token)
if(check):
return True
return False
def concatIpAddress(listOfTokens):
#Se verifica daca exista token-uri consecutive care pot forma o adresa IP, apoi se concateneaza
# si se ia drept un singur token
newList = []
index = 0
while index < len(listOfTokens) :
if index < len(listOfTokens)-2 and (checkIpAddresses(listOfTokens[index] + listOfTokens[index + 1])):
newList.append(listOfTokens[index] + listOfTokens[index + 1])
index = index + 1
else:
if index < len(listOfTokens)-3 and (checkIpAddresses(listOfTokens[index] + listOfTokens[index + 1] + listOfTokens[index + 2])):
newList.append(listOfTokens[index] + listOfTokens[index + 1] + listOfTokens[index + 2])
index = index + 2
else:
newList.append(listOfTokens[index])
index = index + 1
return newList
#Task 3
def checkStartWith(token):
#Verificare daca incepe cu litera mare
return re.match(startWithBigLettter, token) or token in listOfAbrv
def checkForAbreviation(listOfTokens, index):
#Verificare daca exista abrevieri
return checkStartWith(listOfTokens[index]) and listOfTokens[index+1] == '.' and checkStartWith(listOfTokens[index+2])
def concatNames(listOfTokens):
#Daca sunt gasite abrevieri, se concateneaza cu urmatorul token daca acesta incepe cu o litera mare
newList = []
index = 0
while index< len(listOfTokens):
if index <=len(listOfTokens)-3 and checkForAbreviation(listOfTokens, index):
newList.append(listOfTokens[index] + listOfTokens[index+1] + " "+ listOfTokens[index+2])
index = index +2
else:
newList.append(listOfTokens[index])
index = index +1
return newList
#Task 4
def checkPhoneNumber(listOfTokens):
#Verifica daca exista token-uri consecutive care pot forma un numar de telefon si le concateneaza in unul singur
newList = []
index = 0
while index < len(listOfTokens):
if listOfTokens[index][-1] in ['-','/'] and listOfTokens[index + 1][0] in ['0','1','2','3','4','5','6','7','8','9']:
newList.append(listOfTokens[index]+listOfTokens[index+1])
index = index + 2
else:
newList.append(listOfTokens[index])
index = index + 1
return newList
def checkCompoundPhrases(listOfTokens):
#Verifica daca exista token-uri care pot forma expresii sau substantive compuse si le concateneaza
newList = []
index = 0
while index < len(listOfTokens)-1:
if (listOfTokens[index]+" "+listOfTokens[index + 1]) in listOfName :
newList.append(listOfTokens[index]+" "+listOfTokens[index + 1])
index = index + 2
else:
newList.append(listOfTokens[index])
index = index + 1
if(len(listOfTokens) - index ==1):
newList.append(listOfTokens[index])
return newList
#Task 5
def checkHyphens(listOfTokens):
newList = []
index = 0
while index< len(listOfTokens):
if listOfTokens[index] in listOfHyphens:
auxList = listOfTokens[index].split('-')
for token in auxList:
newList.append(token)
index = index + 1
else:
newList.append(listOfTokens[index])
index = index + 1
return newList
#Task 6
def checkDespSilabe(listOfTokens):
#Verifica daca exista cuvinte despartite in silabe, astfel uneste cele doua token-uri, eliminand cratima ce le desparte
newList = []
index = 0
while index < len(listOfTokens) - 1:
if listOfTokens[index + 1] == '-':
newList.append(listOfTokens[index]+listOfTokens[index + 2])
index = index + 2
else:
newList.append(listOfTokens[index])
index = index + 1
if(len(listOfTokens) - index ==1):
newList.append(listOfTokens[index])
return newList
####
def printList(listToPrint):
for element in listToPrint:
print(element)
if __name__ == "__main__":
listOfTokens = tokenizeText(readCorpusFromFile(corpusName))
listOfTokens =checkDespSilabe(listOfTokens)
listOfTokens = concatIpAddress(listOfTokens)
listOfTokens = concatNames(listOfTokens)
listOfTokens = checkPhoneNumber(listOfTokens)
listOfTokens = checkCompoundPhrases(listOfTokens)
listOfTokens = checkHyphens(listOfTokens)
printList(listOfTokens)
| true |
2d93554de200680f7307cac53dbfc84f8dc54ffc | Python | ach-raf/lacor_es_scrapping | /lacor_products_scrapping/lacor_products_scrapping/spiders/products.py | UTF-8 | 1,950 | 2.828125 | 3 | [] | no_license | import scrapy
class ProductsSpider(scrapy.Spider):
name = "products"
def start_requests(self):
allowed_domains = ['http://lacor.es']
start_urls = ['http://lacor.es/eng/catalogo/chef-sets/4335/%s/' % index for index in range(1, 2)]
for url in start_urls:
yield scrapy.Request(url=url, callback=self.parse)
@staticmethod
def strip(string):
return string.strip().replace('>\xa0', '')
def parse(self, response):
# url_example:http://lacor.es/eng/catalogo/chef-sets/4335/
# split the url by '/' and take the 4th item from last, chef-sets in this example
# page_name = response.url.split('/')[-4]
all_products = response.xpath('/html/body/div/div[2]/section/child::*') # /html/body/div/div[2]/section
# image_url = ''
# categories = [self.strip(response.xpath('/html/body/div/div[2]/section/h2/span/text()').extract_first())]
for product in all_products:
title = str(product.xpath('.//p/a/text()').extract_first())
if title != 'None':
# image_url = 'http://lacor.es' + product.xpath('.//a/img/@src').extract_first()
product_url = 'http://lacor.es' + product.xpath('.//p/a/@href').extract_first()
"""my_product = {'title': title, 'categories': categories,
'image_url': image_url, 'product_url': product_url}
yield {
'title': title,
'categories': categories,
'image_url': image_url,
'product_url': product_url,
}"""
yield scrapy.Request(product_url, callback=self.parse_product)
def parse_product(self, response):
self.log('test')
print('==========================')
print(f'hello {response}')
tt = 'http://lacor.es/images/productos/53828p.jpg'
print(tt.split('/')[-1]) | true |
d1b00b89034f4a8598679d73bd2ae162a73135f6 | Python | manishapme/hb_ratings_prediction | /server.py | UTF-8 | 4,357 | 2.8125 | 3 | [] | no_license | """Movie Ratings."""
from jinja2 import StrictUndefined
from flask import Flask, render_template, redirect, request, flash, session
from flask_debugtoolbar import DebugToolbarExtension
from model import (User, Rating, Movie, connect_to_db, db, get_user_by_email, add_user,
get_user_by_email_and_password, add_rating, update_rating)
app = Flask(__name__)
# Required to use Flask sessions and the debug toolbar
app.secret_key = "ABC"
# Normally, if you use an undefined variable in Jinja2, it fails
# silently. This is horrible. Fix this so that, instead, it raises an
# error.
app.jinja_env.undefined = StrictUndefined
@app.route('/')
def index():
"""Homepage."""
return render_template("homepage.html")
@app.route('/users')
def user_list():
"""Show list of users."""
users = User.query.all()
return render_template('user_list.html', users=users)
@app.route('/users/<user_id>')
def user_detail(user_id):
"""Show details for one user."""
result = User.query.get(user_id)
return render_template('user_detail.html', user=result)
@app.route('/movies')
def movie_list():
"""Show list of movies."""
#When using order_by(Classname.attribute) and .all() ALWAYS at the end
movies = Movie.query.order_by(Movie.title).all()
return render_template('movie_list.html', movies=movies)
@app.route('/movies/<movie_id>')
def movie_detail(movie_id):
"""Show details for one movie."""
result = Movie.query.get(movie_id)
return render_template('movie_detail.html', movie=result)
@app.route('/rating', methods=['POST'])
def rating_set():
"""Create or update rating for logged in user."""
user_id = session['user_id']
movie_id = request.form.get('movie_id')
score = request.form.get('rating')
result = Rating.query.filter_by(user_id=user_id, movie_id=movie_id).first()
if result:
flash('Your score of %s has been updated' % score)
update_rating(user_id, movie_id, score)
else:
flash('Your score of %s has been added' % score)
add_rating(user_id, movie_id, score)
return redirect('/users/%s' % user_id)
#User.query.filter_by(email=email, password=password).first()
@app.route('/register', methods=['GET', 'POST'])
def register_user():
"""Register or sign up user"""
#post requests mean they've submitted form on register.html
if request.method == 'POST':
user_email = request.form.get('email')
user_password = request.form.get('password')
user_age = int(request.form.get('age'))
user_zipcode = request.form.get('zipcode')
result = get_user_by_email(user_email) #querying DB for username
if result:
##SHOW ALERT, "username exists"
flash('That %s already exists. Please login or use a different email' % user_email)
return redirect('/register')
else:
add_user(user_email, user_password, user_age, user_zipcode)
flash('%s has been successfully registered and logged in.' % user_email)
session['user_id'] = result.user_id
return redirect('/')
else:
# coming from link on homepage.html
return render_template("register.html")
@app.route('/login', methods=['GET', 'POST'])
def login_user():
"""Login existing user."""
if request.method == 'POST':
user_email = request.form.get('email')
user_password = request.form.get('password')
result = get_user_by_email_and_password(user_email, user_password)
if result:
flash('Hello %s, you are logged in' % user_email)
session['user_id'] = result.user_id
return redirect('/users/%s' % result.user_id)
else:
flash('Error, %s and password did not match a registered user' % user_email)
return redirect('/login')
else:
return render_template('login.html')
@app.route('/logout')
def logout_user():
"""logout user"""
flash('Logged out')
del session['user_id']
return redirect('/')
if __name__ == "__main__":
# We have to set debug=True here, since it has to be True at the
# point that we invoke the DebugToolbarExtension
app.debug = True
connect_to_db(app)
# Use the DebugToolbar
DebugToolbarExtension(app)
app.run()
| true |
4a749dd615da92bb7914012001fb76e187024da0 | Python | adayofmercury/TIL | /boj/11279.py | UTF-8 | 487 | 2.921875 | 3 | [] | no_license | import sys
import heapq
input = sys.stdin.readline
li = []
for _ in range(int(input())) :
command = int(input())
if command == 0 :
if li :
a = heapq.heappop(li)
print(-a)
else :
print(0)
else :
heapq.heappush(li, -command)
# heapq는 최소힙이다, 파이썬은 최대 힙을 지원하지 않기 때문에 부호를 반대로 하는 등의 트릭을 통해 최대 힙을 구현해야 | true |
03b59f3fc010d5071d499f00c1551183b4b2c059 | Python | TheCamilovisk/WagonDetection | /wagon_tracking/utils.py | UTF-8 | 152 | 2.640625 | 3 | [
"MIT"
] | permissive | import os
import sys
def get_realpath(path):
return os.path.abspath(os.path.expanduser(path))
def warning(msg):
print(msg, file=sys.stderr)
| true |
c1b254bf582325a4706785f35ca1e6a9560e9273 | Python | Daransoto/holbertonschool-machine_learning | /math/0x04-convolutions_and_pooling/4-convolve_channels.py | UTF-8 | 1,951 | 3.4375 | 3 | [] | no_license | #!/usr/bin/env python3
""" This module contains the function convolve_channels. """
import numpy as np
def convolve_channels(images, kernel, padding='same', stride=(1, 1)):
"""
Performs a convolution on images with channels.
images is a numpy.ndarray with shape (m, h, w, c) containing multiple
images.
m is the number of images.
h is the height in pixels of the images.
w is the width in pixels of the images.
c is the number of channels in the image.
kernel is a numpy.ndarray with shape (kh, kw, c) containing the kernel for
the convolution.
kh is the height of the kernel.
kw is the width of the kernel.
padding is either a tuple of (ph, pw), same, or valid.
if same, performs a same convolution.
if valid, performs a valid convolution.
if a tuple:
ph is the padding for the height of the image.
pw is the padding for the width of the image.
the image is padded with 0s.
stride is a tuple of (sh, sw).
sh is the stride for the height of the image.
sw is the stride for the width of the image.
Returns: a numpy.ndarray containing the convolved images.
"""
kh, kw, _ = kernel.shape
m, imh, imw, c = images.shape
sh, sw = stride
if type(padding) == tuple:
ph, pw = padding
elif padding == 'same':
ph = int(((imh - 1) * sh - imh + kh) / 2) + 1
pw = int(((imw - 1) * sw - imw + kw) / 2) + 1
else:
ph = pw = 0
padded = np.pad(images, ((0,), (ph,), (pw,), (0,)))
ansh = int((imh + 2 * ph - kh) / sh + 1)
answ = int((imw + 2 * pw - kw) / sw + 1)
ans = np.zeros((m, ansh, answ))
for i in range(ansh):
for j in range(answ):
x = i * sh
y = j * sw
ans[:, i, j] = (padded[:, x: x + kh, y: y + kw, :] *
kernel).sum(axis=(1, 2, 3))
return ans
| true |
71b90444315f1ee092710f841b0b4c4f903567de | Python | watsjustice/qwe | /Parser/parser.py | UTF-8 | 3,920 | 2.671875 | 3 | [] | no_license | import requests
import json
from bs4 import BeautifulSoup as bs
headers = {
'UserAgent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'
}
q = 'https://www.gurufocus.com/stock/AAPL/summary'
r = requests.get(url = q).text #, headers = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36')
data = bs(r , 'lxml').find_all('tr' , class_ = 'stock-indicators-table-row')
#собираем заголовки
data_1 , data_2 , data_3 , data_4 , data_5 = {} , {} , {} , {} , {}
item_barrel = ''
for x , item in enumerate(data):
if x == 8: next
#заголовок
item_titles = f'{item.text}'.strip().replace('\n' , '').replace(' ' , '-').split('--')[0]
#текущее значение
item_current_values = f'{item.text}'.strip().replace('\n' , '').replace(' ' , '-').split('--')[1]
#Barr №1
if x != 8:
try:
item_persents_vsIndustry = item.find('div' , class_ = 'indicator-progress-bar').select('div')
item_persents_vsIndustry = str(item_persents_vsIndustry)[str(item_persents_vsIndustry).index(':')+1:str(item_persents_vsIndustry).index(';')]
except:
item_persents_vsIndustry = item.find('i' , class_ = 'bar-indicator gf-icon-caret-up')
item_persents_vsIndustry = str(item_persents_vsIndustry)[str(item_persents_vsIndustry).index(':')+1:str(item_persents_vsIndustry).index(';')]
#Barr №2
item_persents_vsHistory = item.select('div')[-1].get('style')
item_persents_vsHistory = str(item_persents_vsHistory)[str(item_persents_vsHistory).index(':')+1:str(item_persents_vsHistory).index(';')]\
#if str(item_persents_vsHistory)[str(item_persents_vsHistory).index(':')+1:str(item_persents_vsHistory).index(';')].isnumeric() else 'No data...'
#Barr №3
if x == 7:
item_barrel = str(item.find('div' , class_ = 'bar-step').get('style')).split(':')[1][:-1].strip()
item_index = str(item.find(class_ = 'bar-indicator gf-icon-caret-up').get('style')).split(':')[1][:-1].strip()
data_1[7] = (item_titles , item_current_values , f'Not manipulator : {item_barrel}%' , f'Manipulator : {100-float(item_barrel[:-1])}%' ,\
f'Index : {item_index}')
#составление 5 словарей
if x < 7:
data_1[x] = (item_titles , f'Current value : {item_current_values}' , f'vsIndusrty {item_persents_vsIndustry}' , f'vsHistory {item_persents_vsHistory}')
if x > 7 and x < 17:
data_2[x] = (item_titles , f'Current value : {item_current_values}' , f'vsIndusrty {item_persents_vsIndustry}' , f'vsHistory {item_persents_vsHistory}')
if x > 16 and x < 35:
data_3[x] = (item_titles , f'Current value : {item_current_values}' , f'vsIndusrty {item_persents_vsIndustry}' , f'vsHistory {item_persents_vsHistory}')
if x > 34 and x < 41:
data_4[x] = (item_titles , f'Current value : {item_current_values}' , f'vsIndusrty {item_persents_vsIndustry}' , f'vsHistory {item_persents_vsHistory}')
if x > 41:
data_5[x] = (item_titles , f'Current value : {item_current_values}' , f'vsIndusrty {item_persents_vsIndustry}' , f'vsHistory {item_persents_vsHistory}')
thelist_of_barrels = [data_1 , data_2 , data_3 , data_4 , data_5] #список для перебора
thelist_of_titles = [
'Financial Strength' , 'Profitability Rank' , 'Valuation Rank' ,
'Dividend & Buy Back' , 'Valuation & Return'
]#список для перебора
#ROI and WACC
item = str(data[8].find_all(class_ = 'bar-step')).split(';')
q1 = item[2].split(' ')[1][:6]
q2 = item[-1].split(' ')[1][:6].replace('\n' , '').strip()
data_1[8] = (f'WACC : {q1}' , f'ROIC : {q2}')
#создание 5 файлов
for i in range(5):
with open(f'{thelist_of_titles[i]}.json' , 'w') as file:
json.dump(thelist_of_barrels[i], file , indent = 4 , ensure_ascii = False)
| true |
5fd6c12b577a10ec9182a4400555d289449d0873 | Python | jmccormac01/DIAPL2 | /DIAPL_PlotStars.py | UTF-8 | 27,654 | 2.640625 | 3 | [] | no_license | # ----------------------------------------------------------------------------------
# Description
# ----------------------------------------------------------------------------------
#
# DIAPL_PlotStars.py - a program to filter out the variable stars
#
#
# ----------------------------------------------------------------------------------
# Update History
# ----------------------------------------------------------------------------------
# 31/10/11 - code writen
# 31/10/11 - code tested
# 30/11/11 - added outut for phased files to plot with gnuplot
# 08/12/11 - added error scaling to SExtractor mean
# added errors to plots and outputs etc
#
# Test1: Try Tamuzing!
#
# Result: NO REAL CHANGE FROM TAMUZING!
#
# Test2: Address the systematics problem try several things.
#
# HJD values from header match the star files exactly!
#
# 1 - only use observations from >40 deg in elevation
# 2 - exclude any frame with large FWHM
#
# write a program to batch process each set, making a list of FWHM
# and those images outside the desired altitude range.
#
# then filter all lightcurves against this list according to their hjd value
# output a new list of files that have been filtered
#
# then finally test rejecting extreme outliers before binning
#
# Result: NO NOTICABLE CHANGE REMOVING THESE POINTS!
from pylab import *
import pyfits as pf
import commands, sys
import os, os.path
import numpy as np
from numpy import *
from numpy.fft import *
###############################################
################# FUNCTIONS ###################
###############################################
""" Fast algorithm for spectral analysis of unevenly sampled data
The Lomb-Scargle method performs spectral analysis on unevenly sampled
data and is known to be a powerful way to find, and test the
significance of, weak periodic signals. The method has previously been
thought to be 'slow', requiring of order 10(2)N(2) operations to analyze
N data points. We show that Fast Fourier Transforms (FFTs) can be used
in a novel way to make the computation of order 10(2)N log N. Despite
its use of the FFT, the algorithm is in no way equivalent to
conventional FFT periodogram analysis.
Keywords:
DATA SAMPLING, FAST FOURIER TRANSFORMATIONS,
SPECTRUM ANALYSIS, SIGNAL PROCESSING
Example:
> import numpy
> import lomb
> x = numpy.arange(10)
> y = numpy.sin(x)
> fx,fy, nout, jmax, prob = lomb.fasper(x,y, 6., 6.)
Reference:
Press, W. H. & Rybicki, G. B. 1989
ApJ vol. 338, p. 277-280.
Fast algorithm for spectral analysis of unevenly sampled data
bib code: 1989ApJ...338..277P
"""
def __spread__(y, yy, n, x, m):
"""
Given an array yy(0:n-1), extirpolate (spread) a value y into
m actual array elements that best approximate the "fictional"
(i.e., possible noninteger) array element number x. The weights
used are coefficients of the Lagrange interpolating polynomial
Arguments:
y :
yy :
n :
x :
m :
Returns:
"""
nfac=[0,1,1,2,6,24,120,720,5040,40320,362880]
if m > 10. :
print 'factorial table too small in spread'
return
ix=long(x)
if x == float(ix):
yy[ix]=yy[ix]+y
else:
ilo = long(x-0.5*float(m)+1.0)
ilo = min( max( ilo , 1 ), n-m+1 )
ihi = ilo+m-1
nden = nfac[m]
fac=x-ilo
for j in range(ilo+1,ihi+1): fac = fac*(x-j)
yy[ihi] = yy[ihi] + y*fac/(nden*(x-ihi))
for j in range(ihi-1,ilo-1,-1):
nden=(nden/(j+1-ilo))*(j-ihi)
yy[j] = yy[j] + y*fac/(nden*(x-j))
def fasper(x,y,ofac,hifac, MACC=4):
""" function fasper
Given abscissas x (which need not be equally spaced) and ordinates
y, and given a desired oversampling factor ofac (a typical value
being 4 or larger). this routine creates an array wk1 with a
sequence of nout increasing frequencies (not angular frequencies)
up to hifac times the "average" Nyquist frequency, and creates
an array wk2 with the values of the Lomb normalized periodogram at
those frequencies. The arrays x and y are not altered. This
routine also returns jmax such that wk2(jmax) is the maximum
element in wk2, and prob, an estimate of the significance of that
maximum against the hypothesis of random noise. A small value of prob
indicates that a significant periodic signal is present.
Reference:
Press, W. H. & Rybicki, G. B. 1989
ApJ vol. 338, p. 277-280.
Fast algorithm for spectral analysis of unevenly sampled data
(1989ApJ...338..277P)
Arguments:
X : Abscissas array, (e.g. an array of times).
Y : Ordinates array, (e.g. corresponding counts).
Ofac : Oversampling factor.
Hifac : Hifac * "average" Nyquist frequency = highest frequency
for which values of the Lomb normalized periodogram will
be calculated.
Returns:
Wk1 : An array of Lomb periodogram frequencies.
Wk2 : An array of corresponding values of the Lomb periodogram.
Nout : Wk1 & Wk2 dimensions (number of calculated frequencies)
Jmax : The array index corresponding to the MAX( Wk2 ).
Prob : False Alarm Probability of the largest Periodogram value
MACC : Number of interpolation points per 1/4 cycle
of highest frequency
History:
02/23/2009, v1.0, MF
Translation of IDL code (orig. Numerical recipies)
"""
#Check dimensions of input arrays
n = long(len(x))
if n != len(y):
print 'Incompatible arrays.'
return
nout = 0.5*ofac*hifac*n
nfreqt = long(ofac*hifac*n*MACC) #Size the FFT as next power
nfreq = 64L # of 2 above nfreqt.
while nfreq < nfreqt:
nfreq = 2*nfreq
ndim = long(2*nfreq)
#Compute the mean, variance
ave = y.mean()
##sample variance because the divisor is N-1
var = ((y-y.mean())**2).sum()/(len(y)-1)
# and range of the data.
xmin = x.min()
xmax = x.max()
xdif = xmax-xmin
#extirpolate the data into the workspaces
wk1 = zeros(ndim, dtype='complex')
wk2 = zeros(ndim, dtype='complex')
fac = ndim/(xdif*ofac)
fndim = ndim
ck = ((x-xmin)*fac) % fndim
ckk = (2.0*ck) % fndim
for j in range(0L, n):
__spread__(y[j]-ave,wk1,ndim,ck[j],MACC)
__spread__(1.0,wk2,ndim,ckk[j],MACC)
#Take the Fast Fourier Transforms
wk1 = ifft( wk1 )*len(wk1)
wk2 = ifft( wk2 )*len(wk1)
wk1 = wk1[1:nout+1]
wk2 = wk2[1:nout+1]
rwk1 = wk1.real
iwk1 = wk1.imag
rwk2 = wk2.real
iwk2 = wk2.imag
df = 1.0/(xdif*ofac)
#Compute the Lomb value for each frequency
hypo2 = 2.0 * abs( wk2 )
hc2wt = rwk2/hypo2
hs2wt = iwk2/hypo2
cwt = sqrt(0.5+hc2wt)
swt = sign(hs2wt)*(sqrt(0.5-hc2wt))
den = 0.5*n+hc2wt*rwk2+hs2wt*iwk2
cterm = (cwt*rwk1+swt*iwk1)**2./den
sterm = (cwt*iwk1-swt*rwk1)**2./(n-den)
wk1 = df*(arange(nout, dtype='float')+1.)
wk2 = (cterm+sterm)/(2.0*var)
pmax = wk2.max()
jmax = wk2.argmax()
#Significance estimation
#expy = exp(-wk2)
#effm = 2.0*(nout)/ofac
#sig = effm*expy
#ind = (sig > 0.01).nonzero()
#sig[ind] = 1.0-(1.0-expy[ind])**effm
#Estimate significance of largest peak value
expy = exp(-pmax)
effm = 2.0*(nout)/ofac
prob = effm*expy
if prob > 0.01:
prob = 1.0-(1.0-expy)**effm
return wk1,wk2,nout,jmax,prob
def getSignificance(wk1, wk2, nout, ofac):
""" returns the peak false alarm probabilities
Hence the lower is the probability and the more significant is the peak
"""
expy = exp(-wk2)
effm = 2.0*(nout)/ofac
sig = effm*expy
ind = (sig > 0.01).nonzero()
sig[ind] = 1.0-(1.0-expy[ind])**effm
return sig
def ReadStar(file,err_yn):
if err_yn == 1:
time,flux,err,sky=np.loadtxt(file,usecols=[0,1,2,3],unpack=True)
return time,flux,err,sky
if err_yn != 1:
time,flux=np.loadtxt(file,usecols=[0,1],unpack=True)
return time,flux
def MakeFitsTable(x,y):
from pyfits import Column
c1=Column(name='x', format='E', array=x)
c2=Column(name='y', format='E', array=y)
tbhdu=pf.new_table([c1,c2])
#print tbhdu.header.ascardlist()
name ='StarPosXY.fits'
if os.path.isfile(name) == True:
os.system('rm -rf StarPosXY.fits')
tbhdu.writeto(name)
return 0
def WCS_xy2rd():
if os.path.isfile('StarPosRaDec.fits') == True:
os.system('rm -rf StarPosRaDec.fits')
os.system('wcs-xy2rd -w /Volumes/DATA/nites/Results/M71/M71Solved/tpl.wcs -i StarPosXY.fits -o StarPosRaDec.fits')
return 0
def GetRaDec():
RA,DEC=[],[]
t=pf.open('StarPosRaDec.fits')
tbdata=t[1].data
for i in range(0,len(tbdata)):
ra=tbdata[i][0]
dec=tbdata[i][1]
ra1=(ra/15)
ra2=(fmod(ra1,1)*60)
ra3=(fmod(ra2,1)*60)
if len(str(ra3).split('.')[0]) < 2:
ra3="0"+str(ra3)
ratot="%02d:%02d:%s" % (int(ra1),int(ra2),str(ra3)[:5])
RA.append(ratot)
dec1=dec
dec2=(fmod(dec1,1)*60)
dec3=(fmod(dec2,1)*60)
if len(str(dec3).split('.')[0]) < 2:
dec3="0"+str(dec3)
dectot="%02d:%02d:%s" % (dec1,dec2,str(dec3)[:5])
DEC.append(dectot)
return RA,DEC
def GetPos(starid,section,p):
command='/Volumes/DATA/nites/Results/M71/Photometry/Batch1/A8.0D12S8C12/%s/M71_%s.coo' % (section, section)
f=open(command).readlines()
for i in range(0,len(f)):
num,x,y=f[i].split()
if int(num) == starid:
xk=np.empty(1)
yk=np.empty(1)
# keep x and y
xk[0]=float(x)
yk[0]=float(y)
imx=x
imy=y
if p > 0:
print "X Y: %.2f %.2f" % (xk[0],yk[0])
# get image subsection coords into tpl full
# frame coords for RA and DEC calculations
if section == '1_1':
# x(tplr1_1) = x(tpl) - 20 ; y(tplr1_1) = y(tpl) - 20
xk[0]=xk[0]-20.0
yk[0]=yk[0]-20.0
if p > 0:
print "x(tp1): %.2f y(tpl): %.2f" % (xk[0],yk[0])
if section == '1_2':
# x(tplr1_2) = x(tpl) - 20 ; y(tplr1_2) = y(tpl) + 492
xk[0]=xk[0]-20.0
yk[0]=yk[0]+492.0
if p > 0:
print "x(tp1): %.2f y(tpl): %.2f" % (xk[0],yk[0])
if section == '2_1':
# x(tplr1_2) = x(tpl) + 492 ; y(tplr1_2) = y(tpl) - 20
xk[0]=xk[0]+492.0
yk[0]=yk[0]-20.0
if p > 0:
print "x(tp1): %.2f y(tpl): %.2f" % (xk[0],yk[0])
if section == '2_2':
# x(tplr1_2) = x(tpl) + 492 ; y(tplr1_2) = y(tpl) + 492
xk[0]=xk[0]+492.0
yk[0]=yk[0]+492.0
if p > 0:
print "x(tp1): %.2f y(tpl): %.2f" % (xk[0],yk[0])
d1=MakeFitsTable(xk,yk)
if d1 != 0:
print "Problem making .fits table, exiting!"
sys.exit()
d2=WCS_xy2rd()
if d2 != 0:
print "Problem making .fits table, exiting!"
sys.exit()
ra,dec=GetRaDec()
for i in range(0,len(ra)):
if p > 0:
print "\n%s+%s" % (ra[i],dec[i])
return ra,dec,imx,imy
def GetFlux(section):
command='/Volumes/DATA/nites/Results/M71/Photometry/Batch1/A8.0D12S8C12/%s/M71_%s.flux' % (section, section)
tflux,tfluxerr=np.loadtxt(command,usecols=[3,4],unpack=True)
return tflux,tfluxerr
def GetVariablesAndRMS(templist,tflux):
stddev=np.empty(len(templist))
rms=np.empty(len(templist))
plot_flux=np.empty(len(templist))
# 1 night
stddev_1=np.empty(len(templist))
rms_1=np.empty(len(templist))
nframes=[]
# get the stddev for all
for i in range(0,len(templist)):
time,flux,err,sky=ReadStar(templist[i])
# add the template flux from Sextractor
starid=int(templist[i].split('_')[1])
flux=flux+tflux[(starid-1)]
stddev[i]=std(flux)
# get stddev for only data on 2011-08-04
c1=np.empty(len(time))
c2=np.empty(len(time))
for j in range(0,len(time)):
c1[j]=abs(time[j]-2455778.39028)
c2[j]=abs(time[j]-2455778.67986)
start=np.where(c1==min(c1))[0][0]
end=np.where(c2==min(c2))[0][0]
# get the fractional rms for all nights
# get the plot flux
rms[i]=stddev[i]/tflux[(starid-1)]
plot_flux[i]=tflux[(starid-1)]
# get the fractional rms for 2011-08-04
stddev_1[i]=std(flux[start:end])
rms_1[i]=stddev_1[i]/tflux[(starid-1)]
# only run this part when needed, typically once per batch
get_nightly=0
if get_nightly > 0:
# try getting the nightly stddev per lc
rms_nightly=GetNightlyRMS(templist,time,flux)
if get_nightly==0:
rms_nightly=0
nframes.append(len(flux))
print "[GetVariables] %d/%d" % ((i+1),len(templist))
# variables for investigation
n=np.where(stddev>(2*(median(stddev))))
# non-variables for RMS vs Flux plots
n2=np.where(stddev<(2*(median(stddev))))
# limit line for plot
limitx=[0,(len(templist))]
limity=[(median(stddev)*2),(median(stddev)*2)]
figure(2)
plot(stddev,'k-')
plot(limitx,limity,'r-')
ylabel('stddev')
xlabel('image number')
ylim(0,5000)
figure(3)
semilogx(plot_flux[n2],rms_1[n2],'r.')
ylabel('rms (mag)')
xlabel('flux')
show()
return n,n2,nframes,rms,rms_1,rms_nightly,plot_flux
def GetNightlyRMS(templist,time,flux):
rms_nightly=np.empty((len(templist),43))
start=[0]
end=[]
for j in range(0,len(time)-1):
if abs(time[j+1]-time[j]) > 0.5:
end.append(j)
start.append(j+1)
end.append(len(time)-1)
for j in range(0,len(start)):
rms_nightly[i,j]=(std(flux[start[j]:end[j]]))/tflux[(starid-1)]
return rms_nightly
def GetBestNight(rms_nightly):
loc=[]
for i in range(0,len(rms_nightly)):
loc.append(np.where(rms_nightly[i]==min(rms_nightly[i]))[0][0])
d={}
for i in set(loc):
d[i]=loc.count(i)
return d
def GetLombPeaks(fy,fx):
lombp=zip(fy,fx)
lombp.sort()
fysort,fxsort=zip(*lombp)
# makes a list of values, but they are backwards
# i.e. best period is last
peaks=list(fysort[-20:])
freqs=list(fxsort[-20:])
# reverse the values before returning them
peaks.reverse()
freqs.reverse()
return peaks, freqs
def MakeSimbadList(n,templist,section):
# name the file
name="simlist_%s.txt" % (section)
# check if it exists
# remove it if it does
if os.path.isfile(name) == True:
print "\nOverwritting old simlist file..."
command='rm -rf %s' % (name)
os.system(command)
# write out the data to file
f=open(name,'w')
for i in range(0,len(n[0])):
vstar=templist[n[0][i]]
starid=int(vstar.split('_')[1])
ra,dec,imx,imy=GetPos(starid,section,0)
line="%s+%s\n" % (ra[0],dec[0])
f.write(line)
f.close()
return 0
def MakeRegions(section,imx,imy,starid):
# Add new star to region file
# template region : circle(36.88,481.42,8) # text={94}
file='/Users/James/Documents/Observing/NITESObs/M71/Batch1/%s/%sVariables.reg' % (section,section)
# set up the file is not there already
if os.path.isfile(file) == False:
command='touch /Users/James/Documents/Observing/NITESObs/M71/Batch1/%s/%sVariables.reg' % (section,section)
os.system(command)
mf=open(file,'a')
templine1='# Region file format: DS9 version 4.1\n'
templine2='# Filename: tplr%s.fits\n' % (section)
templine3='global color=green dashlist=8 3 width=1 font="helvetica 10 normal" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\n'
templine4='physical\n'
mf.write(templine1)
mf.write(templine2)
mf.write(templine3)
mf.write(templine4)
mf.close()
f=open(file,'a')
line="circle(%.2f,%.2f,8) # text={%d}\n" % (float(imx),float(imy),starid)
f.write(line)
f.close()
return 0
def GetBinnedLc(time_n,flux,err,sxphe):
# zip lists and sort them in order of phase
# unzip for binning
temp=zip(time_n,flux,err)
temp.sort()
tsort,fsort,errsort=zip(*temp)
if sxphe < 1.0:
bin=1000.0
if sxphe > 0.0:
bin=len(flux)/3
# binning factor to give 'bin' points in final lc
bf=int(len(temp)/bin)
# binned arrays
tbinned=np.empty(bin)
fbinned=np.empty(bin)
errbinned=np.empty(bin)
for j in range(0,len(tbinned)):
tbinned[j]=average(tsort[(j*bf):bf*(j+1)])
fbinned[j]=average(fsort[(j*bf):bf*(j+1)])
errbinned[j]=average(errsort[(j*bf):bf*(j+1)])
return tbinned, fbinned, errbinned
def GetMags(flux):
mags=np.empty(len(flux))
for i in range(0,len(flux)):
mags[i]=(-2.5*log10(flux[i])) + 25.0
return mags
def GetTransit(tbinned,fbinned):
pvals=np.empty(len(tbinned))
transit_new=np.empty(len(tbinned))
transit_mag=np.empty(len(tbinned))
# masked array for low order polynomial fit
index=np.where((tbinned<0.2)+(tbinned>0.8))
print "1st or 2nd Order Fit?"
fittype = raw_input("(1/2): ")
if str(fittype) == '1':
# best line of fit for flux out of transit
coeffs=polyfit(tbinned[index],fbinned[index],1)
# best vals for mags
besty=polyval(coeffs,tbinned[index])
# finding p to fit the data -- equation -- p2xk^2 + p1xk + p0 =yk
for i in range(0,len(fbinned)):
pvals[i]=coeffs[1]+(coeffs[0]*tbinned[i])
for i in range(0,len(fbinned)):
transit_new[i]=fbinned[i]/pvals[i]
if str(fittype) == '2':
# best line of fit for flux out of transit
coeffs=polyfit(tbinned[index],fbinned[index],2)
# best vals for mags
besty=polyval(coeffs,tbinned[index])
# finding p to fit the data -- equation -- p2xk^2 + p1xk + p0 =yk
for i in range(0,len(fbinned)):
pvals[i]=coeffs[2]+(coeffs[1]*tbinned[i])+(coeffs[0]*(tbinned[i]*tbinned[i]))
for i in range(0,len(fbinned)):
transit_new[i]=fbinned[i]/pvals[i]
# remember to do errors later
for i in range(0,len(fbinned)):
transit_mag[i]=-2.5*log10(transit_new[i])
figure(20)
plot(tbinned,fbinned,'r.')
plot(tbinned[index],besty,'-k')
figure(21)
plot(tbinned,transit_new,'r.')
show()
return transit_mag
# print phased light curve for plotting in gnuplot
def PrepareTamuz(templist,nframes):
if os.path.exists('tamuz') == False:
os.mkdir('tamuz')
os.chdir('tamuz')
if os.path.exists('tamuz') == True:
os.chdir('tamuz')
for i in range(0,len(templist)):
if nframes[i]==25741:
if os.path.isfile(templist[i]) == False:
comm="cp ../%s ." % (templist[i])
os.system(comm)
return 0
def PrintFile(section,starid,time,time2,flux,err,period,bub):
savedir="/Volumes/DATA/nites/Results/M71/Photometry/Batch1/Variables/%s/final" % (section)
if os.path.exists(savedir) == False:
os.mkdir(savedir)
if bub == 1:
name = "%s/star_%05d_%s_b_FIN.lc.txt" % (savedir,starid, section)
if bub == 0:
name = "%s/star_%05d_%s_ub_FIN.lc.txt" % (savedir,starid, section)
t_out=np.concatenate((time,time2))
f_out=np.concatenate((flux,flux))
err_out=np.concatenate((err,err))
z=np.concatenate((t_out,f_out,err_out)).reshape(3,len(t_out)).transpose()
np.savetxt(name,z,fmt='%.8f %.5f %.5f')
# open the file and get contents
f=open(name,'r')
s=f.readlines()
f.close()
# reopen in to write title line and contents back
f=open(name,'w')
line="# Star: %05d Period: %.6f\n" % (starid,period)
f.write(line)
for i in range(0,len(s)):
f.write(s[i])
f.close()
return 0
def Normalize(starid,time,time2,flux,err,period,bub):
nf=np.copy(flux)
nf.sort()
norm_f=average(nf[-100:])
f_norm=flux/norm_f
f_mag=-2.5*log10(f_norm)
f_magerr=err/flux[0]
figure(10)
errorbar(time,f_mag,yerr=f_magerr,fmt='r.')
errorbar(time2,f_mag,yerr=f_magerr,fmt='r.')
gca().invert_yaxis()
title("Star %d (binned)" % (starid))
ylabel("Differential Magnitude")
xlabel("Phase")
show()
# work out V_max and dV after normalising
# 26.974 was worked out using AH 1971 standards
# see notes
Vmax=(-2.5*log10(norm_f))+26.974
dV=GetDeltaV(f_mag,bub)
print "V_max = %.2f [%.2f]" % (Vmax, norm_f)
print "dV = %.4f" % (dV)
print "Final Output?"
yn=raw_input("(e.g. y): ")
if str(yn) == 'y':
output=PrintFile(section,starid,time,time2,f_mag,f_magerr,period,bub)
if output != 0:
print "Problem printing output file, exiting!"
sys.exit()
return f_norm,f_mag,f_magerr
def GetPeriodError(section,starid):
file="/Volumes/DATA/nites/Results/M71/Photometry/Batch1/A8.0D12S8C12/%s/period/star_%05d_%s_logfile.dat" % (section,starid,section)
f=open(file).readlines()
period_err=float(f[-2].split()[-1])
return period_err
def GetDeltaV(f_mag,bub):
fmag_cp=np.copy(f_mag)
fmag_cp.sort()
if bub == 0:
v_min = average(fmag_cp[-100:])
v_max = average(fmag_cp[:100])
if bub == 1:
v_min = average(fmag_cp[-10:])
v_max = average(fmag_cp[:10])
dv=v_min-v_max
return dv
###############################################
################### MAIN ######################
###############################################
# toggles
var_rms = 0
make_simlist=0
prep_tamuz=0
run_p = 1
sxphe = 0
err_yn = 1
# get image list
templist=commands.getoutput('ls star_0016*.lc.txt').split('\n')
# get image subsection
section="%s_%s" % (templist[0].split('_')[2],templist[0].split('_')[3][0])
# get the sextractor fluxes
tflux,tfluxerr=GetFlux(section)
# find the variables and RMS's etc
if var_rms > 0:
n,n2,nframes,rms,rms_1,rms_nightly,plot_flux=GetVariablesAndRMS(templist,tflux)
if rms_nightly != 0:
d=GetBestNight(rms_nightly[n2])
n=(array([0]),)
# or use previous variables
#n=(array([0, 4, 5, 6, 47, 48, 49, 50, 54, 57, 58, 59, 84, 90, 91, 94, 119, 122, 123, 181, 182, 194, 206, 223, 228, 250, 251, 277, 280, 282, 283, 304, 321, 330, 362, 365, 377, 380, 398, 420, 436, 445, 447, 453, 467, 472, 475, 486, 491, 493, 494, 497, 502, 506, 508, 518, 522, 533, 548, 556, 604, 630, 633, 634, 635, 642, 662, 664, 665, 670, 677, 704, 714, 715, 717, 818, 824, 843, 851, 855, 896, 924, 930, 937]),) # M71 b1 1_1
# n=(array([2, 3, 5, 14, 16, 17, 29, 56, 81, 83, 102, 105, 121, 129, 130, 131, 133, 136, 139, 141, 150, 151, 157, 159, 174, 175, 185, 248, 251, 261, 262, 270, 274, 281, 285, 286, 287, 288, 290, 292, 296, 304, 305, 306, 307, 313, 314, 316, 323, 327, 336, 338, 342, 356, 363, 365, 368, 369, 390, 398, 411, 416, 417, 420, 423, 440, 445, 446, 457, 462, 463, 467, 472, 473, 474, 485, 494, 495, 502, 508, 512, 535, 538, 565, 566, 573, 574, 583, 600, 618, 637, 676, 688, 689, 693, 694, 705, 737, 751, 770, 771, 773, 775, 776, 777, 778, 779, 803, 806, 849, 865, 928, 935, 936, 1012, 1028, 1036, 1037, 1041, 1046, 1066, 1068, 1071, 1073, 1076, 1077, 1081, 1086, 1087, 1089, 1090, 1103, 1104]),) # M71 b1 1_2
# n=(array([0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 18, 21, 23, 24, 33, 37, 39, 40, 43, 44, 52, 62, 72, 79, 82, 87, 98, 99, 100, 108, 117, 118, 122, 130, 131, 138, 139, 148, 153, 159, 165, 167, 170, 171, 179, 180, 187, 196, 197, 198, 199, 208, 209, 210, 211, 214, 223, 236, 241, 242, 243, 244, 251, 314, 315, 322, 327, 331, 346, 348, 350, 351, 355, 367, 368, 369, 370, 373, 381, 383, 388, 389, 390, 391, 396, 402, 409, 415, 420, 421, 427, 445, 473, 488, 490, 492, 520, 527, 579, 591, 597, 603, 612, 614, 618, 621, 622, 623, 626, 632, 638, 666, 674, 678, 695, 698, 711, 717, 725, 726, 728, 743, 745, 748, 752, 753, 754, 762, 764, 765, 781, 798, 799, 807, 815, 849, 863, 872, 878, 892, 902, 906, 910, 914, 922, 931, 959]),) # M71 b1 2_1
# n=(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 15, 27, 30, 63, 185, 218, 232, 233, 245, 273, 280, 298, 300, 319, 323, 328, 329, 333, 334, 342, 346, 355, 356, 359, 360, 361, 362, 363, 364, 365, 369, 372, 376, 382, 386, 387, 391, 396, 397, 399, 402, 406, 407, 408, 417, 418, 426, 430, 436, 442, 443, 452, 455, 456, 457, 458, 459, 463, 467, 472, 482, 486, 498, 502, 503, 523, 537, 541, 578, 579, 648, 694, 702, 716, 724, 759, 761, 769, 771, 772, 775, 776, 777, 778, 786, 792, 856, 871, 889, 893, 894, 911, 912, 917, 921, 922, 923, 931, 941, 953, 986]),) # M71 b1 2_2
# Make a list for simbad?
if make_simlist > 0:
simlist=MakeSimbadList(n,templist,section)
if simlist != 0:
print "Problem making Simbad list, exiting..."
sys.exit()
# Prepare files for Tamuz
if prep_tamuz > 0:
done=PrepareTamuz(templist,nframes)
if done != 0:
print "Problem making preparing for Tamuz, exiting..."
sys.exit()
# Run period + phasing loop
if run_p > 0:
# now run lomb-scargle on the variables
for i in range(0,len(n[0])):
vstar=templist[n[0][i]]
if err_yn == 1:
time,flux,err,sky=ReadStar(vstar,err_yn)
if err_yn != 1:
time,flux=ReadStar(vstar,err_yn)
starid=int(vstar.split('_')[1])
# add the template flux from Sextractor
if sxphe < 1.0:
flux=flux+tflux[(starid-1)]
# run lomb-scargle
fx,fy, nout, jmax, prob = fasper(time,flux, 6., 6.)
# get error from scargle
period_err=GetPeriodError(section,starid)
# get top 20 peaks and periods
peaks,freqs=GetLombPeaks(fy,fx)
# get this as a check
ls_period=1/fx[jmax]
figure(4)
title('Lomb-Scargle')
ylabel('Power')
xlabel('Period')
plot((1/fx),fy,'r-')
xlim(0,50)
xticks(arange(0,52,2))
print "\n----------------------------------------------------------"
print "Star:\t\t\t%s [%d/%d]" % (templist[n[0][i]],(i+1),len(n[0]))
print "Template Flux:\t\t%f" % (tflux[(starid-1)])
print "Template Err:\t\t%f" % (tfluxerr[(starid-1)])
print "Number of Points:\t%d" % (len(flux))
for j in range (0,len(peaks)):
print "\tPeriod[%d]:\t%f" % ((j+1),(1/(freqs[j])))
#print "Removed %d exteme outliers" % (n_outliers)
print "----------------------------------------------------------\n"
print "LS Period: %f (%f)" % (ls_period,period_err)
print "Check periods!"
choice = 0.0
run=0
redo=0
while choice < 1.0:
# redo = 1 if only running 'gs'
# no need to plot everything again when only getting the coordinates
if redo < 1.0:
epochs=zeros(2000,float)
epoch=time[0]
if run < 1.0:
period=ls_period
#ra,dec,imx,imy=GetPos(starid,section,1)
# making regions is done!
#marked=MakeRegions(section,imx,imy,starid)
print "Star ID: %d\n" % (starid)
if run > 0.0:
period=pnew
print "New Period: %f" % (period)
time_n=np.empty(len(time))
for j in range(0,len(time)):
x=((time[j]-time[0])/period)%1.0
time_n[j]=x
if err_yn == 1:
# get binned lc
tbinned,fbinned,errbinned=GetBinnedLc(time_n,flux,err,sxphe)
# set min light to phase 0
loc=np.where(fbinned==min(fbinned))
tbinned=tbinned-tbinned[loc]
# double the number of cycles for plotting
tbinned2=np.empty(len(tbinned))
time_n2=np.empty(len(time_n))
for j in range(0,len(tbinned)):
tbinned2[j]=tbinned[j]+1.0
for j in range(0,len(time_n)):
time_n2[j]=time_n[j]+1.0
# get mags for plots
fluxm=GetMags(flux)
fbinnedm=GetMags(fbinned)
figure(5)
plot(time_n,flux,'r.')
if err_yn == 1:
plot(time_n2,flux,'r.')
title('Star %d: Raw Data (P=%.5f)' % (starid,period))
xlabel('Phase')
ylabel('Flux')
xlim(0,2.0)
if err_yn == 1:
figure(6)
plot(tbinned,fbinned,'r.')
plot(tbinned2,fbinned,'r.')
title('Star %d: Binned Data (P=%.5f)' % (starid,period))
xlabel('Phase')
ylabel('Flux')
#xlim(0,2.0)
show()
line=raw_input("")
if str(line[0]) == '0':
choice=float(line.split()[0])
pnew=float(line.split()[1])
run = run + 1
if str(line[0]) == '1':
choice=1.0
break
if str(line) == 'ft':
transit_mag=GetTransit(tbinned,fbinned)
redo = 1.0
choice = 0.0
if str(line) == 'pfb':
output=PrintFile(section,starid,tbinned,tbinned2,fbinned,errbinned,period,1)
if output != 0:
print "Problem printing output file, exiting!"
sys.exit()
choice = 1.0
if str(line) == 'pfub':
output=PrintFile(section,starid,time_n,time_n2,flux,err,period,0)
if output != 0:
print "Problem printing output file, exiting!"
sys.exit()
choice = 1.0
if str(line) == 'normb':
f_norm,f_mag,f_magerr=Normalize(starid,tbinned,tbinned2,fbinned,errbinned,period,1)
choice = 1.0
if str(line) == 'normub':
f_norm,f_mag,f_magerr=Normalize(starid,time_n,time_n2,flux,err,period,0)
choice = 1.0 | true |
84338670e54c5af3135425e0ab7d179d0d50c66d | Python | vdblm/Human-Machine-MDP | /environments/make_envs.py | UTF-8 | 9,574 | 3.359375 | 3 | [] | no_license | """
Environment types in the paper for both cell-based and sensor-based state spaces.
"""
from environments.episodic_mdp import GridMDP, EpisodicMDP
from environments.env_types import EnvironmentType
import numpy as np
# default number of features in sensor-based state space
N_FEATURE = 4
# default cell types
CELL_TYPES = ['road', 'grass', 'stone', 'car']
# default width and height
WIDTH, HEIGHT = 3, 10
# default costs
TYPE_COSTS = {'road': 0, 'grass': 2, 'stone': 4, 'car': 5}
# default episode length
EP_L = HEIGHT - 1
class FeatureStateHandler:
"""
Convert a feature vector to a state number and vice versa.
For example, if the cell types are ['road', 'grass', 'car'] and feature vector dim = 4, then
s = ('road', 'grass', 'road', 'car') <--> s = (0102) in base 3 = 11
"""
def __init__(self, types: list = CELL_TYPES, n_feature: int = N_FEATURE):
"""
Parameters
----------
types : list of str
All the cell types
n_feature : int
Dimension of the feature vector
"""
# types= ['road', 'car', ...]
if 'wall' not in types:
types.append('wall')
self.types = types
self.type_value = {}
for i, t in enumerate(self.types):
self.type_value[t] = i
self.base = len(self.types)
self.n_feature = n_feature
self.n_state = np.power(self.base, self.n_feature)
def feature2state(self, feature_vec: list):
"""
Parameters
----------
feature_vec : list of str
An input feature vector. The dimension should be
equal to `self.n_feature`
Returns
-------
state_num : int
The state number corresponding to the input feature vector
"""
assert len(feature_vec) == self.n_feature, 'input dimension not equal to the feature dimension'
values = [self.type_value[g] for g in feature_vec]
state_num = 0
for i, value in enumerate(values):
state_num += value * (self.base ** (len(values) - i - 1))
return state_num
def state2feature(self, state: int):
"""
Parameters
----------
state : int
An state number. It should satisfy the condition
`0 <= state < self.n_state`
Returns
-------
feature_vec : list
The feature vector corresponding to the input state number
"""
assert 0 <= state < self.n_state, 'invalid state number'
type_numbers = list(map(int, np.base_repr(state, self.base)))
for j in range(self.n_feature - len(type_numbers)):
type_numbers.insert(0, 0)
feature_vec = [self.types[i] for i in type_numbers]
return feature_vec
def make_feature_extractor(env_type: EnvironmentType):
types = list(env_type.type_probs.keys())
feat2state = FeatureStateHandler(types=types).feature2state
def sensor_feature_extractor(env, state):
width = env.width
cell_types = env.cell_types
x = state % width
y = state // width
f_s = [cell_types[x, y]]
f_s.extend([cell_types.get((x + i - 1, y + 1), 'wall') for i in range(3)])
return feat2state(f_s)
return sensor_feature_extractor
def grid_feature_extractor(env, state):
return state
def make_cell_based_env(env_type: EnvironmentType, width: int = WIDTH, height: int = HEIGHT,
type_costs: dict = TYPE_COSTS, start_cell: tuple = None):
"""
Generate an episodic MDP with cell-based state space.
Episode length is `height - 1`.
Parameters
----------
type_costs : dict[str, float]
Cost of each cell type. For example: {'road': 0, 'grass': 2, ...}
env_type : EnvironmentType
Specifies the environment type defined in the paper
start_cell : tuple
(x, y) coordinate of the starting cell. If `start_cell=None`,
then it will be the middle cell of the first row.
Returns
-------
env : GridMDP
The generated cell-based episodic MDP based on the environment type
"""
# actions = [left, straight, right]
n_action = 3
n_state = width * height
ep_l = height - 1
if start_cell is None:
start_cell = ((width - 1) // 2, 0)
# true costs and transitions
true_costs = np.zeros(shape=(n_state, n_action))
true_transitions = np.zeros(shape=(n_state, n_action, n_state))
# generate cell types
cell_types = env_type.generate_cell_types(width, height)
# the states corresponding to cell (x, y) will be `y * width + x`
for x in range(width):
for y in range(height):
state = y * width + x
# costs
cost = type_costs[cell_types[x, y]]
for action in range(n_action):
true_costs[state][action] = cost
# transitions
for action in range(n_action):
# the new cell after taking 'action'
x_n, y_n = x + action - 1, y + 1
# the top row
if y_n >= height:
y_n = y
# handle wall
is_wall = x_n < 0 or x_n >= width
if is_wall:
if x_n < 0:
s_n1 = y_n * width + 0
s_n2 = y_n * width + 1
elif x_n >= width:
s_n1 = y_n * width + width - 1
s_n2 = y_n * width + width - 2
true_transitions[state][action][s_n1] = 0.5
true_transitions[state][action][s_n2] = 0.5
else:
s_n = y_n * width + x_n
true_transitions[state][action][s_n] = 1
start_state = start_cell[0] + start_cell[1] * width
env = GridMDP(n_state, n_action, ep_l, costs=true_costs, trans_probs=true_transitions,
start_state=start_state, width=width, height=height, cell_types=cell_types)
return env
def make_sensor_based_env(env_type: EnvironmentType, ep_l: int = EP_L, type_costs: dict = TYPE_COSTS,
n_feature: int = N_FEATURE):
"""
Generate an episodic MDP with sensor-based state space.
Parameters
----------
ep_l : int
Episode length
type_costs : dict[str, float]
Cost of each cell type. For example: {'road': 0, 'grass': 2, ...}
env_type : EnvironmentType
Specifies the environment type defined in the paper
n_feature : int
Dimension of the sensor-based measurements (i.e., feature vector)
Returns
-------
env : EpisodicMDP
The sensor-based episodic MDP based on the environment type
"""
def __find_pos(f):
# TODO only works for width=3. FIX IT
# positions: 0=left, 1=middle, 2=right
if f[1] == 'wall':
return 0
if f[3] == 'wall':
return 2
return 1
def __calc_prob(f_s, f_sn, a):
# raise exception when the action goes to wall
pos = __find_pos(f_s)
pos_n = __find_pos(f_sn)
if a != 1 and pos == a:
raise Exception('The action goes to wall')
check_correct_pos = pos + a - 1 == pos_n
if not check_correct_pos or f_sn[0] != f_s[a + 1]:
return 0
middle_cell = 3 - pos_n
middle_prob = type_probs[f_sn[middle_cell]] if middle_probs is None else middle_probs[f_sn[middle_cell]]
# calculate the probability
if pos_n == 0:
return 1 * type_probs[f_sn[2]] * middle_prob
if pos_n == 1:
return type_probs[f_sn[1]] * middle_prob * type_probs[f_sn[3]]
return middle_prob * type_probs[f_sn[2]] * 1
# actions = [left, straight, right]
n_action = 3
type_probs = env_type.type_probs
middle_probs = env_type.mid_lane_type_probs
# add 'wall' type
type_probs['wall'] = 0
if middle_probs is not None:
middle_probs['wall'] = 0
type_costs['wall'] = max(type_costs.values()) + 1
f_s_handler = FeatureStateHandler(types=list(type_probs.keys()), n_feature=n_feature)
# number of states
n_state = f_s_handler.n_state
# true costs and transitions
true_costs = np.zeros(shape=(n_state, n_action))
true_transitions = np.zeros(shape=(n_state, n_action, n_state))
for state in range(n_state):
for action in range(n_action):
feat_vec = f_s_handler.state2feature(state)
true_costs[state][action] = type_costs[feat_vec[0]]
for nxt_state in range(n_state):
nxt_feat_vec = f_s_handler.state2feature(nxt_state)
# handle wall
# TODO the code works only when `n_feature = 4`. FIX IT
if __find_pos(feat_vec) == 0 and action == 0:
a1, a2 = 1, 2
elif __find_pos(feat_vec) == 2 and action == 2:
a1, a2 = 0, 1
else:
a1, a2 = action, action
true_transitions[state][action][nxt_state] = 0.5 * (__calc_prob(feat_vec, nxt_feat_vec, a1) +
__calc_prob(feat_vec, nxt_feat_vec, a2))
# Normalize
true_transitions[state][action] = true_transitions[state][action] / sum(true_transitions[state][action])
env = EpisodicMDP(n_state, n_action, ep_l, true_costs, true_transitions, start_state=0)
return env
| true |
d36e6208dc97717a599a4dcfd4de92efb63dfc45 | Python | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 046 - What Color Is That Square.py | UTF-8 | 490 | 4 | 4 | [] | no_license | # Exercise 46:What Color Is That Square?
l=input("Enter coordinate letter. ")
num=int(input("Enter coordinate number. "))
y=num % 2
x=num % 2
if l > "h" or num > 8:
print("Error,beyond letter h and number 8, data not allowed.")
elif l=="a" and y==0 or l=="b" and y==1 or l=="b" and y==1 or l=="c" and y==0 \
or l=="d" and y==1 or l=="e" and y==0 or l=="f" and y==1 or l=="g" and y==0 or l=="h" and y==1:
print ("The box is white.")
else:
print("The box is black.")
| true |
235688fc4f2e6d5a45674c1273fc4dcb1dc4dc84 | Python | howardpaget/CNTK-UWP-Example | /CNTKFitExample/CNTKFitExample.py | UTF-8 | 2,300 | 2.796875 | 3 | [] | no_license | # Adapted from this example: https://cntk.ai/pythondocs/CNTK_101_LogisticRegression.html
import cntk
import numpy as np
input_dim = 2
num_output_classes = 1
np.random.seed(0)
# Create features and labels that are dependent on them
features = np.asarray(np.random.random_sample((10000, 2)), dtype=np.float32)
labels = np.asarray([np.asarray([1 if 1 / (1 + np.exp(-(.2 * x[0] + .3 * x[1] - .5))) >= 0.5 else 0], np.float32) for x in features], dtype=np.float32)
#labels = np.asarray([np.asarray([1 / (1 + np.exp(-(.2 * x[0] + .3 * x[1] - .5)))], np.float32) for x in features], dtype=np.float32)
# Create the model, label = sigmoid(feature * W + b)
def create_model(input_var, output_dim):
weight = cntk.parameter(shape=(input_var.shape[0], output_dim), name='W')
bias = cntk.parameter(shape=(output_dim), name='b')
return cntk.sigmoid(cntk.times(input_var, weight) + bias, name='o')
feature = cntk.input_variable(input_dim, np.float32)
model = create_model(feature, num_output_classes)
# Set up inputs and functions used by the trainer
label = cntk.input_variable(num_output_classes, np.float32)
loss = cntk.squared_error(model, label)
eval_error = cntk.squared_error(model, label)
# Create the trianer using a stochastic gradient descent (sgd) learner
learning_rate = 0.5
lr_schedule = cntk.learning_parameter_schedule(learning_rate)
learner = cntk.sgd(model.parameters, lr_schedule)
trainer = cntk.Trainer(model, (loss, eval_error), [learner])
# Fit the model
for i in range(1000):
trainer.train_minibatch({feature: features, label: labels})
if i % 100 == 0:
print ('Batch: {0}, Loss: {1:.4f}, Error: {2:.2f}'.format(i, trainer.previous_minibatch_loss_average, trainer.previous_minibatch_evaluation_average))
# Save the model for later import into UWP app
model.save('../CNTKUWPApp/model.model')
# Evaluate the model on the training data
result = model.eval({feature : features})
predicted = [np.asarray([1], np.float32) if r >= 0.5 else np.asarray([0], np.float32) for r in result]
#predicted = [np.asarray([r], np.float32) for r in result]
comparison = np.abs(labels - predicted)
print('% Correct: {0:.4f}'.format(100 * (1 - np.sum(comparison) / comparison.shape[0])))
print('W: ', model.parameters[0].value)
print('b: ', model.parameters[1].value)
| true |
fbdda5cb06cdb554b0ce15354785aa755bb77f9c | Python | dblotsky/ipd2readable | /shatter.py | UTF-8 | 4,497 | 2.96875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
"""
Splits an IPD binary archive file into a more manageable JSON list of databases and records.
"""
import re
import json
import sys
import os
import argparse
HEADER = "Inter@ctive Pager Backup/Restore File"
class NoMoreBytes(Exception):
def __str__(self):
return "no more bytes"
# decorator to wrap TypeErrors into NoMoreBytes errors
# used on byte-reading functions to avoid too many 'if's
def safe_reader(f):
def wrapped(*args, **kwargs):
try:
return f(*args, **kwargs)
except TypeError as e:
raise NoMoreBytes()
return wrapped
@safe_reader
def read_short_le(f):
return ord(f.read(1)) + (ord(f.read(1)) << 8)
@safe_reader
def read_short(f):
return (ord(f.read(1)) << 8) + ord(f.read(1)) << 0
@safe_reader
def read_int_le(f):
return ord(f.read(1)) + (ord(f.read(1)) << 8) + (ord(f.read(1)) << 16) + (ord(f.read(1)) << 24)
@safe_reader
def read_int(f):
return (ord(f.read(1)) << 24) + (ord(f.read(1)) << 16) + (ord(f.read(1)) << 8) + ord(f.read(1))
@safe_reader
def read_byte(f):
return ord(f.read(1))
class Database(object):
def __init__(self, name):
self.name = name.rstrip("\x00")
self.records = []
def as_dict(self):
return {
"name": self.name,
"records": [record.as_dict() for record in self.records]
}
def __cmp__(self, other):
return cmp(self.name, other.name)
def __str__(self):
return "<Database {name!r} with {n} records>".format(name=self.name, n=len(self.records))
class Record(object):
def __init__(self, handle, uid):
self.handle = handle
self.uid = uid
self.fields = {}
def as_dict(self):
self_dict = {"uid": self.uid}
self_dict.update(self.fields)
return self_dict
def __str__(self):
return "<Record {uid} {f}>".format(uid=self.uid, f=self.fields)
def error(m):
sys.stderr.write(str(m) + "\n")
exit(1)
def main():
# build command-line argument parser
parser = argparse.ArgumentParser()
parser.add_argument(
"in_file",
help = "input IPD file"
)
# parse the args
args = parser.parse_args()
# check that input file exists
if not os.path.exists(args.in_file):
error("input file does not exist")
databases = []
# read the file
with open(args.in_file, "rb") as f:
# mandatory file header
header = f.read(len(HEADER))
assert header == HEADER, "Missing IPD file header"
# mandatory byte (carriage return)
assert f.read(1) == "\x0A", "Missing mandatory carriage return"
# get version and number of databases
version = ord(f.read(1))
num_databases = read_short(f)
# mandatory byte (null)
assert f.read(1) == "\x00", "Missing mandatory null byte"
# read names and create databases
for i in range(num_databases):
name_length = read_short_le(f)
name = f.read(name_length)
db = Database(name)
databases.append(db)
# catch for the NoMoreBytes exception
try:
# read until reading fails
while True:
# read the record header
record_db_id = read_short_le(f)
record_length = read_int_le(f)
record_db_version = read_byte(f)
record_handle = read_short_le(f)
record_unique_id = read_int(f)
# add the record to the db
record = Record(record_handle, record_unique_id)
db = databases[record_db_id]
db.records.append(record)
# read the rest of the record
already_read = 7
while already_read < record_length:
# read field
field_length = read_short_le(f)
field_type = read_byte(f)
field_data = f.read(field_length)
# set field on record
# NOTE: the fields may still be ugly binary, so we wrap them in repr()
record.fields[field_type] = repr(field_data)
already_read += field_length + 3
except NoMoreBytes as e:
pass
print json.dumps([database.as_dict() for database in databases])
if __name__ == '__main__':
main()
| true |
ca48f7b5dd3fc79ba7beca6d3237cc9fbcc19152 | Python | yalimohammadi/School-COVID | /Testing_Strategies/netwrok_based_random.py | UTF-8 | 583 | 2.9375 | 3 | [] | no_license | import random
def test_random_neighbor(school,test_cap,status):
testable = []
test_prob=test_cap*1./len(status.keys())
for v in status.keys():
if not(status[v]=="T"):
if random.uniform(0,1)<test_prob:
#now choose a neighbor of v
# note that if u appears two times as neighbors of a node, then there is a higher chance they appear
school
if test_cap>len(testable):
to_process_test=testable
else:
to_process_test = random.sample(testable, test_cap)
return to_process_test
| true |
bd31994e4458067dc8cf813159a862c3dec85f71 | Python | kugurst/music-recommender | /music/song.py | UTF-8 | 3,522 | 2.65625 | 3 | [] | no_license | import aifc
import base64
import hashlib
import os
import numpy as np
import scipy
from pydub import AudioSegment
from scipy import signal
from scipy.fftpack import fft
from util import os_utils
__all__ = ["Song", "SongSpectrogram", "SongFFT"]
_FFMPEG_ENV = "FFMPEG"
try:
AudioSegment.ffmpeg = os.environ[_FFMPEG_ENV]
except KeyError:
raise RuntimeError("[{}] is not defined. Specify the path to the ffmpeg binary in this variable".format(
_FFMPEG_ENV))
class Song(object):
def __init__(self, path, use_audio_segment=False):
self.__hash = None
self.__path = path
if os_utils.is_windows():
path = "\\\\?\\" + path
if use_audio_segment:
self.song = AudioSegment.from_file(path)
else:
self.song = aifc.open(path, 'rb')
@property
def path(self):
return self.__path
def __hash__(self):
if self.__hash is None:
self.__hash = Song.compute_path_hash(self.__path.encode())
return self.__hash
@staticmethod
def compute_path_hash(path):
m = hashlib.sha512()
m.update(path)
return base64.urlsafe_b64encode(m.digest()).decode('ascii')
class SongSpectrogram(object):
def __init__(self, frequency_series, time_series, spectrogram_series):
self.frequency_series = frequency_series
self.time_series = time_series
self.spectrogram_series = spectrogram_series
@staticmethod
def compute_spectrogram(left_samples_sets, right_samples_sets, frame_rate):
left_spectrograms, right_spectrograms = [], []
for left_samples_set, right_samples_set in zip(left_samples_sets,right_samples_sets):
f_right, t_right, Sxx_right = scipy.signal.spectrogram(right_samples_set, frame_rate, return_onesided=False)
f_left, t_left, Sxx_left = scipy.signal.spectrogram(left_samples_set, frame_rate, return_onesided=False)
left_spectrograms.append(SongSpectrogram(f_left, t_left, Sxx_left))
right_spectrograms.append(SongSpectrogram(f_right, t_right, Sxx_right))
return left_spectrograms, right_spectrograms
class SongFFT(object):
def __init__(self, amplitude_series, frequency_bins):
self.amplitude_series = amplitude_series
self.frequency_bins = frequency_bins
@staticmethod
def compute_ffts(left_samples_sets, right_samples_sets, frame_rate):
left_ffts, right_ffts = [], []
for left_samples_set, right_samples_set in zip(left_samples_sets,right_samples_sets):
# https://www.oreilly.com/library/view/elegant-scipy/9781491922927/ch04.html
X_left = scipy.fftpack.fft(left_samples_set)
X_right = scipy.fftpack.fft(right_samples_set)
freqs_left = scipy.fftpack.fftfreq(len(left_samples_set))
freqs_right = scipy.fftpack.fftfreq(len(right_samples_set))
X_left = np.abs(X_left[:int(len(X_left) / 2)])
X_right = np.abs(X_right[:int(len(X_right) / 2)])
freqs_left = freqs_left[:int(len(freqs_left) / 2)]
freqs_right = freqs_right[:int(len(freqs_right) / 2)]
freqs_left = freqs_left * frame_rate
freqs_right = freqs_right * frame_rate
left_ffts.append(SongFFT(X_left, freqs_left))
right_ffts.append(SongFFT(X_right, freqs_right))
return left_ffts, right_ffts
| true |
a3842b5644dda74b14c6feef658489b4b1cdb02d | Python | Lazy-coder-Hemlock/Leet_Code-Solutions | /318. Maximum Product of Word Lengths.py | UTF-8 | 308 | 2.78125 | 3 | [] | no_license | class Solution:
def maxProduct(self, words: List[str]) -> int:
res=0
for i in range(len(words)-1):
for j in range(i+1,len(words)):
if len(set(words[i]).intersection(words[j]))==0:
res=max(res,len(words[i])*len(words[j]))
return res
| true |
c8a68e5000c250b35182d842dc13c9a061a31d17 | Python | jcoombes/computing-year-2 | /relscript2.py | UTF-8 | 2,118 | 3.203125 | 3 | [
"Unlicense"
] | permissive | """
Tests the super_boost() method of FourVector class.
This second test ensures boost() has the same behaviour as super_boost() in 1d.
"""
from __future__ import division
import relativity as rel
import numpy as np
fail = False
a0 = rel.FourVector(0,[0,0,0]) #This could be done with a for loop and eval()
a1 = rel.FourVector(10,[0,0,0]) #But Explicit Is Better Than Implicit.
a2 = rel.FourVector(20,[0,0,0])
a3 = rel.FourVector(30,[0,0,0])
a4 = rel.FourVector(40,[0,0,0])
a5 = rel.FourVector(50,[0,0,0])
a6 = rel.FourVector(60,[0,0,0])
a7 = rel.FourVector(70,[0,0,0])
a8 = rel.FourVector(80,[0,0,0])
a9 = rel.FourVector(90,[0,0,0])
a10 = rel.FourVector(100,[0,0,0])
a = [a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10]
b0 = rel.FourVector(0,[0,0,50])
b1 = rel.FourVector(10,[0,0,50])
b2 = rel.FourVector(20,[0,0,50])
b3 = rel.FourVector(30,[0,0,50])
b4 = rel.FourVector(40,[0,0,50])
b5 = rel.FourVector(50,[0,0,50])
b6 = rel.FourVector(60,[0,0,50])
b7 = rel.FourVector(70,[0,0,50])
b8 = rel.FourVector(80,[0,0,50])
b9 = rel.FourVector(90,[0,0,50])
b10 = rel.FourVector(100,[0,0,50])
b = [b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10]
c0 = rel.FourVector(0,[15,20,65])
c1 = rel.FourVector(10,[15,20,65])
c2 = rel.FourVector(20,[15,20,65])
c3 = rel.FourVector(30,[15,20,65])
c4 = rel.FourVector(40,[15,20,65])
c5 = rel.FourVector(50,[15,20,65])
c6 = rel.FourVector(60,[15,20,65])
c7 = rel.FourVector(70,[15,20,65])
c8 = rel.FourVector(80,[15,20,65])
c9 = rel.FourVector(90,[15,20,65])
c10 = rel.FourVector(100,[15,20,65])
c = [c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10]
k0 = np.array([0,0,1])
k1 = np.array([0,0,2])
k2 = np.array([-0,0,15])
k3 = np.array([0,0,10000])
k = [k0,k1,k2,k3]
vectors = a + b + c
for vector in vectors:
for direction in k:
temp = rel.FourVector.boost(vector,0.866)
temp2 = rel.FourVector.super_boost(vector,0.866,direction)
if not(temp==temp2):
fail = True
print 'Fail! {} is not {},dir ={}'.format(temp,temp2,direction)
if temp2==temp:
print('.')
if not fail:
print('Success, super_boost -> then <- works in all directions.')
| true |
7e97e7c6013fa9da0dbccc16568cc74728f37831 | Python | zdamao/flask_crud | /main.py | UTF-8 | 3,068 | 2.515625 | 3 | [] | no_license | from flask import Flask, render_template, request , redirect , url_for
from db import dbconnection
from conversion import get_dict_resultset
import pandas as pd
conn = dbconnection()
cur = conn.cursor()
app = Flask(__name__)
@app.route('/contacts', methods=['GET','POST'])
@app.route('/contacts/<method>/<contact_id>', methods=['GET'])
def contacts(contact_id=None,method=None):
contact_id = contact_id or ''
method = method or ''
if (contact_id == ''):
if (request.method == 'GET'):
sql = "select * from contacts";
contacts = get_dict_resultset(sql)
return render_template('contacts.html',contacts=contacts)
elif (request.method == 'POST'):
firstname = request.form['firstname']
lastname = request.form['lastname']
phone_no = request.form['phone_no']
cur.execute("insert into contacts (firstname,lastname,phone_no) values(%s,%s,%s)",(firstname,lastname,phone_no));
conn.commit()
return redirect(url_for('contacts'))
else:
return redirect(url_for('contacts'))
else:
if (method == 'edit'):
sql = "select * from contacts";
contacts = get_dict_resultset(sql)
for i in contacts:
if int(contact_id) == int(i['contact_id']):
contact = i
return render_template('contacts.html',contacts=contacts,contact=contact)
elif (method == 'delete'):
cur.execute("DELETE FROM contacts WHERE contact_id = " + contact_id);
conn.commit();
return redirect(url_for('contacts'))
else:
return redirect(url_for('contacts'))
return redirect(url_for('contacts'))
@app.route('/contacts/update', methods=['POST'])
def update_contacts():
firstname = request.form['updatefirstname']
lastname = request.form['updatelastname']
phone_no = request.form['updatephone_no']
contact_id = request.form['contact_id']
cur.execute("update contacts SET firstname = %s , lastname = %s , phone_no = %s WHERE contact_id = %s" , (firstname,lastname,phone_no,contact_id));
conn.commit();
return redirect(url_for('contacts'))
@app.route('/contacts/export', methods=['GET','POST'])
def export_data():
sql = "select firstname,lastname,phone_no from contacts";
contacts = get_dict_resultset(sql)
df = pd.DataFrame(contacts)
df.to_excel (r'exportdbdata.xlsx', index = False, header=True)
return redirect(url_for('contacts'))
@app.route('/contacts/import', methods=['GET','POST'])
def import_data():
filedata = request.form['importexcel']
re = pd.read_excel(str(filedata), sheet_name='Sheet1')
final_res = re.to_dict('records')
for row in final_res:
cur.execute("insert into contacts (lastname,phone_no,firstname) values(%s,%s,%s)",(str(row['lastname']),str(row['phone_no']),str(row['firstname'])));
conn.commit()
return redirect(url_for('contacts'))
if __name__ == '__main__':
app.run() | true |
98c8dd347c44a97c8f7c511e1c2af76eea369911 | Python | arlandgoh/pycrawlers | /nba_players_crawler/TeamCrawlerBasicInfo_v1.0.py | UTF-8 | 7,370 | 2.625 | 3 | [] | no_license | import settings
from settings import delay
from settings import DATA_PATH, MAIN_URL
import os
import requests
from bs4 import BeautifulSoup
import pandas as pd
import sys
import re
import pdb
from datetime import datetime
import time
import numpy as np
def teams_basic_information():
teams_data_dir = os.path.join(DATA_PATH, "teams")
os.makedirs(teams_data_dir, exist_ok=True)
all_teams_09_path = os.path.join(teams_data_dir, "all_teams_info.csv")
teams = pd.read_csv(all_teams_09_path)
teams = teams[teams['team_url'].notna()] # Filter to get the franchises URL only
teams = teams[(teams['From'] >= '2009-10') | (teams['To'] >= '2009-10')]
for idx in teams.index:
info = {}
print("Scraping franchise for ", teams.loc[idx,'Franchise'], "||", teams.loc[idx,'Lg'])
# Backing Off #
team_url = teams.loc[idx,'team_url']
team_id = team_url.strip().split('/')[-2]
t0_request = time.time()
response = requests.get(team_url)
response_delay = time.time() - t0_request
if(response_delay > 10):
time.sleep(5*response_delay)
print('sleep')
##################
html_doc = response.text
soup = BeautifulSoup(html_doc, 'html.parser')
delay()
_div = soup.find(name="div", attrs = {'id': 'info'})
_h1 = _div.h1.span.text
print(_h1)
info['Franchise Name'] = _h1.strip()
for _ptag in _div.find_all('p'):
row = [text for text in _ptag.stripped_strings]
# Location
if(row[0] == 'Location:'):
info['Location'] = row[1].strip('\n\n\n \n ▪')
#print(info['Location'])
# Championships
elif(row[0] == 'Championships:'):
championships_list = row[1].split(';\n \n ')
championships_nba_aba = re.findall(r"\((.+)\)", championships_list[0])
if(championships_nba_aba):
championships_total = championships_list[0].split()[0]
info['Championships Total'] = int(championships_total)
championships_nba_aba_list = championships_nba_aba[0].split(' & ')
nba_championships_number = championships_nba_aba_list[0].split(' ')[0]
aba_championships_number = championships_nba_aba_list[1].split(' ')[0]
info['Championships NBA'] = int(nba_championships_number)
info['Championships ABA'] = int(aba_championships_number)
else:
championships_total = championships_list[0]
info['Championships Total'] = int(championships_total)
info['Championships NBA'] = int(championships_total)
info['Championships ABA'] = np.nan
print(info['Championships Total'])
print(info['Championships NBA'])
print(info['Championships ABA'])
# Team Name
elif(row[0] == 'Team Names:'):
info['Team'] = row[1]
print(info['Team'])
# Playoff Appearances
elif(row[0] == 'Playoff Appearances:'):
playoff_list = row[1].split(';\n \n ')
playoff_nba_aba = re.findall(r"\((.+)\)", playoff_list[0])
if(playoff_nba_aba):
playoff_total = playoff_list[0].split()[0]
info['Playoff Apprearances Total'] = int(playoff_total)
playoff_nba_aba_list = playoff_nba_aba[0].split(' & ')
nba_playoff_number = playoff_nba_aba_list[0].split(' ')[0]
aba_playoff_number = playoff_nba_aba_list[1].split(' ')[0]
info['Playoff NBA'] = int(nba_playoff_number)
info['Playoff ABA'] = int(aba_playoff_number)
else:
playoff_total = playoff_list[0]
info['Playoff Apprearances Total'] = int(playoff_total)
info['Playoff NBA'] = int(playoff_total)
info['Playoff ABA'] = np.nan
print(info['Playoff Apprearances Total'])
print(info['Playoff NBA'])
print(info['Playoff ABA'])
# Seasons
elif(row[0] == 'Seasons:'):
season_list = row[1].split(';\n \n ')
# Season from & to
season_from = season_list[1].split(' to ')[0]
season_to = season_list[1].split(' to ')[1]
season_nba_aba = re.findall(r"\((.+)\)", season_list[0])
if(season_nba_aba):
season_total = season_list[0].split()[0]
info['Season Total'] = season_total
info['Season From'] = season_from
info['Season To'] = season_to
season_nba_aba_list = season_nba_aba[0].split(' & ')
nba_season_number = season_nba_aba_list[0].split(' ')[0]
aba_season_number = season_nba_aba_list[1].split(' ')[0]
info['Season NBA'] = int(nba_season_number)
info['Season ABA'] = int(aba_season_number)
else:
season_total = season_list[0]
info['Season Total'] = season_total
info['Season From'] = season_from
info['Season To'] = season_to
info['Season NBA'] = int(season_total)
info['Season ABA'] = np.nan
print(info['Season From'])
print(info['Season To'])
print(info['Season Total'])
print(info['Season NBA'])
print(info['Season ABA'])
# Record
elif(row[0] == 'Record:'):
record_win_loss_total = row[1].split(',')[0].split('-')
record_win_total = record_win_loss_total[0]
record_loss_total = record_win_loss_total[1]
record_nba_aba = re.findall(r"\((.+)\)", row[1].split(',')[1])
if(record_nba_aba):
record_win_loss_percentage_list = row[1].split(' ')[1].split('\n \n ')
record_win_loss_percentage = float('0' + record_win_loss_percentage_list[0])
record_win_nba = int(record_nba_aba[0].split(' & ')[0].split()[0].split('-')[0])
record_loss_nba = int(record_nba_aba[0].split(' & ')[0].split()[0].split('-')[1])
record_win_aba = int(record_nba_aba[0].split(' & ')[1].split()[0].split('-')[0])
record_loss_aba = int(record_nba_aba[0].split(' & ')[1].split()[0].split('-')[1])
info['Win Total'] = record_win_total
info['Loss Total'] = record_loss_total
info['Total Win Loss Percentage'] = record_win_loss_percentage
info['Win Total NBA'] = record_win_nba
info['Loss Total NBA'] = record_loss_nba
info['NBA Win Loss Percentage'] = round(record_win_nba/(record_win_nba+record_loss_nba),3)
info['Win Total ABA'] = record_win_aba
info['Loss Total ABA'] = record_loss_aba
info['ABA Win Loss Percentage'] = round(record_win_aba/(record_win_aba+record_loss_aba),3)
else:
record_win_loss_percentage = float('0' + row[1].split(',')[1].split()[0])
info['Win Total'] = record_win_total
info['Loss Total'] = record_loss_total
info['Total Win Loss Percentage'] = record_win_loss_percentage
info['Win Total NBA'] = record_win_total
info['Loss Total NBA'] = record_loss_total
info['NBA Win Loss Percentage'] = record_win_loss_percentage
info['Win Total ABA'] = np.nan
info['Loss Total ABA'] = np.nan
info['ABA Win Loss Percentage'] = np.nan
df_basic_info = pd.DataFrame(info, index=[0])
# print(df_basic_info)
return None
teams_basic_information()
| true |
3e310a7a31f6959e3ecc47f1a8f9cd9fd7971747 | Python | milu234/Python | /house.py | UTF-8 | 974 | 3.109375 | 3 | [] | no_license | from tkinter import *
root=Tk()
#Window Appearancw
root.title("House")
c=Canvas(root,bg='white',height=700,width=1500)
#----------------------------------House Front------------------------------------------------
c.create_polygon(600,250,700,150,800,250,800,400,600,400,width=2,fill="yellow",outline='black')
c.create_rectangle(650,275,750,390,fill="pink")#------------------House door--------------------------
c.create_polygon(800,250,900,150,1000,250,1000,400,800,400,width=2,fill="blue",outline='black')#-------------------house side------------------------------------
c.create_rectangle(850,275,900,327,fill="grey")#----------------------------Window-------------------------------------
c.create_polygon(700,150,800,250,1000,250,900,150,width=2,fill="brown",outline='black')
c.create_oval(680,180,725,250, width=0.5, fill='red')#--------------------------circlr above the door------------------------------------------------------------
c.pack()
root.mainloop()
| true |
b18882dc45dc6c8c558fc7804db5c83f14a49dc8 | Python | Do-code-ing/ChanSuShin_Algorithm | /알고리즘/01_재귀_Recursion.py | UTF-8 | 1,661 | 4.34375 | 4 | [] | no_license | """
재귀 (Recursion)
재귀 함수 = 함수 내부에서 한 번 이상 자신의 함수를 호출
예1: 1 + 2 + ... + n
sum(n) = 1 + 2 + ... + (n-1) + n
= sum(n-1) + n
def sum(n):
if n == 1:
return 1
return sum(n-1) + n
수행시간:
T(n) = T(n-1) + c = O(n)
1. n == 1 테스트: 바닥조건이므로 T(1) = 1 or c
2. 재귀 호출: T(n) = 점화식
예2: sum(a, b) = a + (a+1) + ... + (b-1) + b (가정: a <= b)
sum(3, 8) = 3 + 4 + 5 + 6 + 7 + 8
= sum(3, 7) + 8
= sum(3, 5) + sum(6, 8)
def sum(a, b):
if a == b:
return a
if a > b:
return 0
m = (a+b) // 2
return sum(a, m) + (m+1, b)
T(n) = T(n/2) + T(n/2) + c
= 2 * T(n/2) + c
an = 2 * a(n/2) + c
예3: reverse 함수: A = [1, 2, 3, 4, 5] -- reverse --> A = [5, 4, 3, 2, 1]
reverse(A) = reverse(A[1:]) + A[:1]
T(n) = T(n-1) + c = O(n)
reverse(A, start, stop) = A[start] ... x ... A[stop-1]
= A[stop-1] ... x ... A[start]
x = reverse(A[start+1] ... A[stop-2])
= reverse(A, start+1, stop-2)
T(n) = O(n)
"""
def reverse(L, a):
n = len(L)
if a < n//2:
L[a], L[n-a-1] = L[n-a-1], L[a]
reverse(L, a+1)
L = list(input()) # 문자열을 입력받아 리스트로 변환
reverse(L, 0)
print(''.join(str(x) for x in L)) | true |
da6e6eff1c297c699732be6134b2963e1fa9a6cd | Python | IrvingA5106/APCSP_Zork_Thingie | /main.py | UTF-8 | 12,489 | 3.53125 | 4 | [] | no_license | from __future__ import print_function
from player import Player
def startGame():
print('Welcome to the mysterious mansion.')
# raw_input('Press enter to start the game. ')
player = Player()
basement(player)
print('Congratulations! You escaped the house.')
def library(player):
in_library = True
print('You entered the library!')
print("Empty bookshelves line the walls. On the side of the room, there is a weathered desk with a worn leather chair and a small golden statue on it.")
print("There is a door to the west.")
player.add_room('library')
while in_library:
userAction = raw_input('What would you like to do? ')
if userAction == 'open west door':
print("The door is hard to open, but you get it eventually.")
livingRoom()
elif (userAction == 'take statue' or userAction == "pick up statue") and not player.has('statue'):
print("\nYou cautiously pick up the statue. Nothing happens. Dang, that was anticlimactic.")
print("...")
print("...")
print("Huh, what's that sound?\n")
print("\nThe ceiling of the library disappears, revealing a huge wall of water. The water crashes down, filling the room. You take a deep breath before the water goes over your head...")
player.pick_up('statue')
attic()
elif userAction == 'sit at desk':
print('You sit at the desk. Nothing happens.')
elif userAction in ['quit', 'q']:
print('you have left the game')
exitRoom = True
elif userAction == "scream":
print("Aaaaaahhhhhh")
else:
print("I don't know how to do that. Try again!")
def foyer(player):
in_foyer = True
dresser_items = ['key_foyer', 'flashlight']
player.add_room('foyer')
print('You have entered the foyer')
print('There are two doors in this room. One to the left and one to the right.')
print('There is also a dresser with one drawer in the room.')
while in_foyer == True:
userAction = raw_input('What would you like to do? ')
if userAction == 'open left door' and player.has('key_foyer'):
print('The door slowly creaks open.')
in_foyer = False
bedroom(player)
elif userAction == 'open right door' and player.has('flashlight'):
print('You open the door and can now see inside with the flashlight.')
in_foyer = False
living_room(player)
elif userAction == 'open dresser':
print('You picked up {}'.format(dresser_items))
player.pick_up(dresser_items)
dresser_items = []
elif userAction == 'open left door' and not player.has('key_foyer'):
print('The door will not open.')
elif userAction == "scream":
print("Aaaaaahhhhhh")
elif userAction == 'open right door' and not player.has('flashlight'):
print('You open the door, but it is so dark inside that you cannot see. You do not enter and you close the door.')
else:
print ("I don't understand '{}'".format(userAction))
def attic(player):
wardrobe_open = False
attic_items = ['knife', 'skull']
in_attic = True
if 'attic' in player.visited_rooms:
print("This room looks familiar.")
else:
# Good idea, Idk how to work something like this into player.add_room
print("You open your eyes slowly. What happened?")
player.visited_rooms.append('attic')
print("You are in a dusty attic. The walls and ceiling are covered in cobwebs. A soaked wardrobe is on the side of the wall.")
print("There is a flight of stairs leading down to a doorway.")
while in_attic:
userAction = raw_input("What do you want to do? ")
if userAction == 'open door':
print('You walk down the stairs and open the door.')
in_attic = False
kitchen(player)
elif userAction in ['quit', 'q']:
print('you have left the game')
elif userAction == 'open wardrobe':
print('The wardrobe is filled with waterlogged coats. All of them look ruined. At the bottom of the wardrobe is a box carved out of stone.')
wardrobe_open = True
elif userAction == 'open box' and wardrobe_open == True:
print("You open the box. Inside, there is a silver knife and a dusty skull. You take both.")
player.pick_up(attic_items)
elif userAction == 'scream':
print("Aaaaaaahhh")
else:
print("I can't do that! Try again!")
def bedroom(player):
in_bedroom = True
player.add_room('bedroom')
print("You have entered the bedroom. There is a comfy looking bed in the center of the room, a chest at the foot of the bed, the door you just entered through, and large curtains covering a window on the wall.")
while in_bedroom:
userAction = raw_input('What would you like to do? ')
if userAction == 'open chest' and player.has('chest_key'):
print("You opened up the chest. Inside, there is a book, some matches, a red pocketknife, and a old jacket.")
chest_items = ['book', 'matches', 'jacket', 'pocketknife']
player.pick_up(chest_items)
elif userAction in ['quit', 'q']:
print('you have left the game')
exitRoom = True
elif userAction == 'open chest' and not player.has('chest_key'):
print("The chest is locked.")
elif userAction == 'read book' and player.has('book'):
print("The continent of Codalia, located on the continent of Normal West, is ruled by the gracious, intelligent and beautiful Queen Schermann. Its subjects are mostly teenage students, and occasionally other nobles, like Duke Scornovacco the Wise and Duke Beaty the Bearded")
print("You get bored and put the book down.")
elif userAction == 'sleep on bed' or userAction == 'sit on bed':
print("You lay down on the bed and close your eyes. When you open them again, the chair has moved to the other side of the room. Who was here?")
elif userAction == 'wear jacket':
print("You poke your arms through the sleeves of the jacket. It is musty, but surprisingly comfortable. You find a golden coin in the pocket.")
player.pick_up('coin')
elif userAction == 'open door 3':
print("You open the door and move on.")
living_room()
else:
print("I can't do that! Try again.")
def basement(player):
print ("You're in a cold, pitch black room.")
in_basement = True
while in_basement:
userAction = raw_input("What would you like to do? ")
if userAction == "move forward" or userAction == "walk forward":
if player.direction.direction == 180:
print ("You trip over a box and fall to the floor.")
else:
print ("You walk forward until you run into a damp, slimy wall.")
elif userAction == "turn left":
print ("Turned left.")
player.direction.turn_left()
elif userAction == "turn right":
print ("Turned right.")
player.direction.turn_right()
elif userAction == "turn around":
player.direction.turn_right()
player.direction.turn_right()
print("Turned around")
elif userAction == "open box":
print ("You found a flashlight in the box!")
print ("+1 flashlight")
player.pick_up("flashlight")
elif userAction == "look around":
if player.has("flashlight"):
print ("The room is small and damp with no windows or doors. There is a trapdoor in the ceiling.")
else:
print ("I can't see anything!")
elif userAction in ["open trapdoor", "enter trapdoor"]:
if not player.has("flashlight"):
print ("I don't understand '{}'".format(userAction))
else:
print ("Exiting trapdoor")
in_basement = False
elif userAction in ['quit', 'q']:
print('you have left the game')
in_basement = False
elif userAction == "scream":
print("Aaaaaahhhhhh")
else:
print ("I don't understand '{}'".format(userAction))
living_room(player)
def living_room(player):
dresser_items = ['key2', 'key3','machete']
exitRoom = False
rug_up = False
trapdoor_shut = True
print('You have entered the Living Room')
print('There is a door to the north.')
print('There is a dresser with a drawer partly open against the wall.')
print('There is a rug in the center of the room.')
player.add_room('living_room')
while exitRoom == False:
userAction = raw_input('What would you like to do? ')
if userAction == 'open north door' and not player.has('key3'):
print('This door is locked. Is there a key that you can use to open the door?')
elif userAction == 'open north door' and player.has('key3'):
print('you have opened the north door and entered the foyer')
exitRoom = True
foyer(player)
elif userAction == 'look around':
print('You are in the Living Room')
print('There is a door to the north.')
print('There is a dresser with a drawer partly open against the wall.')
print('There is a rug in the center of the room.')
elif userAction in ['move the rug', 'roll up the rug', 'move rug']:
print('you have moved the rug')
print('There is a trapdoor here that was covered by the rug')
rug_up = True
elif userAction in ['open dresser', 'open dresser drawer', 'pull the dresser drawer open', 'pull open drawer', 'pull open dresser drawer'] :
print('You have opened the dresser drawer.')
print('there are two keys and a machete in the drawer.')
elif userAction in ['take dresser items', 'grab items', 'take items', 'grab dresser items']:
print('You have grabbed the keys and the Machete.')
player.pick_up(dresser_items)
elif userAction in ['open trapdoor', ' enter trapdoor'] and (rug_up and trapdoor_shut):
print('The trapdoor is tied closed by a thick string.')
elif userAction in ['cut the string' ' cut string with the machete'] and player.has('machete'):
print('You have cut the string and opened the trapdor.')
trapdoor_shut = False
elif userAction in ['go into the trapdoor', ' enter trapdoor', 'exit trapdoor'] and (rug_up and not trapdoor_shut):
print('You have entered the west end of the basement')
exitRoom = True
basement(player)
elif userAction == 'scream':
print("Aaaaaahhhhh")
elif userAction in ['quit', 'q']:
print('you have left the game')
exitRoom = True
else:
print("I don't know what " + userAction + " means.")
def kitchen(player):
exitRoom = False
table_items = ["candle", "key_kitchen", "rope", "chest_key"]
print("you have entered the Kitchen.")
print("There is a table with some items lying there.")
print("there is a door to the south and a door to the east.")
player.add_room('kitchen')
while exitRoom == False:
userAction = raw_input('What would you like to do? ')
if userAction == 'open east door' and not player.has('key_kitchen'):
print("The door is locked. Do you have a key that you could use?")
elif userAction == 'open east door' and player.has('key_kitchen'):
exitRoom = True
foyer(player)
elif userAction == 'open south door':
print("You have gone to the backyard.")
exitRoom = True
elif userAction == 'pick up items':
print('you took', table_items)
player.pick_up(table_items)
elif userAction == "scream":
print("Aaaaaahhhhhh")
else:
print("I don't know how to do that!")
if __name__ == "__main__":
startGame()
| true |
b6e5ddb8fee11f43cc3dd85d10d159d0bfaa4ab2 | Python | AndreasKralj/SECMizzouCyberChallenge | /logger.py | UTF-8 | 5,322 | 3.40625 | 3 | [] | no_license | def log_operation(user_id,operation,auth,success ):
#The user ID is an interger determined by looking up the auth token in the token database and
#returning the associated user ID. The ID is passed to the logging function as an interger. The
#operation is a character value, defined by its corresponding CRUD value. For example, you would
#pass a value of 'c' for a create operation or a value of 'u' for an update operation. The auth
#parameter specifies whether the attemped action was allowed or not. If a user attempted to create
#a table entry but did not have proper authority, auth would be FALSE. If a user attempted to
#read a table entry and was permitted to do so, auth would be TRUE. Lastly, success is for error
#logging purposes only. If a user attemped to add a table entry and is authorized to do so but
#there is a database error, a value of FALSE would be passed for success. If the operation is
#successful, TRUE is passed.
import logging
#convert operation character to lower
operation = operation.lower()
#template for log messages
#change log file name for appropriate application
#log file is pwd only, symlink to log dir is recommended
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S', filename='access.log', level=logging.DEBUG)
#perform standard logging operations if requested operation was successful
if success == True:
#attempted CREATE operation
if operation == 'c':
if auth:
#CREATE, authorized, no error
logging.info('user=%d successfuly created an entry in the table', user_id)
else:
#CREATE, unauthorized, no error
logging.warning('user=%d attempted to perform an unauthorized creation operation', user_id)
#attempted READ operation
elif operation == 'r':
if auth:
#READ, authorized, no error
logging.info('user=%d successfuly read an entry in the table', user_id)
else:
#READ, unauthorized, no error
logging.warning('user=%d attempted to perform an unauthorized read operation', user_id)
#attempted UPDATE operation
elif operation == 'u':
if auth:
#UPDATE, authorized, no error
logging.info('user=%d successfuly updated an entry in the table', user_id)
else:
#UPDATE, unauthorized, no error
logging.warning('user=%d attempted to perform an unauthorized update operation', user_id)
#attempted DELETE operation
elif operation == 'd':
if auth:
#DELETE, authorized, no error
logging.info('user=%d successfuly deleted an entry in the table', user_id)
else:
#DELETE, unauthorized, no error
logging.warning('user=%d attempted to perform an unauthorized deletion operation', user_id)
#improper argument error checking
else:
logging.debug('IMPROPER OPERATION VARIABLE PASSED TO FUNCTION')
#log error message if requested operation was not successful
else:
#attempted CREATE operation failed
if operation == 'c':
if auth:
#CREATE, authorized, error
logging.error('user=%d attmpted to perform an authorized creation operation, but encountered an error', user_id)
else:
#CREATE, unauthorized, error
logging.error('user=%d attmpted to perform an unauthorized creation operation, but encountered an error', user_id)
#attempted READ operation failed
elif operation == 'r':
if auth:
#READ, authorized, error
logging.error('user=%d attmpted to perform an authorized read operation, but encountered an error', user_id)
else:
#READ, unauthorized, error
logging.error('user=%d attmpted to perform an unauthorized read operation, but encountered an error', user_id)
#attempted UPDATE operation failed
elif operation == 'u':
if auth:
#UPDATE, authorized, error
logging.error('user=%d attmpted to perform an authorized update operation, but encountered an error', user_id)
else:
#UPDATE, unauthorized, error
logging.error('user=%d attmpted to perform an unauthorized update operation, but encountered an error', user_id)
#attempted DELETE operation failed
elif operation == 'd':
if auth:
#DELETE, authorized, error
logging.error('user=%d attmpted to perform an authorized delete operation, but encountered an error', user_id)
else:
#DELETE, unauthorized, error
logging.error('user=%d attmpted to perform an unauthorized delete operation, but encountered an error', user_id)
#improper argument error checking
else:
logging.debug('IMPROPER OPERATION VARIABLE PASSED TO FUNCTION')
return;
#test function calls
#authorized, no error
log_operation(1234,'C',True,True)
log_operation(1234,'r',True,True)
log_operation(1234,'u',True,True)
log_operation(1234,'d',True,True)
log_operation(1234,'z',True,True)
#unauthorized, no error
log_operation(1234,'c',False,True)
log_operation(1234,'r',False,True)
log_operation(1234,'u',False,True)
log_operation(1234,'d',False,True)
log_operation(1234,'z',False,True)
#authorized, with error
log_operation(1234,'c',True,False)
log_operation(1234,'r',True,False)
log_operation(1234,'u',True,False)
log_operation(1234,'d',True,False)
log_operation(1234,'z',True,False)
#unauthorized, with error
log_operation(1234,'c',False,False)
log_operation(1234,'r',False,False)
log_operation(1234,'u',False,False)
log_operation(1234,'d',False,False)
log_operation(1234,'z',False,False) | true |
cb0348fa410526a5f93b823b712577eefed28657 | Python | dwikinuridhuha/shutit-percobaan | /pause.py | UTF-8 | 162 | 2.515625 | 3 | [] | no_license | import shutit
session = shutit.create_session('bash')
session.pause_point('Have a look around!')
session.send('echo "Did you enjoy your pause point?"', echo=True) | true |
db21db67b6689e909deaec37d8689e5b4b5ba1b4 | Python | quyam2/th6 | /bước 6 hoàn thành.py | UTF-8 | 3,715 | 3.046875 | 3 | [] | no_license | from tkinter import *
from PIL import ImageTk, Image
from time import sleep
img=[0,0,0,0,0]
game = Tk()
game.title("Game bóng")
# tạo tên cho game``
canvas = Canvas(master=game, width=600 , height=450, background="Light blue")
canvas.pack()
# tạo khung cho game
img[0]=ImageTk.PhotoImage(Image.open("bong.png"))
img[1]=ImageTk.PhotoImage(Image.open("un.png"))
img[2]=ImageTk.PhotoImage(Image.open("chim.jpg"))
img[3]=ImageTk.PhotoImage(Image.open("so.jpg"))
img[4]=ImageTk.PhotoImage(Image.open("x2.jpg"))
# đưa file vào game , tất cả file đều do nhóm tìm kiếm
bong=canvas.create_image(10 ,420,anchor=NW,image=img[0])
tree=canvas.create_image(550,390,anchor=NW,image=img[1])
cloud=canvas.create_image(550,140,anchor=NW,image=img[2])
so=canvas.create_image(450,185,anchor=NW,image=img[3])
xx=canvas.create_image(0,-80,anchor=NW,image=img[4])
a=canvas.create_line(0,449,600,449,fill="blue")
# tọa độ và thông số cái file đã đưa vào
canvas.update()
def moveXX():
global xx
canvas.move(xx,-5,0)
if canvas.coords(xx)[0]<-450:
canvas.delete(xx)
xx = canvas.create_image(0,-80, anchor=NW, image=img[4])
canvas.update()
# hàm để hinh nền di chuyển
def moveCloud():
global cloud
canvas.move(cloud,-5,0)
if canvas.coords(cloud)[0]<-20:
canvas.delete(cloud)
cloud = canvas.create_image(550, 220, anchor=NW, image=img[2])
canvas.update()
# hàm để chim di chuyển
def moveSo():
global so
canvas.move(so,-5,0)
if canvas.coords(so)[0]<-20:
canvas.delete(so)
so = canvas.create_image(450, 185, anchor=NW, image=img[3])
canvas.update()
# hàm để may bay di chuyển
score = 0
text_score = canvas.create_text(540, 280, text="Điểm:" + str(score), fill="blue", font=("Times", 13))
def moveTree():
global tree,score,text_score
canvas.move(tree,-5,0)
if canvas.coords(tree)[0]<-20:
score=score+1
canvas.itemconfig(text_score,text="Điểm:" + str(score))
canvas.delete(tree)
tree = canvas.create_image(550, 390, anchor=NW, image=img[1])
canvas.update()
# hàm để cái tường di chuyển
check_jump=False
def jump():
global check_jump
if check_jump==False:
check_jump=True
for i in range(0, 30):
canvas.move(bong,0,-5)
moveCloud()
moveTree()
moveSo()
moveXX()
canvas.update()
sleep(0.01)
for i in range(0, 30):
canvas.move(bong, 0, 5)
moveCloud()
moveTree()
moveSo()
moveXX()
canvas.update()
sleep(0.01)
check_jump=False
# hàm để quả bóng di chuyển lên xuống cùng với các nhân vật
def KeyPress(event):
if event.keysym=="space":
jump()
canvas.bind_all("<KeyPress>",KeyPress)
gameOver=False
# hàm điều khiển và tương tác vs bàn phím để quả bóng di chuyển
def check_gameOver():
global gameOver
coords_tree=canvas.coords(tree)
coords_bong=canvas.coords(bong)
if coords_bong[1]>370 and coords_tree[0]<50:
gameOver=True
game.after(100,check_gameOver)
if coords_bong[1]>370 and coords_tree[0]<50:
canvas.create_text(300, 110, text="Game Over", fill="red", font=('Times', 40))
check_gameOver()
#hàm dùng để kết thúc trờ chơi
while not gameOver:
moveCloud()
moveTree()
moveSo()
moveXX()
sleep(0.01)
#tránh bị khựng khi quá bóng đang di chuyển
game.mainloop() | true |
e8b17ee2610c55dc2996c5df8b85d896f4535f97 | Python | emag-notes/automatestuff-ja | /ch03/validateNumber.py | UTF-8 | 203 | 3.71875 | 4 | [] | no_license | print('整数を入力してください:')
try:
input_num = int(input())
print('入力値: ' + str(input()))
except ValueError:
print('入力された値は整数ではありません。')
| true |
ac66668c91333cca75f5558bf1b4b19a46c56fa0 | Python | 70ucanbin/IMS | /ims/common/ExcelLogicUtil.py | UTF-8 | 6,327 | 2.640625 | 3 | [
"MIT"
] | permissive | import openpyxl as px
import os, shutil, traceback
from calendar import monthrange
from flask import abort
from flask_login import current_user
from ims.service.comServ import getComUser
class __ExcelUtil(object):
"""Excelの共通処理
各出力機能の共通部分を定義します。
1.一時ファイルの作成処理
2.Excel処理中のException処理
3.一時ファイルを閉じて削除する処理
:param template_path: 出力対象フォーマットの格納パス
:param tmp_path: 一時ファイルの格納パス
"""
def __init__(self, template_path, tmp_path):
"""一時ファイルの作成処理
リクエスト別で重複しない一時パスをパラメータで取得します。
テンプレートをそこにコピーし、ロードします。
"""
self.template_path = template_path
self.tmp_path = tmp_path
try:
os.makedirs(tmp_path)
self.tmp_file = shutil.copy(template_path, tmp_path+'\\tmp.xlsx')
self.book = px.load_workbook(self.tmp_file)
except:
#ファイルを読み込み時のエラー処理を記述
if os.path.exists(tmp_path):
shutil.rmtree(self.tmp_path)
abort(500)
def edit_file(self):
"""業務別の帳票への書き込み処理を定義します。
各業務でこれをoverwriteして使用してください。
"""
pass
def close_file(self):
"""一時ファイルを閉じて削除する処理
"""
try:
self.book.close()
shutil.rmtree(self.tmp_path)
except:
#ファイルを閉じる時のエラー処理を記述
traceback.print_exc()
abort(500)
class travelExpenses_excel(__ExcelUtil):
"""旅費精算の帳票出力処理
:param template_path: 出力対象フォーマットの格納パス
:param tmp_path: 一時ファイルの格納パス
"""
def edit_file(self, userId, models):
"""帳票書き込み処理
:param userId: 出力対象ユーザID
:param models: 出力詳細データ格納model
"""
try:
if models:
dto = getComUser(userId)
sheet = self.book.active
# 氏名
sheet.cell(6, 9).value = dto.user_name
# 期間及び提出日
__, lastDay = monthrange(models[0].entry_year, models[0].entry_month)
sheet.cell(8, 2).value = str(models[0].entry_year) + '年' + str(models[0].entry_month) + '月' + '1日'
sheet.cell(8, 5).value = str(models[0].entry_year) + '年' + str(models[0].entry_month) + '月' + str(lastDay) + '日'
sheet.cell(8, 9).value = str(models[0].entry_year) + '年' + str(models[0].entry_month) + '月' + str(lastDay) + '日'
row = 12
column = 1
for model in models:
sheet.cell(row, column).value = model.expense_date
sheet.cell(row, column+1).value = model.expense_item
sheet.cell(row, column+2).value = model.route
sheet.cell(row, column+4).value = model.transit
sheet.cell(row, column+5).value = model.payment
sheet.cell(row, column+6).value = ''
sheet.cell(row, column+7).value = model.file_name
sheet.cell(row, column+8).value = model.note
row += 1
self.book.save(self.tmp_file)
result_file = open(self.tmp_file, "rb").read()
else:
result_file = None
except TypeError:
# 変なデータが登録されない限り、TypeErrorは起こらないが、念のため
traceback.print_exc()
super().close_file()
return result_file
class monthly_report_excel(__ExcelUtil):
"""月報の帳票出力処理
:param template_path: 出力対象フォーマットの格納パス
:param tmp_path: 一時ファイルの格納パス
"""
def edit_file(self, userId, data):
"""帳票書き込み処理
:param userId: 出力対象ユーザID
:param models: 出力詳細データ格納model
"""
try:
if data['models']:
dto = getComUser(userId)
sheet = self.book.active
# ヘッダ項目:年・月・作業者名
sheet.cell(1, 1).value = data['year'] + '年'
sheet.cell(1, 3).value = data['month'] + '月分 作業報告書'
sheet.cell(1, 11).value = dto.user_name
# フッター項目:出勤日数
# 詳細データ
row = 9
column = 1
for model in data['models']:
if model.rest_flg == 1:
sheet.cell(row, column).value = str(model.work_year)+'/'+str(model.work_month)+'/'+str(model.work_day)
sheet.cell(row, column + 2).value = '休み'
row += 1
else:
sheet.cell(row, column).value = str(model.work_year)+'/'+str(model.work_month)+'/'+str(model.work_day)
sheet.cell(row, column + 2).value = model.work_details
sheet.cell(row, column + 5).value = model.start_work_time
sheet.cell(row, column + 6).value = model.end_work_time
sheet.cell(row, column + 7).value = model.normal_working_hours
sheet.cell(row, column + 8).value = model.overtime_hours
sheet.cell(row, column + 9).value = model.holiday_work_hours
row += 1
self.book.save(self.tmp_file)
result_file = open(self.tmp_file, "rb").read()
else:
result_file = None
except TypeError:
# 変なデータが登録されない限り、TypeErrorは起こらないが、念のため
traceback.print_exc()
super().close_file()
return result_file
| true |
3f2910f2e2da27ef07bc2ef5f2f2d039b245a570 | Python | RedRAINXXXX/info2 | /main.py | UTF-8 | 17,984 | 2.53125 | 3 | [] | no_license | import re
import pandas as pd
import os
import glob
import natsort
from tqdm import tqdm
import sys
import os.path
from win32com.client import Dispatch
#initialization
app = Dispatch('Word.Application')
excel = Dispatch('Excel.Application')
data_list = []
label_list = []
color_dict = {'橙色':49407,'蓝色':15773696,'绿色':5287936,'浅绿':5296274}
try:
if os.path.isfile('conf.xlsx'):
conf_path = "conf.xlsx"
else:
conf_path = input("默认配置文件不存在,请输入配置文件路径:")
conf = pd.read_excel(conf_path, header=0, index_col=0)
doc1 = app.Documents.Open(conf.loc['doc_source'][0])
doc1.ActiveWindow.View.ShowHiddenText = False
doc1.Activate()
xbook = excel.Workbooks.Open(conf.loc['data_excel'][0])
app.visible = True if conf.loc['word_visible'][0] == 1 else False
excel.visible = True if conf.loc['excel_visible'][0] == 1 else False
loc_num = conf.loc['loc_num'][0]
for i in range(loc_num):
data_row = conf.loc['data_loc_{}'.format(i + 1)]
data_list.append((data_row[0], (int(data_row[1]), int(data_row[2])), (int(data_row[3]), int(data_row[4]))))
label_row = conf.loc['label_loc_{}'.format(i + 1)]
label_list.append((label_row[0], (int(label_row[1]), int(label_row[2])), (int(label_row[3]), int(label_row[4]))))
except Exception as errmsg:
print(errmsg)
#工作表名称 (起始行,起始列) (结尾行,结尾列)
# data_list = [('替换要素',(2,3),(179,3))]
# label_list = [('替换要素',(2,1),(179,1))]
def fiFindByWildcard(wildcard):
return natsort.natsorted(glob.glob(wildcard, recursive=True))
def replace_all(oldstr, newstr, regrex = False):
app.Selection.Find.Execute(
oldstr, False, False, regrex, False, False, True, 1, False, newstr, 2)
# app.Selection.Find.Execute('\{\$(*)\}', False, False, True, False, False, True, 1, False, '\\1', 2)
#Replace
#1 Remove Color
def remove_color(mode='conf'):
"""
删除指定的颜色
:param mode: input: input conf: conf file
:return:
"""
colorname = None
if mode == 'input':
colorname = input("请输入要删除的颜色,(支持颜色:橙色、蓝色、绿色、浅绿):")
elif mode == 'conf':
colorname = conf.loc['1_colorname'][0]
app.Selection.Find.Font.Color = color_dict[colorname]
app.Selection.Find.Execute(FindText='', MatchCase=False, MatchWholeWord=False, MatchWildcards = False,
MatchSoundsLike = False, MatchAllWordForms = False, Forward = True,
Wrap = 1, Format = True, ReplaceWith='', Replace=2)
print("Func 1 Done!")
def set_find(ClearFormatting=True, Text="", ReplacementText="",Forward=True,
Wrap = 1,Format = False,MatchCase = False,MatchWholeWord = False,
MatchByte = True,MatchAllWordForms = False,MatchSoundsLike = False,MatchWildcards = True):
if ClearFormatting:
app.Selection.Find.ClearFormatting()
app.Selection.Find.Text = Text
app.Selection.Find.Replacement.Text = ReplacementText
app.Selection.Find.Forward = Forward
app.Selection.Find.Wrap = Wrap
app.Selection.Find.Format = Format
app.Selection.Find.MatchCase = MatchCase
app.Selection.Find.MatchWholeWord = MatchWholeWord
app.Selection.Find.MatchByte = MatchByte
app.Selection.Find.MatchAllWordForms = MatchAllWordForms
app.Selection.Find.MatchSoundsLike = MatchSoundsLike
app.Selection.Find.MatchWildcards = MatchWildcards
def hide_change(hidden = False,name = None):
set_find(Text="\{T%s_*_T%s\}" % (name, name))
app.Selection.WholeStory()
while app.Selection.Find.Execute():
app.Selection.Font.Hidden = hidden
def all_com(now,rest):
if rest != '':
all_com(now, rest[1:])
all_com(now+rest[0], rest[1:])
else:
if len(now) != 0:
hide_change(hidden =True, name = ';'.join(now))
#2 Hide Template
def hide_all_T(mode='conf'):
"""
隐藏所有的数字模板
:param mode: input: input conf: conf file
:return:
"""
t_num = None
if mode == 'input':
t_num = int(input("请输入模板总类数:"))
elif mode == 'conf':
t_num = int(conf.loc['t_num'][0])
doc1.ActiveWindow.View.ShowHiddenText = True
tl = [str(i) for i in range(1,t_num + 1)]
all_com(now='',rest=''.join(tl))
doc1.ActiveWindow.View.ShowHiddenText = False
print("Func 2 Done!")
def chosen_copy(now,rest,chosen):
if rest != '':
chosen_copy(now, rest[1:], chosen)
chosen_copy(now+rest[0], rest[1:], chosen)
else:
if len(now) != 0 and chosen in now:
name = ';'.join(now)
replace_all("\{T%s_(*)_T%s\}" % (name, name),"{P_\\1_P}{T%s_\\1_T%s}" % (name, name),regrex=True)
# replace_all("^p^p", "^p")
#3 Copy Chosen Template
def copy_chosen_T(mode='conf'):
"""
将选择的模板复制一份P标记副本
:param mode: input: input conf: conf file
:return:
"""
t_num = None
chosen = None
if mode == 'input':
t_num = int(input("请输入模板总类数:"))
chosen = int(input("请输入要复制的模板:"))
elif mode == 'conf':
t_num = int(conf.loc['t_num'][0])
chosen = int(conf.loc['3_chosen_t'][0])
tl = [str(i) for i in range(1,t_num + 1)]
chosen_copy(now='', rest=''.join(tl), chosen=str(chosen))
print("Func 3 Done!")
#4 Restore from P mode
def restore(mode):
"""
删除所有的P标记模板
:return:
"""
doc1.ActiveWindow.View.ShowHiddenText = True
app.Selection.WholeStory()
replace_all('\{P_(*)_P\}', '', regrex=True)
app.Selection.Font.Hidden = False
doc1.ActiveWindow.View.ShowHiddenText = False
print("Func 4 Done!")
#5 Replace Single File
def replace_doc1(mode):
"""
从data_list,label_list中读取数据,替换doc_source
:return:
"""
replace_elements(doc1.Name)
print("Func 5 Done!")
def replace_elements(filename):
for i,l in zip(data_list,label_list):
row_num = i[2][0]-i[1][0]+1
col_num = i[2][1]-i[1][1]+1
with tqdm(total=row_num*col_num) as pbar:
pbar.set_description(filename+'_'+i[0])
for row in range(row_num):
for col in range(col_num):
data = xbook.sheets[i[0]].Cells(i[1][0]+row,i[1][1]+col).text.strip()
label = xbook.sheets[l[0]].Cells(l[1][0]+row,l[1][1]+col).text.strip()
if data!='' and data!='#DIV/0!' and data!='-':
replace_all(label,data)
pbar.update(1)
#6 Remove Label
def remove_mark(mode='conf'):
"""
去除文件的所有指定标记,并保留一份备份文件
:param mode: input: input conf: conf file
:return:
"""
labels = None
if mode == 'input':
labels = input("请输入要去除的标记(例:P或P;C;D):")
elif mode == 'conf':
labels = conf.loc['6_labels'][0]
doc1.Save()
doc1.SaveAs(os.path.dirname(os.path.abspath(__file__)) + '/{}_remove.docx'.format(doc1.Name.split('.')[0]))
if re.match('^([PCD];)+[PCD]$', labels):
for label in labels.split(";"):
replace_all('\{%s_(*)_%s\}' % (label, label), '\\1', regrex=True)
elif re.match("^[PCD]$", labels):
replace_all('\{%s_(*)_%s\}' % (labels, labels), '\\1', regrex=True)
print("Func 6 Done!")
#7 Remove Specific Row of certain tables
def remove_condition_row(mode='conf'):
"""
去除特定标记范围内的“空”行
:param mode: input: input conf: conf file
enum: '':去除C标记范围内所有表格的全为空的行 '-':去除D标记范围内所有表格的从第二列全为'-'的行
:return:
"""
# doc1.ActiveWindow.View.ShowHiddenText = True
# default enum ''
enum = None
if mode == 'input':
enum = input("请输入要去除的行类型(例:'空'或'-'):")
elif mode == 'conf':
enum = conf.loc['7_enum'][0]
if enum == '空':
enum = ''
col_begin = 1
set_find(Text="\{C_(*)_C\}")
elif enum == '-':
col_begin = 2
set_find(Text="\{D_(*)_D\}")
else:
return
app.Selection.WholeStory()
while app.Selection.Find.Execute():
for table in app.Selection.Range.tables:
if table.Cell(1,1).range.font.hidden == -1:
continue
row_index = 1
for i in range(1, table.rows.count + 1):
flag = True
for j in range(col_begin, table.columns.count + 1):
try:
cell_str = table.Cell(row_index,j).range.text.split('\r')[0]
if cell_str != enum:
flag = False
break
except BaseException:
flag = False
break
if flag:
doc1.Range(table.Cell(row_index,1).range.start,table.Cell(row_index,table.columns.count).range.end).cells.Delete(2)
row_index -= 1
row_index += 1
print("Func 7 Done!")
# doc1.ActiveWindow.View.ShowHiddenText = False
#8 Remove paragraphs with specific trigger
def delete_trigger_para(mode='conf'):
"""
去除带有特定触发字符串的段落
:param mode: input: input conf: conf file
trigger_text: 触发器文字
:return:
"""
trigger_text = None
if mode == 'input':
trigger_text = input("请输入触发器字符串:")
elif mode == 'conf':
trigger_text = conf.loc['8_trigger_text'][0]
set_find(Text=trigger_text, MatchWildcards=False)
app.Selection.WholeStory()
while app.Selection.Find.Execute():
app.selection.paragraphs[0].Range.Delete()
print("Func 8 Done!")
def level_1_condition():
set_find(Text="\{E(*)_")
app.Selection.WholeStory()
while app.Selection.Find.Execute():
label_text = app.Selection.text[2:-1]
#CONDITION JUDGE
try:
cond = 1 if conf.loc[label_text][0] == 1 else 0
except Exception:
cond = 0
#NEED
if cond == 1:
oldStr = "\{E%s_(*)_E%s\}" % (label_text, label_text)
newStr = "{P_\\1_P}{E%s_\\1_E%s}" % (label_text, label_text)
app.Selection.Find.Execute(oldStr, False, False, True, False, False, True, 1, False, newStr, 1)
#HIDE T
start = app.Selection.range.start
end = app.Selection.range.end
content_length = (end - start - 12 - 2*len(label_text))//2
Tstart = content_length + 2 * len(label_text) + 6
doc1.Range(end-Tstart,end).Font.Hidden = True
#DONT NEED
elif cond == 0:
app.Selection.Find.Text = "\{E%s_(*)_E%s\}" % (label_text, label_text)
app.Selection.End = app.Selection.Start
app.Selection.Find.Execute()
app.selection.Font.Hidden = True
app.Selection.Start = app.Selection.End
app.Selection.Find.Wrap = 0
app.Selection.Find.Text = "\{E(*)_"
def sub_condition():
set_find(Text="\{E(*)_")
app.Selection.WholeStory()
while app.Selection.Find.Execute():
label_text = app.Selection.text[2:-1]
#CONDITION JUDGE
try:
cond = 1 if conf.loc[label_text][0] == 1 else 0
except Exception:
cond = 0
#NEED
if cond == 1:
oldStr = "\{E%s_(*)_E%s\}" % (label_text, label_text)
newStr = "\\1"
app.Selection.Find.Execute(oldStr, False, False, True, False, False, True, 1, False, newStr, 1)
#DONT NEED
elif cond == 0:
app.Selection.Find.Text = "\{E%s_(*)_E%s\}" % (label_text, label_text)
app.Selection.End = app.Selection.Start
app.Selection.Find.Execute()
app.selection.Font.Hidden = True
app.Selection.Find.Text = "\{E(*)_"
# 9 Deal with conditions
def condition(mode):
"""
cond from conf
:param mode:
:return:
"""
level_1_condition()
sub_condition()
print("Func 9 Done!")
def Ftrans(path):
target_doc = app.Documents.Open(path)
doc1.Activate()
set_find(Text="\{F(*)_")
app.Selection.WholeStory()
while app.Selection.Find.Execute():
label_text = app.Selection.text[2:-1]
app.Selection.Find.Text = "\{F%s_(*)_F%s\}" % (label_text, label_text)
app.Selection.End = app.Selection.Start
app.Selection.Find.Execute()
offset = len(label_text) + 3
start = app.Selection.Start
end = app.Selection.end
doc1.Range(start+offset,end-offset).Copy()
target_doc.Activate()
app.Selection.Find.Text = "{F%s}" % label_text
app.Selection.Find.MatchWildcards = False
app.Selection.WholeStory()
while app.Selection.Find.Execute():
app.Selection.Paragraphs[0].Range.PasteAndFormat(16)
doc1.Activate()
app.Selection.Find.Text = "\{F(*)_"
app.Selection.Find.MatchWildcards = True
app.Selection.Start = app.Selection.End
app.Selection.Find.Wrap = 0
target_doc.Activate()
target_doc.Save()
target_doc.Close()
doc1.Activate()
#10 Field Trans
def Ftrans_single(mode='conf'):
"""
:param mode: input: input conf: conf file
path: target doc path
:return:
"""
path = None
if mode == 'input':
path = input("请输入目的文件绝对路径:")
elif mode == 'conf':
path = conf.loc['10_single_path'][0]
Ftrans(path)
print("Func 10 Done!")
#11 Inner Field Trans
def Finner_copy(mode):
"""
Inner Field Trans
:return:
"""
set_find(Text="\{F(*)_")
app.Selection.WholeStory()
while app.Selection.Find.Execute():
label_text = app.Selection.text[2:-1]
app.Selection.Find.Text = "\{F%s_(*)_F%s\}" % (label_text, label_text)
app.Selection.End = app.Selection.Start
app.Selection.Find.Execute()
offset = len(label_text) + 3
start = app.Selection.Start
end = app.Selection.end
doc1.Range(start+offset,end-offset).Copy()
app.Selection.Find.Text = "{F%s}" % label_text
app.Selection.Find.MatchWildcards = False
app.Selection.Start = 0
app.Selection.End = 0
while app.Selection.Find.Execute():
app.Selection.Paragraphs[0].Range.PasteAndFormat(16)
app.Selection.Find.Text = "\{F(*)_"
app.Selection.Find.MatchWildcards = True
app.Selection.Start = end
app.Selection.End = end
app.Selection.Find.Wrap = 0
print("Func 11 Done!")
#12 Batch Replace
def batch_replace(mode='conf'):
"""
Batch Replace
:param mode: input: input conf: conf file
directory: Dir containing multiple fields
:return:
"""
directory = None
if mode == 'input':
directory = input("请输入批替换的目录路径:")
elif mode == 'conf':
directory = conf.loc['12_batch_dir'][0]
docx_paths = fiFindByWildcard(os.path.join(directory, '*.docx'))
for path in docx_paths:
temp_doc = app.Documents.Open(path)
temp_doc.Activate()
replace_elements(temp_doc.Name)
temp_doc.Save()
temp_doc.Close()
doc1.Activate()
print("Func 12 Done!")
#13 Batch Trans
def batch_trans(mode = 'conf'):
"""
Batch Trans
:param mode: input: input conf: conf file
directory: Dir containing multiple fields
:return:
"""
directory = None
if mode == 'input':
directory = input("请输入批转移的目录路径:")
elif mode == 'conf':
directory = conf.loc['13_batch_dir'][0]
docx_paths = fiFindByWildcard(os.path.join(directory, '*.docx'))
for path in docx_paths:
Ftrans(path)
doc1.Activate()
print("Func 13 Done!")
#14 Change doc1:
def change_doc1(mode):
path = input("请输入doc_source绝对路径:")
global doc1
doc1.Save()
doc1.Close()
doc1 = app.Documents.Open(path)
doc1.Activate()
print("Func 14 Done!")
#----------------------------------------Testing--------------------------------------
# a = doc1.paragraphs[24].range.highlightcolorindex
# b = doc1.paragraphs[22].range.font.colorindex
#insert col
# for i in range(1, doc1.tables[0].rows.count + 1):
# doc1.tables[0].Cell(i, doc1.tables[0].columns.count).range.text = 'content_{}'.format(i)
# doc1.tables[0].Cell(1,1).range.text = '具体项目'
func_dict = {"1":remove_color,"2":hide_all_T,"3":copy_chosen_T,"4":restore,"5":replace_doc1,"6":remove_mark,
"7":remove_condition_row,"8":delete_trigger_para,"9":condition,"10":Ftrans_single,"11":Finner_copy,"12":batch_replace,
"13":batch_trans,"14":change_doc1}
while True:
cmd = input("请输入模式和命令(或组合):")
if cmd == 'quit':
sys.exit()
else:
Mode,cmd = cmd.split(':')[0],cmd.split(':')[1]
Mode = 'input' if Mode == 'i' else 'conf' if Mode == 'c' else 'error'
if Mode == 'error':
print('Wrong Mode!')
sys.exit()
if re.match("^\d+$", cmd):
func_dict[cmd](Mode)
elif re.match("^(\d+;)+(\d+)$", cmd):
for index in cmd.split(';'):
func_dict[index](Mode)
print('Task Done!')
# copy_chosen_T(chosen=2,t_num=4)
# hide_all_T(t_num=4)
# level_1_condition()
# sub_condition()
# replace_elements('main')
# remove_color('橙色')
# remove_condition_row(enum='-')
# remove_condition_row(enum='')
# #提交时
# remove_mark()
# #恢复模板状态
# restore()
# delete_trigger_para("{Trigger}")
# batch_replace(r'C:\Users\lihongyu\Desktop\testDir')
# Ftrans(doc2)
| true |
8f4f7a9553adaeb3811191e67cb92da2fb85604f | Python | inwidyana/thesis | /preprocessing.py | UTF-8 | 3,595 | 2.796875 | 3 | [] | no_license | #%%
import csv
import os
from shutil import copyfile
#%%
def create_file(file_name):
new_file = open(file_name, 'w+')
new_file.close()
def delete_file(file_name):
os.remove(file_name)
#%%
def get_east_java_data(source_file, dest_file):
with open(source_file) as source:
source_data = csv.reader(source, delimiter=';')
line_count = 0
with open(dest_file, mode='w') as destination:
dest_writer = csv.writer(
destination, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in source_data:
first_line = (line_count == 6)
yogya_data = (((line_count - 6) % 11) == 0)
# temp = row
if first_line or yogya_data:
dest_writer.writerow([float(row[5])])
print('.', end='')
if line_count % 10 == 0:
print('\n')
line_count += 1
print('\nTotal line created: ', (line_count / 11))
#%%
def group_into_yearly_data(source_file, dest_file):
year_data = []
with open(source_file) as csv_file:
with open(dest_file, mode='w') as destination:
dest_writer = csv.writer(
destination, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
source_data = csv.reader(csv_file, delimiter=',')
month_counter = 0
line_counter = 0
for row in source_data:
year_data.append((float(row[0])))
month_counter += 1
if month_counter == 12:
dest_writer.writerow(year_data)
year_data.clear()
month_counter = 0
line_counter += 1
print('.', end='')
if line_counter % 10 == 0:
print('\n')
print('\nTotal line created: ', (line_counter))
#%%
pre_raw_data = '/Users/indrawidyana/OneDrive - UGM 365/Thesis/Code/unprocessed data/pre_cru-ts-4.03-gridded_110.25e9.75s114.75e5.25s_19010116-20181216.csv'
tmp_raw_data = '/Users/indrawidyana/OneDrive - UGM 365/Thesis/Code/unprocessed data/tmp_cru-ts-4.03-gridded_110.25e9.75s114.75e5.25s_19010116-20181216.csv'
pre_temp_data_name = 'pre_temp_data.csv'
tmp_temp_data_name = 'tmp_temp_data.csv'
pre_data_east_java_name = '/Users/indrawidyana/OneDrive - UGM 365/Thesis/Code/processed data/pre_data.csv'
tmp_data_east_java_name = '/Users/indrawidyana/OneDrive - UGM 365/Thesis/Code/processed data/tmp_data.csv'
yield_file_name = '/Users/indrawidyana/OneDrive - UGM 365/Thesis/Code/unprocessed data/maize_yield_east_java.csv'
yield_file_dest = '/Users/indrawidyana/OneDrive - UGM 365/Thesis/Code/processed data/maize_yield_east_java.csv'
#%%
# Create temp file as a temporary storage
create_file(pre_temp_data_name)
create_file(tmp_temp_data_name)
#%%
# Filter out yogyakarta data from the dataset
get_east_java_data(pre_raw_data, pre_temp_data_name)
get_east_java_data(tmp_raw_data, tmp_temp_data_name)
#%%
# Create destination file for the processed dataset
create_file(pre_data_east_java_name)
create_file(pre_data_east_java_name)
#%%
# Group monthly data in temporary file into yearly on destination file
group_into_yearly_data(pre_temp_data_name, pre_data_east_java_name)
group_into_yearly_data(tmp_temp_data_name, tmp_data_east_java_name)
#%%
# Clean up
delete_file(pre_temp_data_name)
delete_file(tmp_temp_data_name)
#%%
# Copy yield data from unprocessed to processed
copyfile(yield_file_name, yield_file_dest) | true |
03a8a969bb6db63662730a6d224bbda0ecd3226f | Python | harshraj22/problem_solving | /solution/leetcode/1025.py | UTF-8 | 948 | 3.59375 | 4 | [] | no_license | # https://leetcode.com/problems/divisor-game/
# Solved again on Feb28, 2021
class Solution:
from math import sqrt
def __init__(self):
self.cache = dict([(1, False), (2, True), (3, False)])
def divisorGame(self, n: int) -> bool:
if n in self.cache:
return self.cache[n]
for i in range(1, int(sqrt(n))+2):
if n%i == 0 and not self.divisorGame(n-i):
return self.cache.setdefault(n, True)
return self.cache.setdefault(n, False)
'''
class Solution {
map<int, int> cache;
public:
Solution() {
cache = {{1, false}, {2, true}, {3, false}};
};
bool divisorGame(int n) {
if (cache.find(n) != cache.end())
return cache[n];
for (int i = 1; i*i <= n; i += 1)
if (n % i == 0 && divisorGame(n-i) == false)
return cache[n] = true;
return cache[n] = false;
}
};
''' | true |
1c738375a7c06c556444c774b02ee57ed395d5ba | Python | aplaceoutofthesun/misc-files | /PythonMisc/bookjoin.py | UTF-8 | 1,594 | 2.875 | 3 | [] | no_license | #!/usr/bin/env python
#
# bookjoin.py - small script to join a folder of pdf files into a single file
import os
import sys
import shutil
import PyPDF2
def main(target_path, output_fname=None):
if not os.path.exists(target_path) or not os.path.isdir(target_path):
sys.exit("Check the target path.\nIt must be an existing directory.\n")
files_to_merge = [x for x in os.listdir(target_path) if x.endswith(".pdf")]
print("The following files will be merged:")
for f in files_to_merge:
print(" - {} ".format(f))
if input("\nContinue? ").lower() == 'n':
sys.exit(1)
merger = PyPDF2.PdfFileMerger()
reader = PyPDF2.PdfFileReader
if output_fname is None:
out = os.path.abspath(target_path).split('\\')
output_fname = ''.join([out, "_merged.pdf"])
for target_file in files_to_merge:
try:
target_file = os.path.join(target_path, target_file)
pdf_obj = open(target_file, 'rb')
pdf_file = reader(pdf_obj)
merger.append(pdf_file)
pdf_obj.close()
except IOError as io_err:
print("IOError: {}".format(io_err))
print("** STACK **\n{}".format(sys.exc_info()[0]))
merger.write(output_fname)
merger.close()
if __name__ == "__main__":
# print(len(sys.argv), sys.argv)
# sys.exit()
if len(sys.argv) <= 1:
sys.exit("Insufficient args.")
if len(sys.argv) == 2:
main(sys.argv[1])
if len(sys.argv) == 3:
main(sys.argv[1], sys.argv[2]) | true |
47d9259b570a1a60b3247dcea8c1bf14613c0cb8 | Python | doctaphred/stuff-django | /src/accounts/models.py | UTF-8 | 648 | 2.78125 | 3 | [] | no_license | from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""Empty user model, for ease of future customization.
According to the Django docs, "If you're starting a new project,
it's highly recommended to set up a custom user model, even if the
default User model is sufficient for you."
https://docs.djangoproject.com/en/3.0/topics/auth/customizing/
#using-a-custom-user-model-when-starting-a-project
"""
pass
def __str__(self):
if self.first_name and self.last_name:
return f"{self.first_name} {self.last_name}"
else:
return self.get_username()
| true |
6db2af6472b80cd7c899ddcf4a57d71870827a99 | Python | pgm-n117/SSIIP1 | /Estructuras/Maze.py | UTF-8 | 1,049 | 3.859375 | 4 | [] | no_license | import sys, random
def getProblemInstance(n, nCars, seed):
"""
This method generates a new problem instance.
Cells with value 0 means empty cells. Cells with value -1 are walls.
Cells with value i (1..n) are occupied by the i-th car.
Returns a maze (problem instance)
Parameters:
:param n: size of the maze (Int)
:param nCars: number of Cars (<=n) (Int)
:param seed: or the random generator (Int)
"""
maze = [[0 for i in range(n)] for j in range(n)]
random.seed(seed)
#number of walls
nWalls = int(n * (n-2) * 0.2)
#placing walls
for i in range(nWalls):
maze[random.randint(0,n-3) + 1][random.randint(0,n-1)] = -1;
#placing cars, labelled as 1, 2, ..., nCars
if(nCars > n):
print("** Error **, number of cars must be <= dimension of maze!!")
sys.exit()
list = [i for i in range(n)]
for c in range(nCars):
idx = random.randint(0, len(list)-1)
maze[0][list[idx]] = c+1;
list.pop(idx)
return maze; | true |
a9a167ab3db792b1f897f15650cc83aab33cacf2 | Python | CamiloMonteagudo/ViajesMng_Python | /Datos/table.py | UTF-8 | 3,474 | 3.375 | 3 | [] | no_license | import money as Mnd
class Table():
"""Clase base para todas las tables de la base de datos"""
def __init__ (self):
"""Crea una tabla sin ninguna columna"""
self.rows = {}
self.nowId = 0
def NRows(self):
"""Retorna el número de columnas de en la tabla"""
return len(self.rows)
def AddRow(self, key, row):
"""Adiciona un registro a la tabla"""
if not key :
key = self.nowId
self.nowId += 1
self.rows[key] = row
return key
def DelRow( self, key ):
"""Borra un registro de la Tabla"""
if( key not in self.rows): return False
del(self.rows[key])
return True
class RowPresupesto():
"""Datos de un presuspuesto para un viaje"""
def __init__ (self, source, value, moneda=0, cambio=1.0):
self.source = source
self.value = value
self.moneda = moneda
self.cambio = cambio
class RowGasto():
"""Datos de un gasto durante un viaje"""
def __init__ (self, descriccion, str_value, valCuc ):
self.descric = descriccion
self.value = str_value # Cadena con el valor y la moneda Ej: '20 Usd'
self.valCuc = valCuc
def Calculate (self, fn_Cnv):
"""Calcula los valores de los campos según la función de conversion"""
val, mnd = Mnd.GetValue(self.value)
self.cuc = fn_Cnv(val, mnd)
class RowCompra():
"""Datos de una compra durante un viaje"""
def __init__ (self, item, count, str_value, str_valueItem, valCUC, valCucItem, comentario="", precio=0, moneda=0):
self.item = item
self.count = count
self.value = str_value # Cadena con el valor y la moneda Ej: '20 Usd'
self.valItem = str_valueItem
self.valCUC = valCUC
self.valCucItem = valCucItem
self.precio = precio
self.moneda = moneda
self.comentario = comentario
def Calculate (self, fn_Cnv):
"""Calcula los valores de los campos según la función de conversion"""
val, mnd = Mnd.GetValue(self.value)
valItem = val/count
self.valItem = f"{valItem} {Mnd.sCode(mnd) }"
self.valCUC = fn_Cnv(val, mnd)
self.valCucItem = fn_Cnv(valItem, mnd)
class RowVenta():
"""Datos de una venta de un item"""
def __init__ (self, idProd, vendedor, count, precio, moneda, fecha, comentario=""):
self.idProd = idProd
self.vendedor = vendedor
self.count = count
self.precio = precio
self.moneda = moneda
self.fecha = fecha
self.comentario = comentario
class RowPago():
"""Datos de un pago a una venta realizada"""
def __init__ (self, idVent, count, cuc, cup, fecha, comentario=""):
self.idVent = idVent
self.count = count
self.cuc = cuc
self.cup = cup
self.fecha = fecha
self.comentario = comentario
if __name__ == '__main__':
tbPresupesto = Table()
presupuesto = RowPresupesto("Reservas para compras", 100, 2, 1.1 )
tbPresupesto.AddRow(None, presupuesto)
print( f"Número de registros = {tbPresupesto.NRows()}" )
row = tbPresupesto.rows[0]
print( f"Descriccion = {row.source}" )
print( f"Valor = {row.value}" )
print( f"Moneda = {row.moneda}" )
print( f"Cambio = {row.cambio}" )
| true |
9cb4e88df8c8a2398674ec19a413ab518cc56b6d | Python | martinbo94/INF200-2019-Exercises | /src/martin_boe_ex/ex03_project/test_sorting.py | UTF-8 | 2,550 | 3.859375 | 4 | [] | no_license | # -*- coding: utf-8 -*-
__author__ = 'Martin Bø'
__email__ = 'martinb@nmbu.no'
def bubble_sort(data1):
sorted_list = list(data1)
for i in range(len(sorted_list) - 1):
for j in range(len(sorted_list) - 1 - i):
if sorted_list[j] > sorted_list[j+1]:
sorted_list[j], sorted_list[j + 1] = sorted_list[j+1],\
sorted_list[j]
return sorted_list
def test_empty():
"""Test that the sorting function works for empty list"""
assert len(bubble_sort([])) == 0
def test_single():
"""Test that the sorting function works for single-element list"""
assert bubble_sort([1]) == [1]
def sorted_is_not_original():
"""Test that the sorting function returns a new object.
"""
data = [3, 2, 1]
sorted_data = bubble_sort(data)
assert sorted_data is not data
def test_original_unchanged():
"""Test that sorting leaves the original data unchanged."""
data = [3, 2, 1]
bubble_sort(data)
assert data == [3, 2, 1]
def test_sort_sorted():
"""Test that sorting works on sorted data"""
sorted_data = [1, 2, 3, 4, 5]
sorted_list = bubble_sort(sorted_data)
for small, large in zip(sorted_list[:-1], sorted_list[1:]):
assert small <= large
def test_sort_reversed():
"""Test that sorting works on reverse-sorted data"""
sorted_data = [5, 4, 3, 2, 1]
sorted_list = bubble_sort(sorted_data)
for small, large in zip(sorted_list[:-1], sorted_list[1:]):
assert small <= large
def test_sort_all_equal():
"""Test that sorting handles data with identical elements."""
equal_data = [1, 1, 1, 1, 1]
sorted_list = bubble_sort(equal_data)
for small, large in zip(sorted_list[:-1], sorted_list[1:]):
assert small <= large
def test_sorting():
"""Test sorting for various cases"""
string = ["A", "B", "C"]
sorted_string = bubble_sort(string)
for small, large in zip(sorted_string[:-1], sorted_string[1:]):
assert small <= large
negative_numbers = [-3, -5, -1, -99, -34, -33]
sorted_negative_numbers = bubble_sort(negative_numbers)
for small, large in zip(sorted_negative_numbers[:-1],
sorted_negative_numbers[1:]):
assert small <= large
odd_length_list = [3, 5, 1, 99, 34, 33, -2]
odd_length_list_sorted = bubble_sort(odd_length_list)
for small, large in zip(odd_length_list_sorted[:-1],
odd_length_list_sorted[1:]):
assert small <= large
| true |
b98872e656bc3fb0e12a8ce8d5ed73668e736de2 | Python | cohoe/barbados | /barbados/factories/origin.py | UTF-8 | 316 | 2.546875 | 3 | [] | no_license | from barbados.factories.base import BaseFactory
from barbados.objects.origin import Origin
class OriginFactory(BaseFactory):
@classmethod
def raw_to_obj(cls, raw):
raw_obj = cls.sanitize_raw(raw_input=raw, required_keys=cls.required_keys)
return Origin(**raw_obj) if raw_obj else Origin()
| true |
10d06b93ea3c0800c1df67934eb7b449d6e666da | Python | syujisu/For_Algorithm | /Baekjoon/12865.평범한 배낭.py | UTF-8 | 1,733 | 3.515625 | 4 | [] | no_license | # 문제
# 이 문제는 아주 평범한 배낭에 관한 문제이다.
# 한 달 후면 국가의 부름을 받게 되는 준서는 여행을 가려고 한다. 세상과의 단절을 슬퍼하며 최대한 즐기기 위한 여행이기 때문에, 가지고 다닐 배낭 또한 최대한 가치 있게 싸려고 한다.
# 준서가 여행에 필요하다고 생각하는 N개의 물건이 있다. 각 물건은 무게 W와 가치 V를 가지는데, 해당 물건을 배낭에 넣어서 가면 준서가 V만큼 즐길 수 있다. 아직 행군을 해본 적이 없는 준서는 최대 K무게까지의 배낭만 들고 다닐 수 있다. 준서가 최대한 즐거운 여행을 하기 위해 배낭에 넣을 수 있는 물건들의 가치의 최댓값을 알려주자.
# 입력
# 첫 줄에 물품의 수 N(1 ≤ N ≤ 100)과 준서가 버틸 수 있는 무게 K(1 ≤ K ≤ 100,000)가 주어진다. 두 번째 줄부터 N개의 줄에 거쳐 각 물건의 무게 W(1 ≤ W ≤ 100,000)와 해당 물건의 가치 V(0 ≤ V ≤ 1,000)가 주어진다.
# 입력으로 주어지는 모든 수는 정수이다.
# 출력
# 한 줄에 배낭에 넣을 수 있는 물건들의 가치합의 최댓값을 출력한다.
# 예제 입력 1
# 4 7
# 6 13
# 4 8
# 3 6
# 5 12
# 예제 출력 1
# 14
n,k = map(int, input().split())
dp = [[0]*(k+1) for _ in range(n+1)]
for i in range(1, n+1):
w, v = map(int, input().split()) #w = weight / v = value
for j in range(1, k+1):
if j < w:
dp[i][j] = dp[i-1][j] #작을 때는 위의 값과 동일 값 삽입
else:
dp[i][j] = max(dp[i-1][j], dp[i-1][j-w]+v) #위의 값과 이전 값의 최대 가치에 이전 값을 더해 삽입
print(dp[n][k]) | true |
04e92b192153fa5753406c248227a3dfafb1455b | Python | viakondratiuk/e-olimp | /31.py | UTF-8 | 380 | 3.203125 | 3 | [] | no_license | import datetime
dates = []
intervals = int(input())
for i in range(intervals):
dates.append(input())
fridays = 0
for d in dates:
years = list(map(int, d.split()))
for year in range(years[0], years[1] + 1):
for month in range(1, 13):
if datetime.datetime(year, month, 13).weekday() == 4:
fridays +=1
print(fridays) | true |
f0c1b3c9f9c921dccf9406e79448787617d3a5fb | Python | sjtupig/codingInterviews | /034-丑数.py | UTF-8 | 2,905 | 4 | 4 | [] | no_license | #暴力解法:超时
# -*- coding:utf-8 -*-
class Solution1:
def GetUglyNumber_Solution(self, index):
# write code here
#ugly = 5**a * 3**b * 2**c, 看a,b,c取值,0-无穷
def is_ugly(a, mul):
for i in mul[::-1]:
while a%i==0:
a=a/i
if a==1:return True
return False
cnt = 0
i = 1
mul = [2,3,5]
while True:
if is_ugly(i, mul):
cnt += 1
mul.append(i)
if cnt == index-1:
return i
i += 1
# -*- coding:utf-8 -*-
###重点是每次都只加进来一个数字
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
#ugly = 5**a * 3**b * 2**c, 看a,b,c取值,0-无穷
res = [1,]
nums = 1
while nums < index:
max_num = max(res)
candidate = []
for i in res:
if 2*i>max_num:
candidate.append(2*i)
break
for i in res:
if 3*i>max_num:
candidate.append(3*i)
break
for i in res:
if 5*i>max_num:
candidate.append(5*i)
break
res.append(min(candidate))
nums+=1
return res[index-1] if index > 0 else 0
#更快解法,每次都记录乘数,因为上一次2*res[low_2]才大于max_num,所以这轮计算式,low_2之前的数都不可能比max_num大,从此往后计算,更快
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
#ugly = 5**a * 3**b * 2**c, 看a,b,c取值,0-无穷
res = [1,]
nums = 1
low_2,low_3,low_5 = 0,0,0
while nums < index:
max_num = max(res)
candidate = []
for i in range(low_2,len(res)):
if 2*res[i]>max_num:
candidate.append(2*res[i])
low_2 = i
break
for i in range(low_3,len(res)):
if 3*res[i]>max_num:
candidate.append(3*res[i])
low_3 = i
break
for i in range(low_5,len(res)):
if 5*res[i]>max_num:
candidate.append(5*res[i])
low_5 = i
break
res.append(min(candidate))
nums+=1
return res[index-1] if index > 0 else 0
sol = Solution2()
print(sol.GetUglyNumber_Solution(1))
print(sol.GetUglyNumber_Solution(2))
print(sol.GetUglyNumber_Solution(3))
print(sol.GetUglyNumber_Solution(4))
print(sol.GetUglyNumber_Solution(5)) | true |
6dd71a9afd40fbc65b0b6de63819f93c61ec4038 | Python | krvc/Python-Programs | /euler_problems/prob_3.py | UTF-8 | 539 | 4.09375 | 4 | [] | no_license | """
Problem:3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
def prim_fact(n):
"Returns all the prime factors of a positive integer"
if n < 1:
raise ValueError, "Parameter must be at least 1."
factors = []
d = 2
while (n > 1):
while (n%d==0):
factors.append(d)
n = n / d
d = d + 1
return factors
pf = prim_fact(600851475143)
largest_prime_factor = pf[-1]
print largest_prime_factor
| true |
cc1930d4b0a745acc47aa9c285852034aefe8d0b | Python | wangbokun/Script | /Mysql批量dump时间段格式表.py | UTF-8 | 1,646 | 2.640625 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: kionf
#
import os
import sys
import datetime
#需要加时间的日期表
Change_Tables = ['expadd', 'test', 'user_lock']
Dump_Tables = ''
def strtodatetime(datestr, format):
return datetime.datetime.strptime(datestr, format)
def datediff(beginDate, endDate):
format = "%Y_%m_%d";
bd = strtodatetime(beginDate, format)
ed = strtodatetime(endDate, format)
oneday = datetime.timedelta(days=1)
count = 0
while bd != ed:
ed = ed - oneday
count += 1
return count
def datetostr(date):
return str(date)[0:10]
def GenerateTables(beginDate, endDate):
format = "%Y_%m_%d"
bd = strtodatetime(beginDate, format)
ed = strtodatetime(endDate, format)
oneday = datetime.timedelta(days=1)
num = datediff(beginDate, endDate) + 1
li = []
fuck = []
for i in range(0, num):
li.append(datetostr(ed.strftime("%Y_%m_%d")))
ed = ed - oneday
for table in Change_Tables:
for date in li:
fuck.append(table + date)
fuck = ' '.join(fuck)
return fuck
def main():
bdate = raw_input('开始时间: ')
edate = raw_input('结束时间: ')
Date_Tables = GenerateTables(bdate, edate)
Dump_Tables = Date_Tables
print('开始备份数据。。。')
DumpCommand = 'mysqldump --force -uroot -p -h172.16.0.13 --skip-lock-tables your_database ' + Dump_Tables + ' |gzip > dump.sql.gz'
print DumpCommand
os.system(DumpCommand)
print('文件大小为:\n')
os.system('ls -alh /root/script/dump.sql.gz')
if __name__ == '__main__':
main()
| true |
5eea947e82833ed2302231880656b28e4ef8344e | Python | kippen/Python_Class | /lab_05_01.py | UTF-8 | 1,633 | 5.0625 | 5 | [] | no_license | '''
1) Create an application that uses a list to hold the following data:
Id Name Email
1 Bob Smith BSmith@Hotmail.com
2 Sue Jones SueJ@Yahoo.com
3 Joe James JoeJames@Gmail.com
2) Add code that lets users appends a new row of data.
3) Add a loop that lets the user keep adding rows.
4) Ask the user if they want to save the data to a file when they exit the loop.
5) Save the data to a file if they say 'yes'
'''
#Create an application that uses a list to hold the following data
lstHeader = ["ID", "Name", "Email"]
lstRow1 = ["1", "Bob Smith", "bsmith@hotmail.com"]
lstRow2 = ["2", "Sue Jones", "suej@yahoo.com"]
lstRow3 = ["3", "Joe James", "joejames@gmail.com"]
lstTable = [lstRow1, lstRow2, lstRow3]
print(lstTable)
#Add code that lets users appends a new row of data.
#Add a loop that lets the user keep adding rows.
while(True):
strID = input("Input an ID: ")
strName = input("Input Customer Name (First and Last): ")
strEmail = input("Input Customer Email: ")
print("You Entered: ", strID, strName, strEmail)
lstRowX = [strID, strName, strEmail]
print(lstRowX)
lstTable.append(lstRowX)
print(lstTable)
strMoreData = input("Add another customer? (y/n): ")
if(strMoreData.lower() == "y"): continue
else: break
#Ask the user if they want to save the data to a file when they exit the loop
strUserInput = input("Do you want to save your data (y/n)?: ")
if(strUserInput.lower() == "y"):
# Save the data to a file if they say 'yes'
objFile = open("C:\python\\list.txt", "a")
objFile.write(str(lstTable)) # write data to file
objFile.close() # close file
else:
print("Data not saved")
| true |
6a77d5acc285700921e56bd8aa6df0b8d6d9fc75 | Python | Mikerpen22/Python_game | /1A2B_ver3.py | UTF-8 | 7,765 | 2.96875 | 3 | [] | no_license | from tkinter import *
from tkinter import messagebox
from PIL import Image, ImageTk
from time import sleep
import pygame
import random
answer = ""
playerGuess = ""
nOfDigits = 4
count = 10
# 我無聊亂放音樂
pygame.init()
pygame.mixer.music.load('Fantasy_Game_Background_Looping.mp3') # Loading File Into Mixer
pygame.mixer.music.play()
class NumberGame(Tk):
def __init__(self):
Tk.__init__(self)
container = Frame(self)
container.grid()
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, MainWin3, EndPage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky=NSEW)
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
image = Image.open('gate.jpg')
self.bg_load = ImageTk.PhotoImage(image) # Add self or image will be garbage collected
bg1 = Button(self, width=130, height=260, image=self.bg_load)
bg2 = Button(self, width=130, height=260, image=self.bg_load)
bg2 = Button(self, width=130, height=260, image=self.bg_load)
bg3 = Button(self, width=130, height=260, image=self.bg_load, command=lambda: controller.show_frame(MainWin3))
bg1.pack(side=LEFT)
bg2.place(relx=0.5, rely=0.5, anchor=CENTER)
bg3.pack(side=RIGHT)
# bg3.place(x=0, y=0, relwidth=1, relheight=1)
# but_go = Button(bg3, height=4, width=8, text='Come on!', command=lambda: controller.show_frame(MainWin3))
# but_go.pack(side=BOTTOM)
class EndPage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
image = Image.open('key.jpg')
self.bg_load = ImageTk.PhotoImage(image) # Add self or image will be garbage collected
bg_label = Label(self, image=self.bg_load)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)
but_go = Button(bg_label, height=4, width=8, text='Come on!', command=lambda: controller.show_frame(MainWin3))
but_go.pack(side=BOTTOM)
class MainWin3(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.grid()
self.setup_widgets()
self.controller = controller
def setup_widgets(self):
def n_digit_num(n):
numbers = random.sample(range(10), n)
rand = ''.join(map(str, numbers))
return rand
def new_game():
print("new_game")
global nOfDigits
global answer
label.config(text='')
resultLabel.config(text="")
answers.delete(1.0, END)
answer = n_digit_num(nOfDigits)
print(answer)
def check_guess():
global playerGuess
global answer
global nOfDigits
global count
playerGuess = label.cget("text")
if len(playerGuess) == nOfDigits:
count = count - 1
a = cal_a(playerGuess)
b = cal_b(playerGuess)
show_result(a, b)
label.config(text="")
answers.insert(INSERT, playerGuess + " " + str(a) + "A" + str(b) + "B" + "\n")
chanceLabel.config(text=str(count)+" chances left")
else:
messagebox.showinfo("提醒", "位數要為" + str(nOfDigits))
label.config(text="")
if count == 0:
chanceLabel.config(text="Try Again!")
count = 10
def cal_a(guess):
global answer
a = 0
for i in range(len(answer)):
if guess[i] == answer[i]:
a = a + 1
return a
def cal_b(guess):
global answer
b = 0
k = len(answer)
for i in range(k):
for j in range(k):
if i != j:
if guess[i] == answer[j]:
b = b + 1
return b
def show_result(a, b):
if a == nOfDigits:
result = "You Win"
else:
result = str(a) + "A" + str(b) + "B"
resultLabel.config(text=result)
sleep(1)
self.controller.show_frame(EndPage)
def click_but1():
label.configure(text=label.cget("text") + "1")
def click_but2():
label.configure(text=label.cget("text") + "2")
def click_but3():
label.configure(text=label.cget("text") + "3")
def click_but4():
label.configure(text=label.cget("text") + "4")
def click_but5():
label.configure(text=label.cget("text") + "5")
def click_but6():
label.configure(text=label.cget("text") + "6")
def click_but7():
label.configure(text=label.cget("text") + "7")
def click_but8():
label.configure(text=label.cget("text") + "8")
def click_but9():
label.configure(text=label.cget("text") + "9")
def click_but0():
label.configure(text=label.cget("text") + "0")
def click_butBack():
s = label.cget("text")
label.configure(text=s[0:-1])
resultLabel = Label(self, text="0A0B", font=('arial', 20))
guessBtn = Button(self, text="Guess", command=check_guess, height=3, width=20)
new_gameBtn = Button(self, text="New Game", command=new_game, height=3, width=20)
chanceLabel = Label(self, height=1, borderwidth=5, text="10 chances left", font=('arial', 12))
label = Label(self, height=1, borderwidth=5, text="", font=('arial', 20))
btn_1 = Button(self, text="1", command=click_but1, height=3, width=6)
btn_2 = Button(self, text="2", command=click_but2, height=3, width=6)
btn_3 = Button(self, text="3", command=click_but3, height=3, width=6)
btn_4 = Button(self, text="4", command=click_but4, height=3, width=6)
btn_5 = Button(self, text="5", command=click_but5, height=3, width=6)
btn_6 = Button(self, text="6", command=click_but6, height=3, width=6)
btn_7 = Button(self, text="7", command=click_but7, height=3, width=6)
btn_8 = Button(self, text="8", command=click_but8, height=3, width=6)
btn_9 = Button(self, text="9", command=click_but9, height=3, width=6)
btn_0 = Button(self, text="0", command=click_but0, height=4, width=14)
btn_back = Button(self, text="←", command=click_butBack, height=4, width=6)
btn_1.grid(row=3, column=0)
btn_2.grid(row=3, column=1)
btn_3.grid(row=3, column=2, sticky="w")
btn_4.grid(row=4, column=0)
btn_5.grid(row=4, column=1)
btn_6.grid(row=4, column=2, sticky="w")
btn_7.grid(row=5, column=0)
btn_8.grid(row=5, column=1)
btn_9.grid(row=5, column=2, sticky="w")
btn_0.grid(row=6, column=0, columnspan=2, sticky="w")
btn_back.grid(row=6, column=2, sticky="e")
answers = Text(self, width=20, height=8, bg='black', foreground='yellow')
answers.grid(row=5, column=4, rowspan=4, pady=2)
label.grid(row=1, column=0, columnspan=3, sticky=W)
chanceLabel.grid(row=0, column=0, columnspan=3, sticky=W)
resultLabel.grid(row=1, column=4)
guessBtn.grid(row=3, column=4)
new_gameBtn.grid(row=4, column=4)
new_game()
app = NumberGame()
app.mainloop() | true |
26dfaa27bf6fe58d4b330a140761bd557474180f | Python | cieabora/opencv | /opencv6.py | UTF-8 | 532 | 2.8125 | 3 | [] | no_license | import cv2
import numpy as np
image = np.full((512, 512, 3), 255, np.uint8)
# image = cv2.line(image, (0, 0), (255, 255), (255, 0, 0), 3)
#
# image = cv2.rectangle(image, (20, 20), (255, 255), (255, 0, 0), 3)
#
# image = cv2.circle(image, (255, 255), 30, (255, 0, 0), 3)
#
# points = np.array([[5, 5], [128, 258], [463, 444], [400, 150]])
# image = cv2.polylines(image, [points], True, (0, 0, 255), 4)
#
image = cv2.putText(image, "Hello World", (0, 200), cv2.FONT_ITALIC, 2, (255, 0, 0))
cv2.imshow("image", image)
cv2.waitKey(0) | true |
d4b5037d8c234446943e7e482257a7a13721804b | Python | yotam-happy/DeepProject | /experiment_setup/src/PairwisePredict.py | UTF-8 | 5,511 | 2.828125 | 3 | [] | no_license | import itertools
import math
import operator
import random
from WikilinksStatistics import *
class PairwisePredict:
"""
This model takes a pairwise model that can train/predict on pairs of candidates for a wikilink
and uses it to train/predict on a list candidates using a knockout method.
"""
def __init__(self, pairwise_model):
"""
:param pairwise_model: The pairwise model used to do prediction/training on a triplet
(wikilink,candidate1,candidate2)
"""
self._pairwise_model = pairwise_model
def predict_prob(self, mention, candidate):
raise "not supported"
def predict(self, mention):
# do a knockout
l = [candidate for candidate in mention.candidates]
random.shuffle(l)
return self._predict(mention, l)
def predict2(self, mention, returnProbMode = False):
"""
pairwise prediction between all possible pairs of candidates (no self pairs)
every comprison is calculated twice for eliminating order importance
:param wikilink:
:param candidates:
:param returnProbMode: if true returns also vote matrix (i rows j column matrix with number of votes of
i beats j. Returns also cond_prob (Same idea with conditional probability of i beats j)
:return:
"""
l = [candidate for candidate in mention.candidates]
if len(l) == 1:
return l[0]
cond_prob = np.ones((len(mention.candidates), len(mention.candidates)))
cond_votes = np.zeros((len(mention.candidates), len(mention.candidates)))
ranking = {x:0.0 for x in l}
# by using a and b we diminish the importance of order in the input
for i in xrange(len(l) - 1):
for j in xrange(i + 1, len(l)):
if returnProbMode:
a, i_beats_j_1 , j_beats_i_1, votes_i_1, votes_j_1 = \
self.getWinnerProbAndUpdateVotes(mention, l[i], l[j] , cond_votes[i][j], cond_votes[j][i])
b, j_beats_i_2, i_beats_j_2, votes_j_2, votes_i_2 = \
self.getWinnerProbAndUpdateVotes(mention, l[j], l[i], cond_votes[j][i], cond_votes[i][j])
if a and b is not None:
cond_votes[i][j], cond_votes[j][i] = votes_i_1 + votes_i_2, votes_j_1 + votes_j_2
else:
cond_votes[i][j] = cond_votes[j][i] = None # TODO : verify that the none task is handled right
cond_prob[i][j] = sum(filter(None, [i_beats_j_1, i_beats_j_2]))
cond_prob[i][j] *= 0.5 if cond_prob[i][j] is not None else 0
cond_prob[j][i] = sum(filter(None, [j_beats_i_1, j_beats_i_2]))
cond_prob[j][i] *= 0.5 if cond_prob[i][j] is not None else 0
else:
a = self._pairwise_model.predict(mention, l[i], l[j])
if a is not None:
ranking[a] += 1
b = self._pairwise_model.predict(mention, l[j], l[i])
if b is not None:
ranking[b] += 1
m = max(ranking.iteritems(), key=operator.itemgetter(1))[0]
mv = max(ranking.iteritems(), key=operator.itemgetter(1))[1]
if m == 0:
return None
finals = {x: mention.candidates[x] for x,y in ranking.items() if y == mv}
final = max(finals.iteritems(), key=operator.itemgetter(1))[0]
if returnProbMode:
# print 'candidates order: ',l
# print 'cond_votes: ',filter(None, cond_votes.tolist())
final = l[np.argmax(np.sum(filter(None, cond_votes.tolist()), axis=1))]
return final, cond_prob, cond_votes
else:
return final
def getWinnerProbAndUpdateVotes(self, mention, cand_first, cand_last, a_beats_b, b_beats_a):
try:
winner , first_cand_winner_prob = self._pairwise_model.predict(mention, cand_first, cand_last,
return_score=True)
except:
print 'wlink: ', mention.mention_text(), '\t first: ', cand_first, '\t last: ', cand_last # FIXME
if winner is None:
return None, None, None, None, None
else:
second_cand_winner_prob = 1 - first_cand_winner_prob
if winner == cand_first and winner is not None:
a_beats_b += 1
elif winner is not None:
b_beats_a += 1
# print '** prob of ',str(cand_first),' to beat ',str(cand_last),' is: ', str(first_cand_winner_prob)
# print '** votes ',str(cand_first),' beats ',str(cand_last),' : ',str(a_beats_b)
# print 'winner :', winner,'\n'
return winner, first_cand_winner_prob, second_cand_winner_prob, a_beats_b, b_beats_a
def _predict(self, mention, l):
while len(l) > 1:
# create a list of surviving candidates by comparing couples
next_l = []
for i in range(0, len(l) - 1, 2):
pr = self._pairwise_model.predict(mention, l[i], l[i+1])
a = l[i] if pr > 0.5 else l[i+1]
if a is not None:
next_l.append(a)
if len(l) % 2 == 1:
next_l.append(l[-1])
l = next_l
if len(l) == 0:
return None
return l[0]
| true |
330be548f60552645d9ed423625f7f55f4057bd4 | Python | jonasrosland/lpthw | /ex3.py | UTF-8 | 992 | 4.53125 | 5 | [] | no_license | # Print out a line
print "I will now count my chickens:"
# Calculate 25 + 30 divided by 6
print "Hens", 25 + 30 / 6
# Calculate 100 - 25 times 3 modulo 4, which gives 100 - ((25 * 3)%4)
print "Roosters", 100 - 25 * 3 % 4
# Print a line
print "Now I will count the eggs:"
# Calculate (3 + 2 + 1 - 5) + (4 % 2) - (1 / 4) + 6
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Print a line
print "Is it true that 3 + 2 < 5 - 7?"
# Calculate if (3 + 2) is less than (5 - 7)
print 3 + 2 < 5 -7
# Print a line and calculate 3 + 2
print "What is 3 + 2?", 3 + 2
# Print a line anc calculate 5 - 7
print "What is 5 - 7?", 5 - 7
# Print a line
print "Oh, that's why it's False."
# Print a line
print "How about some more."
# Print a line and calculate if 5 is greater than -2
print "Is it greater?", 5 > -2
# Print a line and calculate if 5 is greater or equal to -2
print "Is it greater or equal?", 5 >= -2
# Print a line and calculate if 5 is less or equal to -2
print "Is it less or equal?", 5 <= -2 | true |
e718f7cff9ad573d274fd32f41f3843b07ed7954 | Python | pawlos/dnr-visualizer | /parser-tests.py | UTF-8 | 2,038 | 3.234375 | 3 | [
"MIT"
] | permissive | import unittest
import parser
import datetime
from bs4 import BeautifulSoup
class TestParserFunctions(unittest.TestCase):
def test_getGuest_works_when_there_is_with_phrase(self):
self.assertEqual('Coyotee',parser.getGuest('Episode with Coyotee'))
def test_getGuest_works_when_there_is_only_guest_info(self):
self.assertEqual('Yosamite Sam', parser.getGuest('Yosamite Sam'))
def test_parseEpisode_extracts_episode_no_correctly(self):
episode = self.execute()
self.assertEqual(1008, episode['no'])
def test_parseEpisode_extract_title_correctly(self):
episode = self.execute()
self.assertEqual('Michelle Smith', episode['guest'])
def test_parseEpisode_extract_guest_correctly(self):
episode = self.execute()
self.assertEqual('Building Development Teams with Michelle Smith', episode['title'])
def test_parseEpisode_extract_date_correctly(self):
episode = self.execute()
self.assertEqual(datetime.datetime(2014,7,15), episode['date'])
def test_encode_datetime_does_correctly_returns_string(self):
date = datetime.datetime(2014,7,15);
self.assertEqual('2014-07-15', parser.encode_datetime(date))
def test_parseEpisode_extract_url_correctly(self):
episode = self.execute()
self.assertEqual('http://www.dotnetrocks.com/default.aspx?showNum=1008', episode['url'])
def test_parseEpisodeContent_extracts_time_correctly(self):
html = '<span id="ContentPlaceHolder1_lblTime"><font size="1">56 minutes</font></span>'
html = BeautifulSoup(html)
time = parser.extractEpisodeTime(html)
self.assertEqual(56, time)
def test_parseEpisodeContent_when_empty_does_not_throw_exception(self):
html = '<span id="ContentPlaceHolder1_lblTime"><font size="1"> </font></span>'
html = BeautifulSoup(html)
time = parser.extractEpisodeTime(html)
self.assertEqual(0, time)
def execute(self):
html = '<td>1008</td><td><a href="default.aspx?showNum=1008">Building Development Teams with Michelle Smith</a></td><td>7/15/2014</td>'
html = BeautifulSoup(html)
return parser.parseEpisode(html)
if __name__ == '__main__':
unittest.main() | true |
fc9c0bfe00ae9b1638d8a517e7206c32128a5be5 | Python | fahim9898/LearningGit | /for_loop.py | UTF-8 | 91 | 2.625 | 3 | [] | no_license | for i in range(10):
print("hello")
print("Done with for loop")
print("WE in Dev Branch") | true |
2c1e4b8831e3bf6102cf6f1223756087cc617645 | Python | cgautamkrish/optimize-taxi | /fare.py | UTF-8 | 278 | 2.75 | 3 | [] | no_license |
class Fare:
def __init__(self, amount, tips, toll, total, payment_type):
self.amount = amount
self.tips = tips
self.toll = toll
self.total = total
self.payment_type = payment_type
def getAmount(self):
return self.amount
def getTotal(self):
return self.total | true |
c0f324499587d92a00f4140e494e802e562c2a74 | Python | gdeside/LEPL1506_Projet4 | /codepython/coda_tools.py | UTF-8 | 4,314 | 2.984375 | 3 | [
"BSD-3-Clause"
] | permissive | # -*- coding: utf-8 -*-
"""
Some tools to import and process data from the codas.
Created on Wed Mar 17
@author: opsomerl
"""
import pandas as pd
import numpy as np
from scipy import signal
def import_data(file_path):
"""Imports data from a CODA *.txt file and stores it in a data frame"""
# Import data and store it in a data frame
df = pd.read_csv(file_path,
sep = '\t',
header = None,
skiprows = 5)
# Rename columns
nvar = np.size(df,1)
nmrk = int((nvar-1)/4)
colnames = ['time']
for i in range(nmrk):
mrk = i+1
Xname = ['Marker%d_X' % mrk]
Yname = ['Marker%d_Y' % mrk]
Zname = ['Marker%d_Z' % mrk]
Vname = ['Marker%d_Visibility' % mrk]
colnames = colnames + Xname + Yname + Zname + Vname
df.columns = colnames
# Set occluded samples to NaNs
for i in range(nmrk):
mrk = i+1
Xname = 'Marker%d_X' % mrk
Yname = 'Marker%d_Y' % mrk
Zname = 'Marker%d_Z' % mrk
Vname = 'Marker%d_Visibility' % mrk
df.loc[df[Vname] == 0, Xname] = np.nan
df.loc[df[Vname] == 0, Yname] = np.nan
df.loc[df[Vname] == 0, Zname] = np.nan
return df
def manipulandum_center(coda_df, markers_id=[1,2,3,4]):
"""Computes the position of the center of the manipulandum from the position
of the four markers.
Args:
-----
coda_df: data_frame
data frame containing the position of all markers a
markers_id: integer_list
ids of markers 1, 2, 3, 4 with 1 being top left,
2 being top right, 3 being bottom left and 4 being
bottom right:
1-----2
| |
| GLM | (front view)
| |
3-----4
| X
|
FRAME |
|
_________|
Y
"""
# Store 3-d positions in matrices
pos1x = coda_df['Marker%d_X' % markers_id[0]].to_numpy()
pos1y = coda_df['Marker%d_Y' % markers_id[0]].to_numpy()
pos1z = coda_df['Marker%d_Z' % markers_id[0]].to_numpy()
pos1 = np.vstack((pos1x,pos1y,pos1z))
pos2x = coda_df['Marker%d_X' % markers_id[1]].to_numpy()
pos2y = coda_df['Marker%d_Y' % markers_id[1]].to_numpy()
pos2z = coda_df['Marker%d_Z' % markers_id[1]].to_numpy()
pos2 = np.vstack((pos2x,pos2y,pos2z))
pos3x = coda_df['Marker%d_X' % markers_id[2]].to_numpy()
pos3y = coda_df['Marker%d_Y' % markers_id[2]].to_numpy()
pos3z = coda_df['Marker%d_Z' % markers_id[2]].to_numpy()
pos3 = np.vstack((pos3x,pos3y,pos3z))
pos4x = coda_df['Marker%d_X' % markers_id[3]].to_numpy()
pos4y = coda_df['Marker%d_Y' % markers_id[3]].to_numpy()
pos4z = coda_df['Marker%d_Z' % markers_id[3]].to_numpy()
pos4 = np.vstack((pos4x,pos4y,pos4z))
# Compute X-axis
X1 = (pos1 - pos3)
X1 = X1 / np.linalg.norm(X1,axis=0)
X2 = (pos2 - pos4)
X2 = X2 / np.linalg.norm(X2,axis=0)
# Compute Y-axis
Y1 = (pos1 - pos2)
Y1 = Y1 / np.linalg.norm(Y1,axis=0)
Y2 = (pos3 - pos4)
Y2 = Y2 / np.linalg.norm(Y2,axis=0)
# Compute the center of the manipulandum from the four triplets of markers
# 124
Z = np.cross(X2,Y1,axisa=0,axisb=0,axisc=0)
Z = Z / np.linalg.norm(Z,axis=0)
C1 = pos1 - 37*X2 - 10*Y1 - 20*Z
# 243
Z = np.cross(X2,Y2,axisa=0,axisb=0,axisc=0)
Z = Z / np.linalg.norm(Z,axis=0)
C2 = pos2 - 37*X2 + 10*Y2 - 20*Z
# 431
Z = np.cross(X1,Y2,axisa=0,axisb=0,axisc=0)
Z = Z / np.linalg.norm(Z,axis=0)
C3 = pos4 + 37*X1 + 10*Y2 - 20*Z
# 312
Z = np.cross(X1,Y1,axisa=0,axisb=0,axisc=0)
Z = Z / np.linalg.norm(Z,axis=0)
C4 = pos3 + 37*X2 - 10*Y2 - 20*Z
# Center = average of the four centers
C = np.nanmean(np.array((C1,C2,C3,C4)),axis=0)
return C
| true |
c188f732fe3b8df7a50a4b9585ccf21fe7e22ac3 | Python | omarmohd/historicalStockPrices | /Job3/MapReduce/mapper.py | UTF-8 | 2,934 | 3.28125 | 3 | [] | no_license | #!/usr/bin/env python3
import sys
# Serve per creare dizionari annidati
class AutoTree(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
# VARIABILI GLOBALI:
# dizionario che immagizzina azione > mese > data iniziale, data finale, valori
stock_mese = {}
# serve da iteratore per i mesi
months = ['GEN', 'FEB', 'MAR', 'APR', 'MAG', 'GIU',
'LUG', 'AGO', 'SET', 'OTT', 'NOV', 'DIC']
def create_stock_info(map, stock, data, valore_chiusura):
mese = str(data[5:7])
if stock in map:
if mese in map[stock]:
if data < map[stock][mese]["data_inizio"]["data"]:
map[stock][mese]["data_inizio"]["data"] = data
map[stock][mese]["data_inizio"]["valore"] = valore_chiusura
if data > map[stock][mese]["data_fine"]["data"]:
map[stock][mese]["data_fine"]["data"] = data
map[stock][mese]["data_fine"]["valore"] = valore_chiusura
else:
stock_info_to_add = {
"data_inizio": {"data": data, "valore": valore_chiusura},
"data_fine": {"data": data, "valore": valore_chiusura},
}
map[stock][mese] = stock_info_to_add
else:
map[stock] = {}
stock_info_to_add = {
"data_inizio": {"data": data, "valore": valore_chiusura},
"data_fine": {"data": data, "valore": valore_chiusura},
}
map[stock][mese] = stock_info_to_add
return map
stock_monthly_variation = AutoTree()
csvIn = sys.stdin
for line in csvIn:
line_input = line.strip().split(",")
# solo anno 2017 è d'interesse
if line_input[7][0:4] == "2017":
# print('{}\t{}\t{}'.format(input[0], input[2], input[7]))
# values = line.strip().split('\t')
# stock, data, valore_chiusura = values[0], values[7], values[1]
stock, data, valore_chiusura = (
line_input[0],
line_input[7],
float(line_input[1]),
)
monthly_stock = create_stock_info(stock_mese, stock, data, valore_chiusura)
# calcolo variazione mensile per ogni azione, in base alle date
for stock in monthly_stock:
for mese in monthly_stock[stock]:
variazione = (((monthly_stock[stock][mese]["data_fine"]["valore"]) * 100)
/ monthly_stock[stock][mese]["data_inizio"]["valore"]) - 100
stock_monthly_variation[stock][mese] = round(variazione, 2)
# tengo solo azioni con 12 mesi
for stock in list(stock_monthly_variation):
if len(stock_monthly_variation[stock].keys()) != 12:
del stock_monthly_variation[stock]
for stock in stock_monthly_variation:
line_to_print = []
line_to_print.append(stock)
for month in stock_monthly_variation[stock]:
line_to_print.append(month)
line_to_print.append(stock_monthly_variation[stock][month])
print(*line_to_print, sep='\t')
| true |
66e3d9c4f410eba7af56a83e22f6242194028f48 | Python | futurecolors/fc-toolbelt | /fc_toolbelt/tasks/git.py | UTF-8 | 1,312 | 2.671875 | 3 | [] | no_license | # coding: utf-8
from fabric.api import local, run
from fabric.tasks import Task
__all__ = ['prune']
class DeleteMergedBranches(Task):
"""Useful git aliases"""
name = 'git'
default_branches = ('dev', 'master')
delete_merged_brances_cmd = ('echo git push origin'
'$(git branch -r --merged origin/master'
'| sed "s/origin\\//:/" | egrep -v "HEAD|%s")' % '|'.join(default_branches))
def run(self):
result = local(self.delete_merged_brances_cmd, capture=True)
if result == 'git push origin':
print "No old branches, yeah!"
else:
print result
class GetBranch(Task):
"""Get branch by mask"""
name = 'get_git_branch'
get_branch_commnad = (
"""git for-each-ref --sort='-committerdate' --format='%(refname:short)' """
"""| grep '{0}' | head -n 1"""
)
def run(self, git_branch, **kwargs):
result = local(self.get_branch_commnad.format(git_branch), capture=True)
branch_name = result.strip()
if not branch_name:
raise AttributeError(
"Bad git branch mask: \n"
"%s" % result
)
return branch_name
get_branch = GetBranch()
prune = DeleteMergedBranches()
| true |
c9e3962af6fbab9972cdaeddffe82f0f31186a5f | Python | earth-chris/grad-school | /projects/costarica/cr-plot-covar-dist.py | UTF-8 | 2,736 | 2.5625 | 3 | [
"MIT"
] | permissive | # script to plot the density distributions of covariates at the field sites and for costa rica
import aei
import gdal
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib tk
# set the paths to use
base = '/home/salo/Downloads/costa-rica/'
plots = base + 'plots/'
sp_file = base + 'sp-data/sites-covariates.csv'
# set the raster paths
biomass = base + 'raster/biomass.tif'
fcover = base + 'raster/fcover.tif'
radar = base + 'raster/radar.tif'
tassledcap = base + 'raster/tassled-cap.tif'
temperature = base + 'raster/temperature.tif'
treecover = base + 'raster/tree-cover.tif'
# read the species data into pandas
sp = pd.read_csv(sp_file)
# create a list of raster files, bands, and names to iterate through
rasters = [biomass, fcover, fcover, fcover, radar, radar,
tassledcap, tassledcap, tassledcap, temperature,
temperature, temperature, treecover]
bands = [0,0,1,2,0,1,0,1,2,0,1,2,0]
names = ['Biomass', 'SoilPct', 'VegPct', 'Impervious', 'HH', 'HV',
'tcBrt', 'tcGrn', 'tcWet', 'TMin', 'TMed', 'TMax', 'TreeCover']
pnames = ['Biomass', 'Soil cover', 'Vegetation cover', 'Impervious cover', 'Radar-HH',
'Radar-HV','Tassled cap brightness', 'Tassled cap greenness',
'Tassled cap wetness', 'Min. annual temp', 'Median annual temp',
'Max. annual temp', 'Tree cover']
xunit = ['Mg C/ha', '%', '%', '%', 'dB', 'dB', 'unitless',
'unitless', 'unitless', 'C', 'C', 'C', '%']
# loop through each covariate and plot background vs field plots
for i in range(len(names)):
print('[ STATUS ]: Plotting {} data'.format(names[i]))
# read the full raster data into memory
tref = gdal.Open(rasters[i])
bref = tref.GetRasterBand(bands[i]+1)
ndval = bref.GetNoDataValue()
band = bref.ReadAsArray()
gd = band != ndval
bkgr = band[gd]
# clear memory
band = None
bref = None
tref = None
# to speed things up a bit, sample just 1 mil. background points
n_rnd = int(1e6)
rnd = np.random.choice(len(bkgr), n_rnd, replace=False)
bkgr = bkgr[rnd]
# subset the data from the field plots
plts = np.array(sp[names[i]])
# create the plot device
plt.figure(figsize=(5,5), dpi=150)
# set the colors to use
colors = aei.color.color_blind()
dns = aei.plot.density_dist([bkgr, plts], plot=plt,
label=['Background', 'Plots'],
color=[colors[0], colors[5]],
title='{}'.format(pnames[i]),
xlabel = '({})'.format(xunit[i]),
ylabel = '', fill_alpha = 0.4)
# prep to save the figure
dns.tight_layout()
dns.savefig(plots + '{}-density-dist.png'.format(names[i]))
dns.close()
| true |