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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
03f336e88de9827c151834ff81d413dc0d85dc38 | Python | sindish/unitedwelearn | /object_detection/detectron2/experiments/examples/plot.py | UTF-8 | 896 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | import matplotlib.pyplot as plt
from PIL import Image
fig, axes = plt.subplots(2, 2)
axes[0,0].imshow(Image.open('concat1_part1.png'), aspect = 'equal')
axes[0,1].imshow(Image.open('concat1_part2.png'), aspect = 'equal')
# axes[0,2].imshow(Image.open('concat1_part3.png'), aspect='auto')
# axes[1,0].imshow(Image.open('concat2_part1.png'), aspect ='equal')
# axes[1,1].imshow(Image.open('concat2_part2.png'), aspect = 'equal')
# axes[1,2].imshow(Image.open('concat2_part3.png'), aspect='auto')
axes[1,0].imshow(Image.open('concat3_part1.png'), aspect='equal')
axes[1,1].imshow(Image.open('concat3_part2.png'), aspect='equal')
# axes[2,2].imshow(Image.open('concat3_part3.png'))
for i in range(2):
for j in range(2):
axes[i,j].set_axis_off()
plt.axis('off')
plt.subplots_adjust(wspace=0.0, hspace=0.0)
fig.tight_layout()
plt.savefig('figure1_2.png', bbox_inches='tight', dpi=300)
| true |
245d70bb8d162aeec36013c4e1821c52b8241b40 | Python | syamilisn/Python-Files-Repo | /SmartWork/MinCostSpanTree.py | UTF-8 | 2,019 | 3.203125 | 3 | [] | no_license | #Minimum Cost Spanning Tree
"""
Created on Sun May 17 06:03:34 2020
@author: shyam
"""
#weighted graph:4x4
wtgraph=[[0,20,0,90],[2,0,100,10],[0,100,0,40],[90,10,40,0]]
#Display wtgraph
for row in range(4):
for col in range(4):
print(wtgraph[row][col],end=" ")
print(" ")
#start=input("Enter the starting vertex:")
#vxt=[start]
vx=[1,2,3,4]
vxt=[1,2]
ed=[None]
edt=[None]
v=len(vx)
#list of all possible edges
for i in range(4):
for j in range(4):
ed=[vx[i],vx[j]]
print(ed,end=" ")
#original vx set, tree vertex set
def remainvx(vx,vxt):
for i in range(len(vxt)):
for j in range(len(vx)):
if vxt[i]==vx[j]:
vx.remove(vx[j])
return vx
#pass search_element, array_list_to_be_searched
def ifpresent(n,list):
for item in list:
if n==item:
return True
else:
return False
#pass an edge
def edwt(ed):
row=ed[0][0]
col=ed[0][1]
return wtgraph[row][col]
#pass edge set
def minwtedge(ed,vx,vxt):
minedge=[None]
minedge=ed[0]
for i in range(len(vxt)):
for j in range(len(vx)):
currentedge=ed[i] #change later
if ifpresent(i,vxt) and ifpresent(j,vx):#if vx present in tree_vx and orig_vx
if(edwt(minedge)>edwt(currentedge)):
minedge=currentedge
#vxt=vxt.append(minedge[0])
vxt=vxt.append(vx[j])
vx=remainvx(vx,vxt)
return minedge
#actual s*it starts here lmao
for i in range(v):
minwted=minwtedge(ed,vx,vxt)
""" vxt=vxt.append(minwted[0][1])
edt=edt.append(minwted)
"""
"""for i in range(v):
minwt(vxt,vxo)"""
"""
#to find minimum edge
def minwtedge(ed):
minedge=ed[0]
for i in range(len(ed)):
if(minedge>ed[i]):
minedge=ed[i]
return minedge
"""
| true |
d6cc27750039b98130af8787c3b138df7b883ab1 | Python | tausifzmn/worm-game | /worm game.py | UTF-8 | 3,978 | 3.390625 | 3 | [] | no_license | # making the game window
import pygame
import time
import random
pygame.init() # Initializes all of the imported Pygame modules
# colors
grass = (147, 194, 198)
pink = (253, 177, 150)
yellow = (251, 231, 163)
red = (255, 0, 0)
milk = (255, 253, 246)
# Takes a tuple or a list as its parameter to create a surface
dispW = 600
dispH = 400
disp = pygame.display.set_mode((dispW, dispH))
pygame.display.set_caption("Emo the Worm by Tofu")
clock = pygame.time.Clock()
worm_size = 10
wormSpeed = 10
font_style = pygame.font.SysFont("bahnschrift", 20, False, True)
score_font = pygame.font.SysFont("bahnschrift", 14, False, True)
def disp_score(score):
value = score_font.render(
"Your glizzy is " + str(score) + " inches long!", True, milk)
disp.blit(value, [0, 0])
def emo_worm(worm_size, worm_list):
for x in worm_list:
pygame.draw.circle(disp, pink, [x[0], x[1]], worm_size, 7)
def message(msg, color):
mesg = font_style.render(msg, True, color)
disp.blit(mesg, [dispW/5.2, dispH/2.2])
def gameLoop(): # the whole game function
game_over = False
game_close = False
x = dispW / 2
y = dispH / 2
x_move = 0
y_move = 0
worm_list = []
len_worm = 1
x_food = round(random.randrange(0, dispW - worm_size) / 10.0) * 10.0
y_food = round(random.randrange(0, dispH - worm_size) / 10.0) * 10.0
while not game_over:
while game_close == True:
disp.fill(grass)
message("You're bad Kid! Press Q (Quit) or R (Restart)", milk)
disp_score(len_worm - 1)
pygame.display.update()
for event in pygame.event.get(): # key event to check if you want to quit or restart game
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q: # q to quit
game_over = True
game_close = False
if event.key == pygame.K_r: # r to restart
gameLoop()
for event in pygame.event.get(): # print out all the action that takes place on screen
if event.type == pygame.QUIT: # when click 'X' the screen should close
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_move = -worm_size
y_move = 0
if event.key == pygame.K_RIGHT:
x_move = worm_size
y_move = 0
if event.key == pygame.K_UP:
x_move = 0
y_move = -worm_size
if event.key == pygame.K_DOWN:
x_move = 0
y_move = worm_size
# this is the condition that checks if the worm touches the border then the game ends
if x >= dispW or x < 0 or y >= dispH or y < 0:
game_close = True
x += x_move
y += y_move
disp.fill(grass)
pygame.draw.circle(disp, yellow, [x_food, y_food], worm_size)
worm_Head = []
worm_Head.append(x)
worm_Head.append(y)
worm_list.append(worm_Head)
if len(worm_list) > len_worm:
del worm_list[0]
for i in worm_list[:-1]:
if i == worm_Head:
game_close = True
emo_worm(worm_size, worm_list)
disp_score(len_worm - 1)
pygame.display.update() # updates changes on the screen
if x == x_food and y == y_food:
x_food = round(random.randrange(
0, dispW - worm_size) / 10.0) * 10.0
y_food = round(random.randrange(
0, dispH - worm_size) / 10.0) * 10.0
len_worm += 1
clock.tick(wormSpeed)
pygame.quit() # closes everything
quit()
gameLoop()
| true |
42deb932554bdc01a0ebdfa6244891dce48e87ea | Python | LucaKaufmann/Home-AssistantConfig | /scripts/build_maps.py | UTF-8 | 4,233 | 2.609375 | 3 | [
"MIT"
] | permissive | """
#!/usr/bin/env python3
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Released by: Asphalter
Thanks to DustCloud project: https://raw.githubusercontent.com/dgiese/dustcloud
Thanks to CodeKing: https://github.com/dgiese/dustcloud/issues/22#issuecomment-367618008
"""
import argparse
import io
from PIL import Image, ImageFile, ImageDraw, ImageChops
ImageFile.LOAD_TRUNCATED_IMAGES = True
def build_map(slam_log_data, map_image_data):
map_image = Image.open(io.BytesIO(map_image_data))
map_image = map_image.convert('RGBA')
map_image = map_image.resize((map_image.size[0]*3, map_image.size[1]*3))
# calculate center of the image
center_x = map_image.size[0] / 2
center_y = map_image.size[0] / 2
map_image = map_image.rotate(-90)
color_move = (238, 247, 255, 255)
color_dot = (164, 0, 0, 255)
color_ext_background = (82, 81, 82, 255)
color_home_background = (35, 120, 198, 255)
color_wall = (105, 208, 253, 255)
color_white = (255, 255, 255, 255)
color_grey = (125, 125, 125, 255)
color_black = (0, 0, 0, 255)
color_transparent = (0, 0, 0, 0)
# prepare for drawing
draw = ImageDraw.Draw(map_image, 'RGBA')
# loop each line of slam log
prev_pos = None
for line in slam_log_data.split("\n"):
# find positions
if 'estimate' in line:
d = line.split('estimate')[1].strip()
# extract x & y
y, x, z = map(float, d.split(' '))
# set x & y by center of the image
x = center_x + (x * 60)
y = center_y + (y * 60)
pos = (x, y)
if prev_pos:
draw.line([prev_pos, pos], color_move, 1)
prev_pos = pos
# draw current position
def ellipsebb(x, y):
return x-5, y-5, x+5, y+5
draw.ellipse(ellipsebb(x, y), color_dot)
map_image = map_image.rotate(90)
# crop image
bgcolor_image = Image.new('RGBA', map_image.size, color_grey)
cropbox = ImageChops.subtract(map_image, bgcolor_image).getbbox()
map_image = map_image.crop(cropbox)
# and replace background with transparent pixels
pixdata = map_image.load()
for y in range(map_image.size[1]):
for x in range(map_image.size[0]):
# Image Background
if pixdata[x, y] == color_grey:
pixdata[x, y] = color_transparent
# Home floor
elif pixdata[x, y] == color_white:
pixdata[x, y] = color_home_background
# Home wall
elif pixdata[x, y] == color_black:
pixdata[x, y] = color_wall
# Hide everything else (if you want sensors to be hidden uncomment this)
#elif pixdata[x, y] not in [color_move, color_dot]:
# pixdata[x, y] = color_home_background
temp = io.BytesIO()
map_image.save(temp, format="png")
return temp
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="""
Process the runtime logs of the vacuum (SLAM_fprintf.log, navmap*.ppm from /var/run/shm)
and draw the path into the map. Outputs the map as a PNG image.
""")
parser.add_argument(
"-slam",
default="SLAM_fprintf.log",
required=False)
parser.add_argument(
"-map",
required=True)
parser.add_argument(
"-out",
required=False)
args = parser.parse_args()
with open(args.slam) as slam_log:
with open(args.map, 'rb') as mapfile:
augmented_map = build_map(slam_log.read(), mapfile.read(), )
out_path = args.out
if not out_path:
out_path = args.map[:-4] + ".png"
if not out_path.endswith(".png"):
out_path += ".png"
with open(out_path, 'wb') as out:
out.write(augmented_map.getvalue())
| true |
e49ce47a0b0a1fbfa366aa04b9c140c9bafc4554 | Python | Linus-MK/AtCoder | /AHC/ahc001_testcase.py | UTF-8 | 1,124 | 3.03125 | 3 | [] | no_license | import random
n = round(50 * 4 ** random.random())
print(f'n={n}')
# x, y
coords_list = []
xs = []
ys = []
for i in range(n):
x = random.randrange(10000)
y = random.randrange(10000)
assert (x, y) not in coords_list
coords_list.append((x, y))
xs.append(x)
ys.append(y)
# r
limit = 10**8
r = random.sample(range(1, limit), n-1)
r = [0] + sorted(r) + [limit]
# print(r)
import matplotlib
import matplotlib.pyplot as plt
import math
plt.style.use('ggplot')
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(xs,ys)
ax.set_xlabel('x')
ax.set_ylabel('y')
for i in range(n):
xi = xs[i]
yi = ys[i]
area = r[i+1] - r[i]
x_width = math.sqrt(area) * random.uniform(0.8, 1.25)
y_width = area / x_width
x_width = 200
y_width = 200
rect1 = matplotlib.patches.Rectangle((xi-x_width//2, yi-y_width//2),
x_width, y_width,
edgecolor='black', fill=False)
ax.add_patch(rect1)
ax.set_aspect('equal')
fig.show()
plt.savefig('hoge.png')
import numpy as np
print(np.min(np.diff(r))) | true |
a8df6d3d16477340e3a1f98aab9277ce14cac403 | Python | jcontrerasroberto/AES | /Python/aes.py | UTF-8 | 6,056 | 3.359375 | 3 | [] | no_license | from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
import base64
'''
FUNCTION DECLARATION
1) keyGenerator: Generate a valid DES3 24 bytes key using EDE
Output: A valid DES3 24 bytes key
2) saveKey: Save the key generated in a file in base 64
Input: Name of the file and the key
3) saveText: Save the encipher text in the file in base 64 with the extension .des
Input: Name of the file and the encrypted message
4) readMessage: Reads the text file
Input: Name of the file with the text
Output: The text of the file
5) readText_base64: Read the text from a file in base 64 and decodes it
Input: The name of the file to read
Output: The text read
6) read_ivText:
7) writeDecipherText: Write the decipher text in the file
Input: The name of the file to write and the decipher text
'''
def keyGenerator(n):
#Generate a valid AES 128, 192 or 256 bits key
key = get_random_bytes(n)
return key
def saveKey (keyFile, key):
with open(keyFile , 'w') as f:
base64TextKey=base64.b64encode(key)
f.write(str(base64TextKey, "utf-8"))
def readMessage(textFile):
with open(textFile ,'r', encoding="utf-8" ) as r:
plaintext=r.read()
plaintext_as_bytes = str.encode(plaintext)
return plaintext_as_bytes
def saveText (textFile, iv, encrypted_message):
# Save the encipher text in the file
with open(textFile, 'w') as f:
if iv != "":
base64Text = base64.b64encode(iv)
f.write(str(base64Text, "utf-8"))
base64Text=base64.b64encode(encrypted_message)
f.write(str(base64Text, "utf-8"))
def readText_base64(keyFileDecipher):
with open(keyFileDecipher, mode="r") as base64_file:
data = base64.b64decode(bytes(base64_file.readline(), "utf-8"))
return data
def read_ivText(fileText, mode):
with open(fileText, mode="r") as base64_file:
if mode == "CTR":
iv = base64.b64decode(bytes(base64_file.readline(12), "utf-8"))#12 CTR MODE
else:
iv = base64.b64decode(bytes(base64_file.readline(24), "utf-8"))
data = base64.b64decode(bytes(base64_file.readline(), "utf-8"))
return iv,data
def writeDecipherText(textName: str, decriptedText: bytes):
with open(textName, mode="w", encoding="utf-8") as wfile:
wfile.write(str(decriptedText,"utf-8"))
'''
MAIN PART
Input: the option to encrypt or decrypt a text
the option to choose the operation mode to decrypt
Output: Files with the key in base64, encrypted text in the diferent operation modes
in base64 and after the decryption a text generates a file with the original text.
'''
option=input("Select one option: \n1. Encryption \n2. Decryption\n")
if option == '1':
plaintext_File=input("Write the name of the file with the plaintext with te extension, for example: plaintext.txt\n")
plaintext=readMessage(plaintext_File)
key_128 = b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
key_192= b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17'
key_256 = b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'
#print(f"Bytes del 128: {len(key_128)}")
#print(f"Bytes del 192: {len(key_192)}")
#print(f"Bytes del 256: {len(key_256)}")
#Cipher modes
cipher_CBC = AES.new(key_128, AES.MODE_CBC)
cipher_CTR = AES.new(key_192, AES.MODE_CTR)
cipher_CFB = AES.new(key_256, AES.MODE_CFB)
#Nonce creator
nonce = cipher_CTR.nonce
#Encryption part
#CBC
ciphered_data_CBC = cipher_CBC.encrypt(pad(plaintext, AES.block_size))
print(f"Texto cifrado: {str(ciphered_data_CBC)}")
saveText("encryptedCBC.txt", cipher_CBC.iv, ciphered_data_CBC)
saveKey("CBCKey.txt",key_128)
#CTR
ciphered_data_CTR = cipher_CTR.encrypt(plaintext)
saveText("encryptedCTR.txt",nonce, ciphered_data_CTR)#CTR dont have iv :cipher_CTR.iv
saveKey("CTRKey.txt",key_192)
#CFB
ciphered_data_CFB = cipher_CFB.encrypt(plaintext)
saveText("encryptedCFB.txt", cipher_CFB.iv, ciphered_data_CFB)
saveKey("CFBKey.txt",key_256)
else:
optionD=input("Select an option:\n1. CBC Mode\n2.CTR Mode\n3.CFB Mode\n")
if (optionD == '1'):
encipherFileCBC=input("Write the name of the file with the CBC cipher text with extension:\n")
keyFile=input("Write the name of the file with the key of 128 bits with extension\n")
#Read the files
key = readText_base64(keyFile)
iv, ciphertext= read_ivText(encipherFileCBC,"CBC")
cipher = AES.new(key, AES.MODE_CBC, iv=iv) # Setup cipher
original_data = unpad(cipher.decrypt(ciphertext), AES.block_size)
writeDecipherText("originalCBC.txt", original_data)
print(f"Proceso Terminado")
elif (optionD == '2'):
encipherFileCTR=input("Write the name of the file with the CTR cipher text with extension:\n")
keyFile=input("Write the name of the file with the key of 192 bits with extension\n")
#Read the files
key = readText_base64(keyFile)
nonce, ciphertext= read_ivText(encipherFileCTR,"CTR")
cipher = AES.new(key, AES.MODE_CTR, nonce = nonce) # Setup cipher
original_data = cipher.decrypt(ciphertext)
writeDecipherText("originalCTR.txt", original_data)
print(f"Proceso Terminado")
elif (optionD == '3'):
encipherFileCFB=input("Write the name of the file with the CFB cipher text with extension:\n")
keyFile=input("Write the name of the file with the key of 256 bits with extension\n")
#Read the files
key = readText_base64(keyFile)
iv, ciphertext= read_ivText(encipherFileCFB,"CFB")
cipher = AES.new(key, AES.MODE_CFB, iv=iv) # Setup cipher
original_data = cipher.decrypt(ciphertext)
writeDecipherText("originalCFB.txt", original_data)
print(f"Proceso Terminado") | true |
27f27e96abcc39147b014c24a79921b88985a18b | Python | hckhilliam/programming | /LeetCode/1395.py | UTF-8 | 852 | 3.375 | 3 | [] | no_license | import numpy as np
class Solution(object):
def numTeams(self, rating):
# d[i][j] = max possibilities if this is the jth number
# d[i][2] = sum(d[j][1] for j in 0..i-1 if rating[j] < rating[i])
# d[i][1] = sum[d[j][0] for j in 0..i-1 if rating[j] < rating[i])
# d[i][0] = 1
# return sum(d[i][2])
l = len(rating)
dg = np.zeros((l, 3), dtype=int)
dl = np.zeros((l, 3), dtype=int)
for i in range(l):
dg[i][0] = 1
dl[i][0] = 1
for j in range(i):
if rating[j] < rating[i]:
dg[i][1] += dg[j][0]
dg[i][2] += dg[j][1]
elif rating[j] > rating[i]:
dl[i][1] += dl[j][0]
dl[i][2] += dl[j][1]
return sum(dg[:, 2]) + sum(dl[:, 2])
print(Solution().numTeams([1, 2, 3, 4])) | true |
e27588a492bedf383e4da59ce78a000458652a0a | Python | defcxz/2020_prog.algoritmos | /03-07_funciones/ArreglosFunciones.py | UTF-8 | 3,001 | 4.1875 | 4 | [] | no_license | import os #para limpiar pantalla
def llenar(arreglo, n):
sw=True
while(sw==True):
try:
n=int(input("Cuantos numeros desea ingresar? "))
if(n>0):
sw=False
else:
print("Debe ingresar una cantidad positiva")
except ValueError:
print("Debe ingresar un numero entero")
for i in range(n):
sw=True
while(sw==True):
try:
num=int(input("Ingrese un numero "))
sw=False
except ValueError:
print("Debe ingresar un numero entero")
arreglo.append(num)
def mostrar(arreglo, sw1):
if(sw1==1):
print(arreglo)
else:
print("Debe llenar el arreglo antes de mostrarlo ")
def elepares(arreglo, sw1):
if(sw1==1):
for i in range(len(arreglo)):
if(arreglo[i] % 2 == 0):
print(arreglo[i]) #muestro el arreglo
else:
print("Debe llenar el arreglo antes de mostrarlo ")
def posimpar(arreglo, sw1):
if(sw1==1):
for i in range(len(arreglo)):
if(not arreglo.index(i) % 2 == 0):
print(arreglo[i]) #muestro el arreglo
else:
print("Debe llenar el arreglo antes de mostrarlo ")
def segundo(arreglo, sw1):
if(sw1==1):
for i in range(len(arreglo)):
if(arreglo[i] % 5 == 0):
secarreglo.append(arreglo[i]) #muestro el arreglo
print("El segundo arreglo quedaría tal que así:",secarreglo)
else:
print("Debe llenar el arreglo antes de mostrarlo ")
#programa principal
seguir=True
arreglo=[]
secarreglo=[]
sw1=0
while(seguir):
os.system('cls')
print("---- MENU PRINCIPAL ----")
print("1. Llenar arreglo")
print("2. Mostrar Arreglo")
print("3. Mostrar todos los elementos pares del arreglo llenado")
print("4. Mostrar todos los elementos en posicion impar del arreglo")
print("5. Dejar en un segundo arreglo todos los elementos que sean divisibles por 5, mostrar ese arreglo")
print("6. Salir del menu")
correcto=False
n=0
while(not correcto):
try:
op=int(input("Digite opción 1,2,3,4,5 o 6: "))
if(op>0 and op<7):
correcto=True
except ValueError:
print('Error, debe ingresar 1,2,3,4,5 o 6')
if(op == 1):
sw1=1 #cambio el sw1 a uno
llenar(arreglo, n) #llamada a función - def.
elif(op == 2):
mostrar(arreglo,sw1)
pausa=input("Presione enter para continuar")
elif(op == 3):
elepares(arreglo, sw1)
pausa=input("Presione enter para continuar")
elif(op == 4):
posimpar(arreglo,sw1)
pausa = input("Presione enter para continuar")
elif(op == 5):
segundo(arreglo,sw1)
pausa = input("Presione enter para continuar")
if(op==6):
print("Gracias, nos vemos pronto!")
seguir=False | true |
f8c2387a2973a665aaf61f4585ce7c884f5486f6 | Python | wesrer/Algo_trading | /simple_btc_trader.py | UTF-8 | 2,065 | 2.953125 | 3 | [
"MIT"
] | permissive | import robin_stocks as r
import json
import time
import getpass as gp
from timeloop import Timeloop
from datetime import timedelta as td
username = input('Your Robinhood email: ')
passw = gp.getpass('Your pass: ')
login = r.login(username, passw)
# global flags to fulfill orders
sold = False
last_order_id = ""
tl = Timeloop()
SELL_PRICE = float(input('Your BTC target sell price: ') or '38700.00')
BUY_PRICE = float(input ('Your BTC target buy price: ') or '38100.00')
print("looking to buy at ", BUY_PRICE, " and sell at ", SELL_PRICE)
def get_btc_price_robin():
btc_price = r.crypto.get_crypto_quote('BTC')['mark_price']
return round(float(btc_price), 8)
def sell_btc():
owned_bitcoin = get_owned_bitcoin()
order = r.orders.order_sell_crypto_by_quantity('BTC', owned_bitcoin, priceType = 'mark_price')
return order['id']
def check_order_status(order_id):
data = r.orders.get_crypto_order_info(order_id)
return data['state']
def buy_btc():
buying_power = r.profiles.load_account_profile('portfolio_cash')
buying_power = float(buying_power) - 20.00 # leeway for transaction fees
order = r.orders.order_buy_crypto_by_price('BTC', buying_power, priceType = 'mark_price')
return order['id']
def get_owned_bitcoin():
owned = r.crypto.get_crypto_positions()
for x in owned:
if x['currency']['code'] == 'BTC':
return round(float(x['quantity']),8)
# If you don't own BTC, then return 0
return 0
@tl.job(interval=td(seconds=1))
def trade_btc():
global sold
global last_order_id
btc = get_btc_price_robin()
print("current btc price:", btc)
if last_order_id != "" and check_order_status(last_order_id) != "filled":
return
if (btc > SELL_PRICE) and not(sold):
last_order_id = sell_btc()
sold = True
print("sold bitcoin at: ", btc)
if sold and btc < BUY_PRICE:
last_order_id = buy_btc()
sold = False
print("bought bitcoin at: ", btc)
if __name__ == "__main__":
tl.start(block=True)
| true |
4870b61a905d9ac6ce553dad416999407cea7964 | Python | Mamoth112/SML-Cogs-v3 | /dstats/utils.py | UTF-8 | 419 | 2.921875 | 3 | [
"MIT"
] | permissive | def get_emoji(bot, name, remove_dash=True):
"""Return emoji by name
name is used by this cog.
key is values returned by the api.
Use key only if name is not set
"""
if remove_dash:
name = name.replace('-', '')
for guild in bot.guilds:
for emoji in guild.emojis:
if emoji.name == name:
return f'<:{emoji.name}:{emoji.id}>'
return f':{name}:' | true |
27c1bf9c12ffca16b6d367559a0c18986a28114b | Python | mahathu/bachelorarbeit | /skripte/surface_3d.py | UTF-8 | 924 | 2.84375 | 3 | [] | no_license | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.view_init(30,120)
e = np.e
r = 1
step = .025
stept = .5
X = np.arange(-r, r, step)
Y = np.arange(-r, r, step)
X, Y = np.meshgrid(X, Y)
# Z = (X**2 - Y**2)/5 #\frac{X^2 - Y^2}{5} (pringle)
# Z = -(2*X*e**(-(X**2+Y**2)/5))/5 # Ableitung von: np.e**(-1*(X**2+Y**2)/5) (gauss)
# Z = (20 - Y)**(5/4) + 10*(X - Y**2)**2
Z = X**2 + Y**2
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0.2, antialiased=True)
# plt.xticks(np.arange(-r/2, r*1.5, stept))
# plt.yticks(np.arange(-r, r, stept))
plt.xlabel('m')
plt.ylabel('t')
ax.tick_params(labelbottom=False, labelleft=False)
# plt.show()
plt.savefig('3d.png', bbox_inches='tight', dpi=300) | true |
27bcff7d24f14a8818cc5a504d6d9e4b88d7ca4b | Python | biolearning-stadius/rdkit | /rdkit/utils/chemutils.py | UTF-8 | 4,896 | 2.828125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #
# Copyright (C) 2000 greg Landrum
#
""" utility functions with "chemical know-how"
"""
import os
import re
from rdkit import RDConfig
if not RDConfig.usePgSQL:
_atomDbName = os.path.join(RDConfig.RDDataDir, 'atomdb.gdb')
else:
_atomDbName = "::RDData"
def GetAtomicData(atomDict, descriptorsDesired, dBase=_atomDbName, table='atomic_data', where='',
user='sysdba', password='masterkey', includeElCounts=0):
""" pulls atomic data from a database
**Arguments**
- atomDict: the dictionary to populate
- descriptorsDesired: the descriptors to pull for each atom
- dBase: the DB to use
- table: the DB table to use
- where: the SQL where clause
- user: the user name to use with the DB
- password: the password to use with the DB
- includeElCounts: if nonzero, valence electron count fields are added to
the _atomDict_
"""
extraFields = ['NVAL', 'NVAL_NO_FULL_F', 'NVAL_NO_FULL_D', 'NVAL_NO_FULL']
from rdkit.Dbase import DbModule
cn = DbModule.connect(dBase, user, password)
c = cn.cursor()
descriptorsDesired = [s.upper() for s in descriptorsDesired]
if 'NAME' not in descriptorsDesired:
descriptorsDesired.append('NAME')
if includeElCounts and 'CONFIG' not in descriptorsDesired:
descriptorsDesired.append('CONFIG')
for field in extraFields:
if field in descriptorsDesired:
descriptorsDesired.remove(field)
toPull = ','.join(descriptorsDesired)
command = 'select %s from atomic_data %s' % (toPull, where)
try:
c.execute(command)
except Exception:
print('Problems executing command:', command)
return
res = c.fetchall()
for atom in res:
tDict = {}
for i in range(len(descriptorsDesired)):
desc = descriptorsDesired[i]
val = atom[i]
tDict[desc] = val
name = tDict['NAME']
atomDict[name] = tDict
if includeElCounts:
config = atomDict[name]['CONFIG']
atomDict[name]['NVAL'] = ConfigToNumElectrons(config)
atomDict[name]['NVAL_NO_FULL_F'] = ConfigToNumElectrons(config, ignoreFullF=1)
atomDict[name]['NVAL_NO_FULL_D'] = ConfigToNumElectrons(config, ignoreFullD=1)
atomDict[name]['NVAL_NO_FULL'] = ConfigToNumElectrons(
config, ignoreFullF=1, ignoreFullD=1)
def SplitComposition(compStr):
""" Takes a simple chemical composition and turns into a list of element,# pairs.
i.e. 'Fe3Al' -> [('Fe',3),('Al',1)]
**Arguments**
- compStr: the composition string to be processed
**Returns**
- the *composVect* corresponding to _compStr_
**Note**
-this isn't smart enough by half to deal with anything even
remotely subtle, so be gentle.
"""
target = r'([A-Z][a-z]?)([0-9\.]*)'
theExpr = re.compile(target)
matches = theExpr.findall(compStr)
res = []
for match in matches:
if len(match[1]) > 0:
res.append((match[0], float(match[1])))
else:
res.append((match[0], 1))
return res
def ConfigToNumElectrons(config, ignoreFullD=0, ignoreFullF=0):
""" counts the number of electrons appearing in a configuration string
**Arguments**
- config: the configuration string (e.g. '2s^2 2p^4')
- ignoreFullD: toggles not counting full d shells
- ignoreFullF: toggles not counting full f shells
**Returns**
the number of valence electrons
"""
arr = config.split(' ')
nEl = 0
for i in range(1, len(arr)):
l = arr[i].split('^')
incr = int(l[1])
if ignoreFullF and incr == 14 and l[0].find('f') != -1 and len(arr) > 2:
incr = 0
if ignoreFullD and incr == 10 and l[0].find('d') != -1 and len(arr) > 2:
incr = 0
nEl = nEl + incr
return nEl
if __name__ == '__main__': # pragma: nocover
print(SplitComposition('Fe'))
print(SplitComposition('Fe3Al'))
print(SplitComposition('Fe99PdAl'))
print(SplitComposition('TiNiSiSO12P'))
temp = ['[Xe] 4f^12 6s^2', '[Xe] 4f^14 5d^6 6s^2', '[Xe] 4f^14 5d^10 6s^2',
'[Xe] 4f^14 5d^10 6s^2 6p^1', '[Xe] 5d^10']
print('ignore all')
for entry in temp:
print(entry, '\t\t\t\t', ConfigToNumElectrons(entry, ignoreFullD=1, ignoreFullF=1))
print('ignore d')
for entry in temp:
print(entry, '\t\t\t\t', ConfigToNumElectrons(entry, ignoreFullD=1, ignoreFullF=0))
print('ignore f')
for entry in temp:
print(entry, '\t\t\t\t', ConfigToNumElectrons(entry, ignoreFullD=0, ignoreFullF=1))
print('ignore None')
for entry in temp:
print(entry, '\t\t\t\t', ConfigToNumElectrons(entry, ignoreFullD=0, ignoreFullF=0))
| true |
8b0296411c9df758b0350c21f9b7f5c403e7b004 | Python | shu-xiao/alicptfts | /alicptfts/sftpwrapper.py | UTF-8 | 2,371 | 2.859375 | 3 | [
"BSD-2-Clause"
] | permissive | # Adapted from Mathew Newville's code
# https://github.com/pyepics/newportxps/blob/master/newportxps/ftp_wrapper.py
import pysftp
from io import BytesIO
class SFTPWrapper():
def __init__(self):
self.host = None
self.username = None
self.password = None
self._conn = None
def connect(self, host=None, username=None, password=None):
self.host = host
self.username = username
self.password = password
try:
self._conn = pysftp.Connection(host=self.host,
username=self.username,
password=self.username)
except:
print('SFTP Error: SFTP connection to {0} failed'.format(self.host))
print('May need to add the host keys for the XPS to the')
print('ssh known_hosts file, using a command like this:')
print(' ssh-keyscan {0} >> ~/.ssh/known_hosts'.format(self.host))
raise
def close(self):
if self._conn is not None:
self._conn.close()
self._conn = None
def cwd(self, remotedir):
try:
self._conn.cwd(remotedir)
except IOError:
print('Error: Could not find path')
raise
def save(self, remotefile, localfile):
"Save a remote file to a local file"
try:
self._conn.get(remotepath=remotefile, localpath=localfile)
except IOError:
print('Error: Could not save file')
raise
def put(self, localfile, remotefile):
try:
self._conn.put(localpath=localfile, remotepath=remotefile)
except IOError:
print('SFTP Error: Remote path does not exist')
raise
except OSError:
print('SFTP Error: Local file does not exist')
raise
else:
return True
def getlines(self, remotefile):
"Read text of a remote file"
tmp = BytesIO()
try:
self._conn.getfo(remotefile, tmp)
except:
print('SFTP Error: Could not read remotefile')
raise
else:
tmp.seek(0)
text = bytes2str(tmp.read())
return(text.split('\n'))
def bytes2str(s):
FTP_ENCODING = 'latin-1'
return str(s, FTP_ENCODING)
| true |
d753f01c5e8739b0e9a6fb08cbf408dbecfbcda5 | Python | SirJan18/Youtube-Song-Downloader | /download.py | UTF-8 | 1,304 | 2.671875 | 3 | [] | no_license | # Include Libarires
# from pytube import YouTube
import pafy
import sys
import re
import os
import helpers
def downloadSong(link):
try:
yt = pafy.new(link)
print("Downloading: " + yt.title)
yt.getbestaudio().download(filepath='video', quiet=False)
ext = yt.getbestaudio().extension
helpers.convertVideo(yt.title, ext)
print("Done!\n")
except OSError:
print('Video not found!')
def figure(input):
if 'www.youtube.com/' in input:
# Determine if playlist or video
if 'playlist' in input:
# playlist
helpers.PlaylistSort(input)
else:
# not playlist
downloadSong(input)
else:
with open(input, 'r') as file:
for item in file:
figure(item)
if len(sys.argv) < 2:
print("You need to provide a link or file")
exit()
else:
if os.path.exists('./misc') == False:
os.mkdir('./misc')
if os.path.exists('./audio') == False:
os.mkdir('./audio')
if os.path.exists('./video') == False:
os.mkdir('./video')
try:
figure(sys.argv[1])
except KeyboardInterrupt:
print('\nUser Aborted Operation')
print('Cleaning Up...')
#Begin Cleanup Process | true |
7e46335ff1efdfb88b071761b1f7372381bdf5fb | Python | HaGriD1993/Obiektowe-II | /Kowal.py | UTF-8 | 12,417 | 3.34375 | 3 | [] | no_license | import random
import time
import Bohater
import Przedmiot
class Kowal:
def __init__(self):
self.imie = "Ryszard"
self.wiek = 52
self.specjanosc = "Kowal"
def info(self):
print("\nWitaj nazywam się: " + self.imie, ",jestem", self.specjanosc+"em") #PRZEDSTAWIA SIE
def skladniki(self, mojbohater: Bohater.Bohater):
metale = []
for i in range(1): # DODANIE DO LISTY
metale.append(Przedmiot.ruda_zelaza)
metale.append(Przedmiot.ruda_miedzi)
metale.append(Przedmiot.ruda_brazu)
metale.append(Przedmiot.ruda_niklu)
metale.append(Przedmiot.ruda_zlota)
metale.append(Przedmiot.ruda_srebra)
wybor = input("Za 'bryłke złota' mogę dać ci kilka róznych rud. (T/N): ")
if wybor == str("T"):
if Przedmiot.brylka in mojbohater.plecak: # SPRAWDZA CZY JEST BRYLKA
mojbohater.plecak.remove(Przedmiot.brylka)
print("Otrzymujesz: ")
for i in range(3): # DO PLECAKA DODAJE 3 ELEMENTY Z LISTY
time.sleep(2)
wyb_metale = random.choice(metale)
print(wyb_metale.__str__())
mojbohater.plecak.append(wyb_metale)
else:
print("Nie masz ani jednej 'bryłki złota', wróc do mnie jak bedziesz miał.")
else:
print("Wróc jak zmienisz zdanie.")
def przetapianie(self, mojbohater: Bohater.Bohater):
metale = []
sztabki = []
for i in range(1): # DODANIE DO POSZCZEGOLNYCH LIST
metale.append(Przedmiot.ruda_zelaza)
metale.append(Przedmiot.ruda_miedzi)
metale.append(Przedmiot.ruda_brazu)
metale.append(Przedmiot.ruda_niklu)
metale.append(Przedmiot.ruda_zlota)
metale.append(Przedmiot.ruda_srebra)
sztabki.append(Przedmiot.sz_zelaza)
sztabki.append(Przedmiot.sz_miedzi)
sztabki.append(Przedmiot.sz_brazu)
sztabki.append(Przedmiot.sz_niklu)
sztabki.append(Przedmiot.sz_zlota)
sztabki.append(Przedmiot.sz_srebra)
for metal in metale: # SPRAWDZA ILOSC RUD METALI W PLECAKU
x = mojbohater.plecak.count(metal)
print("ilość:", x, "|", metal.__str__())
for metal in metale:
x = mojbohater.plecak.count(metal)
if x >= 3: # JAK JEST 3 LUB WIECEJ WTEDY USUWA 3 SZT I DAJE JEDNA SZTABKE .
if metal == Przedmiot.ruda_zelaza:
for i in range(3):
mojbohater.plecak.remove(Przedmiot.ruda_zelaza)
mojbohater.plecak.append(Przedmiot.sz_zelaza)
print("Otrzymujesz:", Przedmiot.sz_zelaza.__str__())
if metal == Przedmiot.ruda_miedzi:
for i in range(3):
mojbohater.plecak.remove(Przedmiot.ruda_miedzi)
mojbohater.plecak.append(Przedmiot.sz_miedzi)
print("Otrzymujesz:", Przedmiot.sz_miedzi.__str__())
if metal == Przedmiot.ruda_brazu:
for i in range(3):
mojbohater.plecak.remove(Przedmiot.ruda_brazu)
mojbohater.plecak.append(Przedmiot.sz_brazu)
print("Otrzymujesz:", Przedmiot.sz_brazu.__str__())
if metal == Przedmiot.ruda_niklu:
for i in range(3):
mojbohater.plecak.remove(Przedmiot.ruda_niklu)
mojbohater.plecak.append(Przedmiot.sz_niklu)
print("Otrzymujesz:", Przedmiot.sz_niklu.__str__())
if metal == Przedmiot.ruda_zlota:
for i in range(3):
mojbohater.plecak.remove(Przedmiot.ruda_zlota)
mojbohater.plecak.append(Przedmiot.sz_zlota)
print("Otrzymujesz:", Przedmiot.sz_zlota.__str__())
if metal == Przedmiot.ruda_srebra:
for i in range(3):
mojbohater.plecak.remove(Przedmiot.ruda_srebra)
mojbohater.plecak.append(Przedmiot.sz_srebra)
print("Otrzymujesz:", Przedmiot.sz_srebra.__str__())
def handel(self, mojbohater: Bohater.Bohater):
print("\nZobacz co mam na sprzedaż: ")
print("{} {}".format("1.|", "Miecz: "))
print("{} {}".format("2.|", "Pancerz: "))
print("{} {}".format("3.|", "Tarcza: "))
print("{} {}".format("4.|", "Hełm: "))
print("{} {}".format("5.|", "Pozostałe: "))
miecze = []
pancerz = []
tarcza = []
helm = []
pozostale = []
for i in range(1): # DODAJE PRZEDMIOTY DO KONKRETNYCH LIST.
miecze.append(Przedmiot.miecz_zardzewialy)
miecze.append(Przedmiot.miecz_zwykly)
miecze.append(Przedmiot.miecz_doskonaly)
miecze.append(Przedmiot.miecz_stalowy)
miecze.append(Przedmiot.miecz_zelazny)
pancerz.append(Przedmiot.pancerz_sierzanta)
pancerz.append(Przedmiot.pancerz_straznika)
pancerz.append(Przedmiot.pancerz_oficera)
tarcza.append(Przedmiot.tarcza_drewniana)
tarcza.append(Przedmiot.tarcza_stalowa)
tarcza.append(Przedmiot.tarcza_zelazna)
tarcza.append(Przedmiot.tarcza_rogata)
helm.append(Przedmiot.helm_skorzany)
helm.append(Przedmiot.helm_stalowy)
helm.append(Przedmiot.helm_zelazny)
helm.append(Przedmiot.helm_rogaty)
pozostale.append(Przedmiot.kilof)
pozostale.append(Przedmiot.mlotek)
pozostale.append(Przedmiot.oselka)
wybor = int(input("\nWybierz: ")) # WYBIERAMY KATEGORIE
if wybor == 1:
nr = 0
for rzecz in miecze: # POKAZE PRZEDMIOTY ZACZYNAJAC OD 1.
nr += 1
print("Nr:", str(nr), rzecz, sep=" ")
kupiony = input("\nKtóry chcesz kupić: ")
nr_przedmiotu = int(kupiony)
nr_przedmiotu -= 1
wartosc_przedmiotu = Przedmiot.Zwykly.kupno(miecze[nr_przedmiotu])
if mojbohater.sakwa >= wartosc_przedmiotu: # SPRAWDZA ILOSC MONET W SAKWIE DO CENY PRZEDMIOTU
print("Mam odpowiednią ilość monet.") # JAK NAS STAC TO KUPUJE.
mojbohater.sakwa -= wartosc_przedmiotu
mojbohater.plecak.append(miecze[nr_przedmiotu])
print("Zostało mi:", mojbohater.sakwa)
else:
print("\nMasz za mało pieniedzy.", # JAK NIE STAC TO ZWRACA SAKWE I CENE PRZEDMIOTU
"\nSakwa:", mojbohater.sakwa, "|Cena przedmiotu:", wartosc_przedmiotu)
elif wybor == 2:
nr = 0
for rzecz in pancerz:
nr += 1
print("Nr:", str(nr), rzecz, sep=" ")
kupiony = input("\nKtóry chcesz kupić: ")
nr_przedmiotu = int(kupiony)
nr_przedmiotu -= 1
wartosc_przedmiotu = Przedmiot.Zwykly.kupno(pancerz[nr_przedmiotu])
if mojbohater.sakwa >= wartosc_przedmiotu:
print("Mam odpowiednią ilość monet.")
mojbohater.sakwa -= wartosc_przedmiotu
mojbohater.plecak.append(pancerz[nr_przedmiotu])
print("Zostało mi:", mojbohater.sakwa)
else:
print("\nMasz za mało pieniedzy.",
"\nSakwa:", mojbohater.sakwa, "|Cena przedmiotu:", wartosc_przedmiotu)
elif wybor == 3:
nr = 0
for rzecz in tarcza:
nr += 1
print("Nr:", str(nr), rzecz, sep=" ")
kupiony = input("\nKtóry chcesz kupić: ")
nr_przedmiotu = int(kupiony)
nr_przedmiotu -= 1
wartosc_przedmiotu = Przedmiot.Zwykly.kupno(tarcza[nr_przedmiotu])
if mojbohater.sakwa >= wartosc_przedmiotu:
print("Mam odpowiednią ilość monet.")
mojbohater.sakwa -= wartosc_przedmiotu
mojbohater.plecak.append(tarcza[nr_przedmiotu])
print("Zostało mi:", mojbohater.sakwa)
else:
print("\nMasz za mało pieniedzy.",
"\nSakwa:", mojbohater.sakwa, "|Cena przedmiotu:", wartosc_przedmiotu)
elif wybor == 4:
nr = 0
for rzecz in helm:
nr += 1
print("Nr:", str(nr), rzecz, sep=" ")
kupiony = input("\nKtóry chcesz kupić: ")
nr_przedmiotu = int(kupiony)
nr_przedmiotu -= 1
wartosc_przedmiotu = Przedmiot.Zwykly.kupno(helm[nr_przedmiotu])
if mojbohater.sakwa >= wartosc_przedmiotu:
print("Kupiłeś: ", helm[nr_przedmiotu])
mojbohater.sakwa -= wartosc_przedmiotu
mojbohater.plecak.append(helm[nr_przedmiotu])
print("Zostało mi:", mojbohater.sakwa)
else:
print("\nMasz za mało pieniedzy.",
"\nSakwa:", mojbohater.sakwa, "|Cena przedmiotu:", wartosc_przedmiotu)
elif wybor == 5:
nr = 0
for rzecz in pozostale:
nr += 1
print("Nr:", str(nr), rzecz, sep=" ")
kupiony = input("\nKtóry chcesz kupić: ")
nr_przedmiotu = int(kupiony)
nr_przedmiotu -= 1
wartosc_przedmiotu = Przedmiot.Zwykly.kupno(pozostale[nr_przedmiotu])
if mojbohater.sakwa >= wartosc_przedmiotu:
print("Kupiłeś: ", pozostale[nr_przedmiotu])
mojbohater.sakwa -= wartosc_przedmiotu
mojbohater.plecak.append(pozostale[nr_przedmiotu])
print("Zostało mi:", mojbohater.sakwa)
else:
print("\nMasz za mało pieniedzy.",
"\nSakwa:", mojbohater.sakwa, "|Cena przedmiotu:", wartosc_przedmiotu)
def naprawa(self, mojbohater: Bohater.Bohater): #NAPRAWA EKWIPUNKU
print("\nZa 'bryłke złota' moge naprawić twoj ekwipunek.")
print("Stan pancerza: {}, Stan broni {}".format(mojbohater.stan_pancerz, mojbohater.stan_bron))
wybor = str(input("Czy chcesz dokonać naprawy: (T/N)"))
if wybor == "T":
if Przedmiot.brylka in mojbohater.plecak: #SPRAWDZA CZY JEST BRYŁKA
print("Naprawiam:")
mojbohater.plecak.remove(Przedmiot.brylka) #USUWA BRYŁKE
while mojbohater.stan_pancerz < 5: #NAPRAWIA W PETLI DO WARTOSCI 5.
time.sleep(2)
mojbohater.stan_pancerz += 1
print("+", mojbohater.stan_pancerz)
print("Pancerz: ", mojbohater.stan_pancerz)
while mojbohater.stan_bron < 5:
time.sleep(2)
mojbohater.stan_bron += 1
print("+", mojbohater.stan_bron)
print("Broń: ", mojbohater.stan_bron)
else:
print("Nie masz 'bryłki złota', ilość:", mojbohater.plecak.count(Przedmiot.brylka))
else:
print("Wróć jak zmienisz zdanie.")
def skup(self, mojbohater: Bohater.Bohater):
print("Tutaj możesz sprzedać mi kilka twoich rzeczy: ")
nr = 0
for rzecz in mojbohater.plecak:
nr += 1
print("Nr:", str(nr), rzecz, sep=" ")
sprzedany = input("Wybierz numer przedmiotu: ")
nr_sprzedany = int(sprzedany)
nr_sprzedany -= 1
wartosc_przedmiotu = Przedmiot.Zwykly.sprzedaz(mojbohater.plecak[nr_sprzedany])
print("Chcesz sprzedać za: ", wartosc_przedmiotu)
wybor = input("T/N: ")
if wybor == "T":
mojbohater.plecak.remove(mojbohater.plecak[nr_sprzedany])
mojbohater.sakwa += wartosc_przedmiotu
else:
print("Wróc jak zmienisz zdanie.") | true |
25801d340a5adf33afea32801a176203e594f307 | Python | MathieuR/bioloid_typea_gazebo | /scripts/walker_demo.py | UTF-8 | 756 | 2.53125 | 3 | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | permissive | #!/usr/bin/env python
import rospy
from typea_gazebo.typea import TypeA
if __name__=="__main__":
rospy.init_node("walker_demo")
rospy.loginfo("Instantiating TypeA Client")
typea=TypeA()
rospy.sleep(1)
rospy.loginfo("TypeA Walker Demo Starting")
typea.set_walk_velocity(0.2,0,0)
rospy.sleep(30)
typea.set_walk_velocity(1,0,0)
rospy.sleep(30)
#typea.set_walk_velocity(0,1,0)
#rospy.sleep(3)
#typea.set_walk_velocity(-1,0,0)
#rospy.sleep(3)
#typea.set_walk_velocity(0,-1,0)
#rospy.sleep(3)
#typea.set_walk_velocity(1,1,0)
#rospy.sleep(3)
#typea.set_walk_velocity(-1,-1,0)
#rospy.sleep(3)
typea.set_walk_velocity(0,0,0)
rospy.loginfo("TypeA Walker Demo Finished")
| true |
3afca428e776c15e713b0ca02329d2fb75cff902 | Python | umutbozkurt/backend-challenges | /kvdb/tests.py | UTF-8 | 3,476 | 2.796875 | 3 | [] | no_license | import unittest
import time
from unittest.mock import patch
from dbserver import Server
class ServerTests(unittest.TestCase):
def setUp(self):
self.server = Server()
def test_ping(self):
payload = {
'command': 'PING'
}
response = self.server.handle_message(payload)
self.assertEqual(response['status'], Server.STATUS_OK)
self.assertEqual(response['result'], 'PONG')
def test_process_input(self):
commands = (
'GET',
'SET',
'PING',
'DELETE',
'INCR',
'DECR',
'TTL',
'EXPIRE',
)
for command in commands:
cmd = self.server.process_input(dict(command=command, args=dict()))
self.assertTrue(callable(cmd))
def test_process_args(self):
key = 'key'
value = 'val'
payload = {
'command': 'SET',
'args': {
'key': key,
'value': value
}
}
response = self.server.handle_message(payload)
self.assertEqual(response['status'], Server.STATUS_OK)
self.assertIsNone(response['result'])
out = self.server.get(key)
self.assertEqual(out, value)
def test_set(self):
key = 'KEY'
val = 'VAL'
self.server.set(key, val)
store = self.server._get_store(key)
self.assertEqual(store.value, val)
def test_get(self):
key = 'KEY'
value = 'VAL'
self.server.set(key, value)
out = self.server.get(key)
self.assertEqual(out, value)
def test_delete(self):
key = 'KEY'
self.server.set(key, 'VAL')
self.server.delete(key)
self.assertEqual(self.server.get(key), None)
with self.assertRaises(KeyError):
_ = self.server.data[key]
def test_increment(self):
key = 'KEY'
val = 1000
self.server.set(key, val)
out = self.server.increment(key)
self.assertEqual(out, val + 1)
def test_increment_null(self):
out = self.server.increment('key')
self.assertEqual(out, 1)
def test_decrement(self):
key = 'KEY'
val = 1000
self.server.set(key, val)
out = self.server.decrement(key)
self.assertEqual(out, val - 1)
def test_decrement_null(self):
out = self.server.decrement('key')
self.assertEqual(out, -1)
@patch('dbserver.time')
def test_ttl(self, time):
key = 'KEY'
ttl = 1000
time.time.return_value = 100000
self.server.set(key, 'val', ttl=ttl)
self.server.expire(key, ttl)
time.time.return_value = 100001 # 1 second passed
self.assertLess(self.server.ttl(key), ttl)
@patch('dbserver.time')
def test_expiration(self, time):
key = 'KEY'
ttl = 1
time.time.return_value = 100000
self.server.set(key, 'val', ttl=ttl)
self.server.expire(key, ttl)
time.time.return_value = 100002 # 2 seconds passed
self.assertIsNone(self.server.get(key))
def test_expiry_service(self):
key = 'KEY'
ttl = 1
self.server.set(key, 'val', ttl=ttl)
self.server.expire(key, ttl)
time.sleep(2)
value = self.server.get(key)
self.assertIsNone(value)
if __name__ == '__main__':
unittest.main()
| true |
fc935b3dec9c1b7eb6bbc421efe4ca9f7b4a9bde | Python | lichkingwulaa/Codewars | /5 kyu/5_kyu_Return_substring_instance_count-2.py | UTF-8 | 1,247 | 3.140625 | 3 | [] | no_license | def search_substr(full_text, search_text, allow_overlap=True):
print(full_text, search_text, allow_overlap)
if allow_overlap:
count = 0
for i in range(len(full_text) - len(search_text) + 1):
if full_text[i:i + len(search_text)] == search_text != '':
count += 1
return count
else:
return full_text.count(search_text) if search_text else 0
print(search_substr('a', '', allow_overlap=True))
# 汪小佬
def search_substr1(full_text, search_text, allow_overlap=True):
if allow_overlap:
return len([search_text for i in range(len(full_text) - len(search_text) + 1)
if full_text[i:i + len(search_text)] == search_text != '' ])
else:
return full_text.count(search_text) if search_text else 0
def search_substr2(full_text, search_text, allow_overlap=True):
return len([search_text for i in range(len(full_text) - len(search_text) + 1)
if full_text[i:i + len(search_text)] == search_text != '']) \
if allow_overlap else (full_text.count(search_text) if search_text else 0)
# 大佬鼠
import re
def search_substr(full_text, search_text, allow_overlap=True):
if not full_text or not search_text: return 0
return len(re.findall(f'(?=({search_text}))' if allow_overlap else search_text, full_text)) | true |
6e9b4cc631e3282876add51d01def381594998dd | Python | Motamensalih/LISUM03_motamen_week5 | /model_deploy_using_html_form.py | UTF-8 | 782 | 2.71875 | 3 | [
"MIT"
] | permissive | from flask import Flask, render_template, request
import pickle
import numpy as np
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict' , methods = ['POST'])
def tumor_predict():
model = pickle.load(open('model.pkl' , 'rb'))
int_features = [float(x) for x in request.form.values()]
final_features = [np.array(int_features)]
tumor_pred = model.predict(final_features)
if tumor_pred == 1:
return render_template('index.html' , prediction_text = "tumor is benign , it will not spread")
else:
return render_template('index.html' , prediction_text = "tumor is malignant , it will spread")
if __name__ =='__main__':
app.run(debug = True)
| true |
ebcf7316e577b5dad2e2284e1ab524db64d0d170 | Python | nicolopinci/6DOF | /Vision system/ballRecognition.py | UTF-8 | 4,900 | 3.125 | 3 | [] | no_license | """
Computer vision system for the detection of the ball position and velocity.
"""
import numpy as np
import cv2
from collections import deque
import imutils
from datetime import datetime
import math
from tkinter import *
def getCurrentRoll():
return 0
def getCurrentPitch():
return 0
def stabilizeCenter():
print("Stabilization to the center...")
def drawEight():
print("Drawing an eight...")
def drawCircle():
print("Drawing a circle...")
def detectBall():
cap = cv2.VideoCapture(0)
halfX = cap.get(cv2.CAP_PROP_FRAME_WIDTH)/2
halfY = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)/2
bufflen = 20;
pts = deque(maxlen=bufflen)
realX = 0
realY = 0
previousX = 0
previousY = 0
deltaX = 0
deltaY = 0
deltaVx = 0
deltaVy = 0
windowName = '6DOF motion platform'
initialTime = datetime.now()
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
blurred = cv2.GaussianBlur(frame,(11, 11),0)
hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
# Threshold of red in HSV space
lower_red_low = np.array([0, 100, 100])
lower_red_up = np.array([10, 255, 255])
upper_red_low = np.array([160, 100, 100])
upper_red_up = np.array([179, 255, 255])
# preparing the mask to overlay
mask1 = cv2.inRange(hsv, lower_red_low, lower_red_up)
mask2 = cv2.inRange(hsv, upper_red_low, upper_red_up)
mask = cv2.bitwise_or(mask1,mask2)
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
center = None
# only proceed if at least one contour was found
if len(cnts) > 0:
# find the largest contour in the mask, then use
# it to compute the minimum enclosing circle and
# centroid
c = max(cnts, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
# only proceed if the radius meets a minimum size
if radius > 10:
# draw the circle and centroid on the frame,
# then update the list of tracked points
cv2.circle(frame, (int(x), int(y)), int(radius),
(0, 255, 255), 2)
cv2.circle(frame, center, 5, (0, 0, 255), -1)
# update the points queue
pts.appendleft(center)
# loop over the set of tracked points
for i in range(1, len(pts)):
# if either of the tracked points are None, ignore
# them
if pts[i - 1] is None or pts[i] is None:
continue
# otherwise, compute the thickness of the line and
# draw the connecting lines
thickness = int(np.sqrt(bufflen / float(i + 1)) * 2.5)
cv2.line(frame, pts[i - 1], pts[i], (0, 0, 255), thickness)
# Display the resulting frame
cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
cv2.resizeWindow(windowName, 711,600)
cv2.imshow(windowName, frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if center is not None:
previousX = realX
previousY = realY
currentRoll = getCurrentRoll()
currentPitch = getCurrentPitch()
realX = (center[0] - halfX)/math.cos(currentRoll)
realY = (center[1] - halfY)/math.cos(currentPitch)
deltaX = realX - previousX
deltaY = realY - previousY
deltaT = (datetime.now() - initialTime).total_seconds()
Vx = deltaX/deltaT
Vy = deltaY/deltaT
initialTime = datetime.now()
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
def platformControl():
pc = Tk()
pc.title("Platform control")
pc.mainloop()
window = Tk()
window.title("6DOF control")
buttonCenter = Button(window, text="Stabilize ball in the middle", command=stabilizeCenter)
buttonCenter.pack()
buttonEight = Button(window, text="Draw an eight", command=drawEight)
buttonEight.pack()
buttonCircle = Button(window, text="Draw a circle", command=drawCircle)
buttonCircle.pack()
buttonCircle = Button(window, text="Ball detection", command=detectBall)
buttonCircle.pack()
buttonPLatformControl = Button(window, text="Manual control of the platform", command=platformControl)
buttonPLatformControl.pack()
window.mainloop()
| true |
84aa8b043f5acd79ec051c0241b95dc7851afaa5 | Python | Yejin6911/Algorithm | /백준/BJ_1260.py | UTF-8 | 1,193 | 3.53125 | 4 | [] | no_license | import sys
from collections import deque
n, m, v = map(int, sys.stdin.readline().rstrip().split())
graph = [[] for _ in range(n+1)]
for i in range(m):
v1, v2 = map(int, sys.stdin.readline().rstrip().split())
# 양방향이기 때문에 양쪽에 다 넣어주어야 한다.
graph[v1].append(v2)
graph[v2].append(v1)
# 숫자가 작은 점부터 조회할 수 있도록 정렬처리해주었다.
for i in graph:
i.sort()
# 깊이우선탐색
def dfs(graph, v, visited):
print(v, end=' ')
visited[v] = True
for i in graph[v]:
if not visited[i]:
dfs(graph, i, visited)
# 너비우선탐색
def bfs(graph, v, visited):
queue = deque()
queue.append(v)
visited[v] = True
while queue:
now = queue.popleft()
print(now, end=' ')
for i in graph[now]:
if not visited[i]:
queue.append(i)
visited[i] = True
visited = [False for _ in range(n+1)]
dfs(graph, v, visited)
for i in range(1, n+1):
if not visited[v]:
dfs(i)
print()
visited = [False for x in range(n+1)]
bfs(graph, v, visited)
for i in range(1, n+1):
if not visited[v]:
bfs(i)
| true |
4e739a5642ccacb45895c05da2553be1fe75fe77 | Python | Ilgrim/cwmud | /cwmud/core/items.py | UTF-8 | 3,533 | 2.734375 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""Item management and containers."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2017 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)
from collections import Counter
from .attributes import Attribute, ListAttribute, Unset
from .entities import ENTITIES, Entity
from .logs import get_logger
from .utils import joins
log = get_logger("items")
class ItemListAttribute(ListAttribute):
"""An attribute for a list of items."""
class Proxy(ListAttribute.Proxy):
def __repr__(self):
return repr(self._items)
def __setitem__(self, index, value):
if not isinstance(value, Item):
raise TypeError(joins(value, "is not an Item"))
value.container = self._entity
super().__setitem__(index, value)
def __delitem__(self, index):
self._items[index].container = Unset
super().__delitem__(index)
def insert(self, index, value):
if not isinstance(value, Item):
raise TypeError(joins(value, "is not an Item"))
value.container = self._entity
super().insert(index, value)
def get_counts(self):
return Counter([item.name for item in self._items]).items()
def get_weight(self):
return sum([item.get_weight() for item in self._items])
@classmethod
def serialize(cls, entity, value):
return [item.uid for item in value]
@classmethod
def deserialize(cls, entity, value):
return cls.Proxy(entity, [Item.get(uid) for uid in value])
@ENTITIES.register
class Item(Entity):
"""An item."""
_uid_code = "I"
type = "item"
def __repr__(self):
return joins("Item<", self.uid, ">", sep="")
def get_weight(self):
"""Get the weight of this item."""
return self.weight
@Item.register_attr("nouns")
class ItemNouns(Attribute):
"""An item's nouns."""
_default = "item"
@Item.register_attr("name")
class ItemName(Attribute):
"""An item's name."""
_default = "an item"
@Item.register_attr("short")
class ItemShortDesc(Attribute):
"""An item's short description."""
_default = "Some sort of item is lying here."
@Item.register_attr("long")
class ItemLongDesc(Attribute):
"""An item's long description."""
_default = "There's nothing particularly interesting about it."
@Item.register_attr("weight")
class ItemWeight(Attribute):
"""An item's weight."""
_default = 0
@Item.register_attr("container")
class ItemContainer(Attribute):
"""The container an item is in.
Changing this does not set a reverse relationship, so setting this
will generally be managed by the container.
"""
@classmethod
def serialize(cls, entity, value):
return value.uid
@classmethod
def deserialize(cls, entity, value):
container = Item.get(value)
if not container:
log.warning("Could not load container '%s' for %s.",
value, entity)
return container
@ENTITIES.register
class Container(Item):
"""A container item."""
type = "container"
def get_weight(self):
"""Get the weight of this container and its contents."""
return self.weight + self.contents.get_weight()
@Container.register_attr("contents")
class ContainerContents(ItemListAttribute):
"""The contents of a container."""
| true |
d56f61c624424aa16dbda193d9b44aa754b4c235 | Python | BrianHerron-exe/CS103 | /lab-bmplib/lab-bmplib/compile | UTF-8 | 1,236 | 2.546875 | 3 | [] | no_license | #!/usr/bin/python
#-*- mode: python -*-
"""
Usage:
compile foo # runs clang++ <options> foo.cpp -o foo
compile foo.cpp # same as previous
compile foo.cpp bar.cpp baz.o -o bar # clang++ <options> <args>
For installation instructions, see
http://bits.usc.edu/cs103/compile/
Contact: dpritcha@usc.edu
"""
def compile_convert(args, warn = True):
if len(args) == 1:
arg = args[0]
if arg.endswith(".cpp"):
arg = arg[:-4]
args = [arg+".cpp", "-o", arg]
prefix = ["clang++", "-g"]
if warn:
prefix += ["-Wall", "-Wvla", "-Wshadow", "-Wunreachable-code",
"-Wconversion",
"-Wno-shorten-64-to-32", "-Wno-sign-conversion",
"-Wno-sign-compare", "-Wno-write-strings"]
# this was going to be added Fall 2015 but is probably too experimental
# "-fsanitize=undefined"
# it's worth considering -fsanitize=address or -fsanitize=memory too
# except that they are not compatible with valgrind :(
return prefix + args
if __name__ == "__main__":
import os, sys
if len(sys.argv) <= 1:
print("Error in 'compile': no arguments given")
else:
os.system(" ".join(compile_convert(sys.argv[1:])))
| true |
7972df936501804d6fd40b22450ae95fa5b7dd12 | Python | xfroggy/NOAA-Hurricane-RISK-predictor---local | /models.py | UTF-8 | 2,847 | 3.375 | 3 | [] | no_license | from datetime import timedelta
import math
def get_hits(data, my_location, radius):
#filter for only storms that became hurricanes
df_hu = data[data['status'] == 'HU']
#full list of storms
hurricane_dt = data
#sorted by unique storm identifier
id = df_hu['identifier'].unique()
# array that will store list of storms that hit location coordinates
hurricane_history = []
# iterate through list of coordinates for each storm, checking to see if the paths cross location coordinates
for ind in id:
current = hurricane_dt[hurricane_dt['identifier'] == ind]
initial_reading = current.head(1)
# determine if storm started South of location coordinates
starts_South = initial_reading['latitude'] < my_location[0]
if (starts_South.item() == True):
coord_name = 'latitude'
nearest_coord(coord_name, current, my_location, hurricane_history, radius)
#determine if storm started East of location coordinates
starts_East = initial_reading['longitude'] < my_location[0]
if (starts_East.item() == True):
coord_name = 'longitude'
nearest_coord(coord_name, current, my_location, hurricane_history, radius)
return [hurricane_history, len(id)]
def checkCollision(P,Q, x, y, radius):
x1 = P['latitude'].item()
y1 = P['longitude'].item()
x2 = Q['latitude'].item()
y2 = Q['longitude'].item()
# formula for the perpendicular distance of the location (point) to the line
dist = abs(((y1-y2)*x)+((x2-x1)*y) + (x1*y2) - (x2*y1)) / math.sqrt(((x2-x1)*(x2-x1)) + ((y2-y1)*(y2-y1)))
if (radius == dist) or (radius > dist):
# touches or intersects radius
return True
else:
# outside of radius
return False
def nearest_coord(coord_name, current, my_location, hurricane_history, radius):
# get 2 points closest to the location to form a line, then pass these readings to 'checkCollision' to see if line intersects with the radius around our location
# get first location after crossing latitude (if it crosses)
mask = current[coord_name] >= my_location[0]
point_A = current[mask].head(1)
# if it crosses, find previous location reading
if not point_A.empty:
point_B = current[
(current['datetime'] >= (point_A['datetime'].item() - timedelta(hours=6))) & (current['datetime'] < point_A['datetime'].item())
]
# data is not always in 6 hour increments so if more than 1 reading in previous 6 hours, take the latest
point_B = point_B.tail(1)
is_hit = checkCollision(point_A, point_B, my_location[0], my_location[1], radius)
if is_hit:
hurricane_history.append(point_A['identifier'].item())
return ""
| true |
024d6360e5b6cd06fca597eea47812776cc01e13 | Python | Ritvik09/My-Python-Codes | /Python Codes/Problems & Solutions/16..py | UTF-8 | 233 | 3.578125 | 4 | [] | no_license | v = input("Enter a verb: ")
a = input("Enter an adjective: ")
n = input("Enter a noun: ")
print("Jeeves " + v + " my " + a + " " + n + " out of the " + n + " as if he were a vegetarian fishing a " + n + " out of his salad.")
| true |
9980a770a6a1adb3b72a9936fd6f452ae6742f5a | Python | hackjoy/learn_cryptography | /cryptohack/encoding/decimalToAscii.py | UTF-8 | 245 | 2.578125 | 3 | [] | no_license | from Cryptodome.Util.number import long_to_bytes
number = 11515195063862318899931685488813747395775516287289682636499965282714637259206269
print(long_to_bytes(number)) # this somehow converted all the way to ascii rather than the raw bytes..
| true |
bfea29acbefb48c5033fa07a55e6457b91229a1c | Python | cjwcommuny/pybetter | /pybetter/global_function_replacer.py | UTF-8 | 484 | 2.921875 | 3 | [
"MIT"
] | permissive | from contextlib import contextmanager
class replace_attribute:
def __init__(self, obj, attr_name: str, new_attr):
self.obj = obj
self.attr_name = attr_name
self.new_attr = new_attr
self.__temp = None
def __enter__(self):
self.__temp = getattr(self.obj, self.attr_name)
setattr(self.obj, self.attr_name, self.new_attr)
def __exit__(self, exc_type, exc_val, exc_tb):
setattr(self.obj, self.attr_name, self.__temp)
| true |
a123e0e656e312f76bee0b5873983a907d86fbb9 | Python | keyi/Leetcode_Solutions | /Algorithms/Python/Word-Break-II.py | UTF-8 | 1,025 | 3.0625 | 3 | [] | no_license | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: List[str]
"""
def check(word):
if not word:
return True
arr = [False for i in range(len(word))]
for i in range(len(word)):
if word[:i + 1] in wordDict:
arr[i] = True
continue
for j in range(i):
if arr[j] and word[j + 1:i + 1] in wordDict:
arr[i] = True
break
return arr[-1]
def dfs(cur, pos):
if pos == len(s):
ans.append(' '.join(cur))
return
temp = s[pos:]
for i in range(len(temp)):
x = temp[:i + 1]
if x in wordDict:
dfs(cur + [x], pos + i + 1)
ans = []
if check(s):
dfs([], 0)
return ans
| true |
f2e381e6801ec5698ccf79056d0e707fde583dee | Python | nax1016cs/ML | /iris.py | UTF-8 | 12,961 | 2.734375 | 3 | [] | no_license | import numpy as np
import pandas as pd
import math
import random
df =pd.read_csv("iris.data", header = None, names = ["sepal_length","sepal_width","petal_length", "petal_width", "name"])
df = df.sample(frac=1).reset_index(drop=True)
name = ["Iris-setosa","Iris-versicolor","Iris-virginica"]
feature = ["sepal_length","sepal_width","petal_length", "petal_width"]
# #
# n = ["mean", "std"]
# seta = pd.DataFrame(index=n, columns = feature)
# df_set = df[df["name"] == "Iris-setosa"]
# df_ver = df[df["name"] == "Iris-versicolor"]
# df_vir = df[df["name"] == "Iris-virginica"]
# for index, row in seta.iterrows():
# for x in range(len(feature)):
# if(index=="mean"):
# seta[feature[x]][index] = df_vir[feature[x]].mean()
# elif(index=="std"):
# seta[feature[x]][index] = df_vir[feature[x]].std()
# seta.to_csv('Iris-virginica.csv')
# #
actual_set_predict_set = 0
actual_set_predict_ver = 0
actual_set_predict_vir = 0
actual_ver_predict_set = 0
actual_ver_predict_ver = 0
actual_ver_predict_vir = 0
actual_vir_predict_set = 0
actual_vir_predict_ver = 0
actual_vir_predict_vir = 0
for l in range(1,4):
if(l==1):
### df1 = testing data
df1 = df[:50]
### df2 = training data
df2 = df[50:]
elif(l==2):
### df1 = testing data
df1 = df[50:100]
### df2 = training data
df2 = df[0:50]
df2 = df2.append(df[100:150], ignore_index = True)
elif(l==3):
### df1 = testing data
df1 = df[100:]
### df2 = training data
df2 = df[0:100]
df_set = df2[df2["name"] == "Iris-setosa"]
df_ver = df2[df2["name"] == "Iris-versicolor"]
df_vir = df2[df2["name"] == "Iris-virginica"]
record_mean = {"Iris-setosa":{},"Iris-versicolor":{},"Iris-virginica":{}}
record_std = {"Iris-setosa":{},"Iris-versicolor":{},"Iris-virginica":{}}
#Iris-setosa
for x in range(4):
record_mean["Iris-setosa"][feature[x]] = df_set[feature[x]].mean()
record_std["Iris-setosa"][feature[x]] = df_set[feature[x]].std()
#Iris-versicolor
for x in range(4):
record_mean["Iris-versicolor"][feature[x]] = df_ver[feature[x]].mean()
record_std["Iris-versicolor"][feature[x]] = df_ver[feature[x]].std()
#Iris-virginica
for x in range(4):
record_mean["Iris-virginica"][feature[x]] = df_vir[feature[x]].mean()
record_std["Iris-virginica"][feature[x]] = df_vir[feature[x]].std()
for index, row in df1.iterrows():
probability_of_set = 0;
probability_of_ver = 0;
probability_of_vir = 0;
for x in range(len(feature)):
if(record_std["Iris-setosa"][feature[x]]!=0):
probability_of_set += math.log(1/(record_std["Iris-setosa"][feature[x]]*math.sqrt(2*math.pi)) *math.exp((row[feature[x]]- record_mean["Iris-setosa"][feature[x]])**2 *(-1)/( 2*(record_std["Iris-setosa"][feature[x]])**2) ))
if(record_std["Iris-versicolor"][feature[x]]!=0):
probability_of_ver += math.log(1/(record_std["Iris-versicolor"][feature[x]]*math.sqrt(2*math.pi)) *math.exp((row[feature[x]]- record_mean["Iris-versicolor"][feature[x]])**2 *(-1)/( 2*(record_std["Iris-versicolor"][feature[x]])**2) ))
if(record_std["Iris-virginica"][feature[x]]!=0):
probability_of_vir += math.log(1/(record_std["Iris-virginica"][feature[x]]*math.sqrt(2*math.pi)) *math.exp((row[feature[x]]- record_mean["Iris-virginica"][feature[x]])**2 *(-1)/( 2*(record_std["Iris-virginica"][feature[x]])**2) ))
pset = df2[df2["name"]=="Iris-setosa"].shape[0] /df2.shape[0]
pver = df2[df2["name"]=="Iris-versicolor"].shape[0] /df2.shape[0]
pvir = df2[df2["name"]=="Iris-virginica"].shape[0] /df2.shape[0]
probability_of_set += math.log(pset)
probability_of_ver += math.log(pver)
probability_of_vir += math.log(pvir)
if( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_set and row["name"]=="Iris-setosa"):
actual_set_predict_set+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_ver and row["name"]=="Iris-setosa"):
actual_set_predict_ver+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_vir and row["name"]=="Iris-setosa"):
actual_set_predict_vir+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_set and row["name"]=="Iris-versicolor"):
actual_ver_predict_set+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_ver and row["name"]=="Iris-versicolor"):
actual_ver_predict_ver+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_vir and row["name"]=="Iris-versicolor"):
actual_ver_predict_vir+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_set and row["name"]=="Iris-virginica"):
actual_vir_predict_set+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_ver and row["name"]=="Iris-virginica"):
actual_vir_predict_ver+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_vir and row["name"]=="Iris-virginica"):
actual_vir_predict_vir+=1
print("K-fold cross-validation results: ")
print("-------------------------")
print("Confusion matrix:")
print(" predict Iris-setosa predict Iris-versicolor predict Iris-virginica")
print("actual Iris-setosa: ",int(actual_set_predict_set/3)," ",int(actual_set_predict_ver/3)," ",int(actual_set_predict_vir/3))
print("actual Iris-versicolor: ",int(actual_ver_predict_set/3)," ",int(actual_ver_predict_ver/3)," ",int(actual_ver_predict_vir/3))
print("actual Iris-virginica: ",int(actual_vir_predict_set/3)," ",int(actual_vir_predict_ver/3)," ",int(actual_vir_predict_vir/3))
print('\n')
print("Sensitivity(Recall): ")
print(" predict Iris-setosa predict Iris-versicolor predict Iris-virginica")
print(" ", actual_set_predict_set / (actual_set_predict_set+ actual_set_predict_ver+actual_set_predict_vir)," ",actual_ver_predict_ver / (actual_ver_predict_ver+ actual_ver_predict_set+actual_ver_predict_vir), " ",actual_vir_predict_vir / (actual_vir_predict_set+ actual_vir_predict_ver+actual_vir_predict_vir))
print('\n')
print("Precision: ")
print(" predict Iris-setosa predict Iris-versicolor predict Iris-virginica")
print(" ",actual_set_predict_set / (actual_set_predict_set+actual_ver_predict_set+actual_vir_predict_set)," ",actual_ver_predict_ver / (actual_ver_predict_ver+actual_set_predict_ver+actual_vir_predict_ver), " ",actual_vir_predict_vir / (actual_vir_predict_vir+actual_ver_predict_vir+actual_set_predict_vir))
print('\n')
print("Accuracy: ", (actual_set_predict_set + actual_ver_predict_ver + actual_vir_predict_vir) / (df1.shape[0]*3) )
print("-------------------------")
print('\n\n\n')
actual_set_predict_set = 0
actual_set_predict_ver = 0
actual_set_predict_vir = 0
actual_ver_predict_set = 0
actual_ver_predict_ver = 0
actual_ver_predict_vir = 0
actual_vir_predict_set = 0
actual_vir_predict_ver = 0
actual_vir_predict_vir = 0
df = df.sample(frac=1).reset_index(drop=True)
df1.iloc[0:0]
df2.iloc[0:0]
r0 = [random.randint(0, df.shape[0]) for _ in range(int(df.shape[0]/3))]
for x in range(1,df.shape[0]):
if x in r0:
df1 = df1.append(df[x:x], ignore_index = True)
else:
df2 = df2.append(df[x:x], ignore_index = True)
df_set = df2[df2["name"] == "Iris-setosa"]
df_ver = df2[df2["name"] == "Iris-versicolor"]
df_vir = df2[df2["name"] == "Iris-virginica"]
record_mean = {"Iris-setosa":{},"Iris-versicolor":{},"Iris-virginica":{}}
record_std = {"Iris-setosa":{},"Iris-versicolor":{},"Iris-virginica":{}}
#Iris-setosa
for x in range(4):
record_mean["Iris-setosa"][feature[x]] = df_set[feature[x]].mean()
record_std["Iris-setosa"][feature[x]] = df_set[feature[x]].std()
#Iris-versicolor
for x in range(4):
record_mean["Iris-versicolor"][feature[x]] = df_ver[feature[x]].mean()
record_std["Iris-versicolor"][feature[x]] = df_ver[feature[x]].std()
#Iris-virginica
for x in range(4):
record_mean["Iris-virginica"][feature[x]] = df_vir[feature[x]].mean()
record_std["Iris-virginica"][feature[x]] = df_vir[feature[x]].std()
for index, row in df1.iterrows():
probability_of_set = 0;
probability_of_ver = 0;
probability_of_vir = 0;
for x in range(len(feature)):
if(record_std["Iris-setosa"][feature[x]]!=0):
probability_of_set += math.log(1/(record_std["Iris-setosa"][feature[x]]*math.sqrt(2*math.pi)) *math.exp((row[feature[x]]- record_mean["Iris-setosa"][feature[x]])**2 *(-1)/( 2*(record_std["Iris-setosa"][feature[x]])**2) ))
if(record_std["Iris-versicolor"][feature[x]]!=0):
probability_of_ver += math.log(1/(record_std["Iris-versicolor"][feature[x]]*math.sqrt(2*math.pi)) *math.exp((row[feature[x]]- record_mean["Iris-versicolor"][feature[x]])**2 *(-1)/( 2*(record_std["Iris-versicolor"][feature[x]])**2) ))
if(record_std["Iris-virginica"][feature[x]]!=0):
probability_of_vir += math.log(1/(record_std["Iris-virginica"][feature[x]]*math.sqrt(2*math.pi)) *math.exp((row[feature[x]]- record_mean["Iris-virginica"][feature[x]])**2 *(-1)/( 2*(record_std["Iris-virginica"][feature[x]])**2) ))
pset = df2[df2["name"]=="Iris-setosa"].shape[0] /df2.shape[0]
pver = df2[df2["name"]=="Iris-versicolor"].shape[0] /df2.shape[0]
pvir = df2[df2["name"]=="Iris-virginica"].shape[0] /df2.shape[0]
probability_of_set += math.log(pset)
probability_of_ver += math.log(pver)
probability_of_vir += math.log(pvir)
if( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_set and row["name"]=="Iris-setosa"):
actual_set_predict_set+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_ver and row["name"]=="Iris-setosa"):
actual_set_predict_ver+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_vir and row["name"]=="Iris-setosa"):
actual_set_predict_vir+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_set and row["name"]=="Iris-versicolor"):
actual_ver_predict_set+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_ver and row["name"]=="Iris-versicolor"):
actual_ver_predict_ver+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_vir and row["name"]=="Iris-versicolor"):
actual_ver_predict_vir+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_set and row["name"]=="Iris-virginica"):
actual_vir_predict_set+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_ver and row["name"]=="Iris-virginica"):
actual_vir_predict_ver+=1
elif( max(probability_of_set,probability_of_ver,probability_of_vir) ==probability_of_vir and row["name"]=="Iris-virginica"):
actual_vir_predict_vir+=1
print("Holdout validation results: ")
print("-------------------------")
print("Confusion matrix:")
print(" predict Iris-setosa predict Iris-versicolor predict Iris-virginica")
print("actual Iris-setosa: ",int(actual_set_predict_set)," ",int(actual_set_predict_ver)," ",int(actual_set_predict_vir))
print("actual Iris-versicolor: ",int(actual_ver_predict_set)," ",int(actual_ver_predict_ver)," ",int(actual_ver_predict_vir))
print("actual Iris-virginica: ",int(actual_vir_predict_set)," ",int(actual_vir_predict_ver)," ",int(actual_vir_predict_vir))
print('\n')
print("Sensitivity(Recall): ")
print(" predict Iris-setosa predict Iris-versicolor predict Iris-virginica")
print(" ", actual_set_predict_set / (actual_set_predict_set+ actual_set_predict_ver+actual_set_predict_vir)," ",actual_ver_predict_ver / (actual_ver_predict_ver+ actual_ver_predict_set+actual_ver_predict_vir), " ",actual_vir_predict_vir / (actual_vir_predict_set+ actual_vir_predict_ver+actual_vir_predict_vir))
print('\n')
print("Precision: ")
print(" predict Iris-setosa predict Iris-versicolor predict Iris-virginica")
print(" ",actual_set_predict_set / (actual_set_predict_set+actual_ver_predict_set+actual_vir_predict_set)," ",actual_ver_predict_ver / (actual_ver_predict_ver+actual_set_predict_ver+actual_vir_predict_ver), " ",actual_vir_predict_vir / (actual_vir_predict_vir+actual_ver_predict_vir+actual_set_predict_vir))
print('\n')
print("Accuracy: ", (actual_set_predict_set + actual_ver_predict_ver + actual_vir_predict_vir) / (df1.shape[0]) )
print("-------------------------")
print('\n\n\n')
| true |
e12336ab71fedd856d3dd3582e055ad805d97c3f | Python | PacktPublishing/Learning-Concurrency-in-Python | /Chapter 03/forking.py | UTF-8 | 330 | 3.25 | 3 | [
"MIT"
] | permissive | import os
def child():
print("We are in the child process with PID= %d"%os.getpid())
def parent():
print("We are in the parent process with PID= %d"%os.getpid())
newRef=os.fork()
if newRef==0:
child()
else:
print("We are in the parent process and our child process has PID= %d"%newRef)
parent()
| true |
888ce47cfb264e98dddc737ae75c3f75df4acebc | Python | doan97/BSC | /Hille/exp/gamma/targets.py | UTF-8 | 3,470 | 2.953125 | 3 | [] | no_license | import numpy as np
# TODO write docstrings
class Target:
def __init__(self, position, stop_iteration):
self.position = position
self.stop_iteration = stop_iteration
def __iter__(self):
return self
def __next__(self):
raise NotImplementedError('create target subclass')
class ConstantTarget(Target):
def __init__(self, position, stop_iteration):
super().__init__(position, stop_iteration)
self.iteration = 0
def __next__(self):
if self.iteration == self.stop_iteration:
raise StopIteration
else:
self.iteration += 1
return self.position
class RandomTarget(Target):
def __init__(self, position, stop_iteration,
refresh_iteration, low, high):
super().__init__(position, stop_iteration)
self.refresh_iteration = refresh_iteration
self.low = low
self.high = high
self.iteration = 0
def __next__(self):
if self.iteration == self.stop_iteration:
raise StopIteration
else:
if self.iteration % self.refresh_iteration == 0:
self.position = np.random.uniform(self.low, self.high)
self.iteration += 1
return self.position
class OtherTarget(Target):
def __init__(self, position, stop_iteration, other):
super().__init__(position, stop_iteration)
self.other = other
self.iteration = 0
def __next__(self):
if self.iteration == self.stop_iteration:
raise StopIteration
else:
self.iteration += 1
self.position = self.other['target']
return self.position
class AgentTarget(Target):
def __init__(self, position, stop_iteration, other):
super().__init__(position, stop_iteration)
self.other = other
self.iteration = 0
def __next__(self):
if self.iteration == self.stop_iteration:
raise StopIteration
else:
self.iteration += 1
self.position = self.other['position']
return self.position
class LineTarget(Target):
def __init__(self, position, stop_iteration, refresh_iteration, low, high):
super().__init__(position, stop_iteration)
self.refresh_iteration = refresh_iteration
self.low = low
self.high = high
self.iteration = 0
self.point_a = None
self.point_b = None
def __next__(self):
if self.iteration == self.stop_iteration:
raise StopIteration
else:
if self.iteration % self.refresh_iteration == 0:
self.point_a = np.random.uniform(self.low, self.high)
self.point_b = np.random.uniform(self.low, self.high)
scale = (self.iteration % self.refresh_iteration) / self.refresh_iteration
self.position = scale * self.point_a + (1 - scale) * self.point_b
self.iteration += 1
return self.position
class ProximityTarget(Target):
def __init__(self, position, stop_iteration, refresh_iteration, low, high, proximity):
super().__init__(position, stop_iteration)
self.refresh_iteration = refresh_iteration
self.low = low
self.high = high
self.proximity = proximity
def __next__(self):
raise NotImplementedError('sensor loss is not directly connected to proximity target')
| true |
533dd62b6fe0c915917e38ed0a321409b50e48cf | Python | vyahello/python-decorators-cheetsheet | /materials/decorate_class_method.py | UTF-8 | 742 | 3.890625 | 4 | [
"Apache-2.0"
] | permissive | def trace(method):
def wrapper(*args, **kwargs):
method_name = method.__name__
class_name = args[0].__class__.__name__
print(f'Entering "{method_name}" method in "{class_name}" class instance')
print(f'"{method_name}" class method takes [{args}, {kwargs}] args')
result = method(*args, **kwargs)
print(f'Result of "{method_name}" method in "{class_name}" class instance is {result}')
print(f'Exiting from "{method_name}" method in "{class_name}" class instance')
return result
return wrapper
class Hello:
def __init__(self, word):
self._word = word
@trace
def say(self):
return f'Hello {self._word}!'
hello = Hello('Python')
hello.say()
| true |
e915717fcd42194c2f6828a4ea8e8ca51723bf0a | Python | 18haddadm/PythonProject1 | /menugenerator.py | UTF-8 | 104 | 3.125 | 3 | [] | no_license | import random
def food():
food = ["eggs", "milk", "candy"]
print (random.choice(food))
food ()
| true |
c0a9ea056083882be07ab435845b337a33dc6b32 | Python | nolanlum/kochira | /kochira/services/textproc/americanize.py | UTF-8 | 2,436 | 2.671875 | 3 | [
"MS-PL"
] | permissive | """
Passive-aggressive spelling corrector.
Ensures that users are using Freedom English. Could be configured for other
languages, I guess...
"""
import enchant
import re
from textblob import TextBlob
from nltk.corpus import wordnet
from kochira import config
from kochira.service import Service, background, Config
service = Service(__name__, __doc__)
DISSIMILARITY_THRESHOLD = 0.5
@service.config
class Config(Config):
from_lang = config.Field(doc="Language to convert from.", default="en_GB")
to_lang = config.Field(doc="Language to convert to (hint: en_US).", default="en_US")
def dissimilarity(from_word, to_word):
from_syn = set(wordnet.synsets(from_word))
to_syn = set(wordnet.synsets(to_word))
both = from_syn & to_syn
# we don't actually know anything about this word
if not both:
return float("inf")
return len(from_syn - to_syn) / len(both)
def process_words(words):
for word in words:
# split hyphenated words because those suck
yield from str(word).split("-")
def compute_replacements(from_lang, to_lang, message):
from_dic = enchant.Dict(from_lang)
to_dic = enchant.Dict(to_lang)
blob = TextBlob(message)
replacements = {}
for word in process_words(blob.words):
if (from_dic.check(word) or any(word.lower() == s.lower() for s in from_dic.suggest(word))) and \
not (to_dic.check(word) or any(word.lower() == s.lower() for s in to_dic.suggest(word))):
suggestions = sorted([(dissimilarity(word, s), i, s) for i, s in enumerate(to_dic.suggest(word))
if s.lower() != word.lower()])
if suggestions:
score, _, replacement = suggestions[0]
if score <= DISSIMILARITY_THRESHOLD:
replacements[word] = replacement
return replacements
@service.hook("channel_message")
@background
def murrika(ctx, target, origin, message):
replacements = compute_replacements(ctx.config.from_lang,
ctx.config.to_lang,
message)
if not replacements:
return
for src, tgt in replacements.items():
message = re.sub(r"\b{}\b".format(re.escape(src)),
"\x1f" + tgt + "\x1f", message)
ctx.message("<{origin}> {message}".format(
origin=ctx.origin,
message=message
))
| true |
76977b2b54ea8057fd26d9807bee881e63355a62 | Python | zzhaoiii/caculate | /caculate_acc.py | UTF-8 | 7,329 | 2.765625 | 3 | [] | no_license | import xml.etree.ElementTree as ET
import os
import shutil
import cv2
import json
CLASSES = []
def convert(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
objects = root.findall('object')
gt = []
for element in objects:
org_name = element.find('name').text
# name = str(class_to_ind[org_name])
if org_name not in CLASSES:
continue
bndbox = element.find('bndbox')
x1 = int(float(bndbox.find('xmin').text))
y1 = int(float(bndbox.find('ymin').text))
x2 = int(float(bndbox.find('xmax').text))
y2 = int(float(bndbox.find('ymax').text))
gt.append([org_name, x1, y1, x2, y2])
return gt
def get_gts(anns_folder):
gts = {}
for index, file_name in enumerate(os.listdir(anns_folder)):
full = os.path.join(anns_folder, file_name)
gt = convert(full)
gts[file_name[:file_name.rindex('.')]] = gt
return gts
def calculate_iou(rec1, rec2):
"""
computing IoU
:param rec1: (y0, x0, y1, x1), which reflects
(top, left, bottom, right)
:param rec2: (y0, x0, y1, x1)
:return: scala value of IoU
"""
# computing area of each rectangles
S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])
# computing the sum_area
sum_area = S_rec1 + S_rec2
# find the each edge of intersect rectangle
left_line = max(rec1[1], rec2[1])
right_line = min(rec1[3], rec2[3])
top_line = max(rec1[0], rec2[0])
bottom_line = min(rec1[2], rec2[2])
# judge if there is an intersect
if left_line >= right_line or top_line >= bottom_line:
return 0
else:
intersect = (right_line - left_line) * (bottom_line - top_line)
return (intersect / (sum_area - intersect)) * 1.0
def pre_results_pic(results_pic, anns_folder, imgs_folder, out_folder):
back_data = {}
for item in results_pic:
image_name = os.path.basename(item['path'])
name = image_name[:image_name.rindex('.')]
if name not in back_data:
back_data[name] = [item]
else:
back_data[name].append(item)
for xml_name in os.listdir(anns_folder):
name = xml_name[:xml_name.rindex('.')]
if name not in back_data:
back_data[name] = []
draw_result(imgs_folder, back_data, out_folder)
return back_data
def draw_result(imgs_folder, results_pic, out_folder):
if os.path.exists(out_folder):
shutil.rmtree(out_folder)
os.makedirs(out_folder)
print('draw result to images ...')
for image_name in os.listdir(imgs_folder):
name = image_name[:image_name.rindex('.')]
results = results_pic[name]
full = os.path.join(imgs_folder, image_name)
image = cv2.imread(full)
for box in results:
cv2.rectangle(image, (int(box['xmin']), int(box['ymin'])), (int(box['xmax']), int(box['ymax'])),
(0, 0, 255), 3)
txt = '%s:%s' % (box['type'], box['score'])
cv2.putText(image, txt, (int(box['xmin']), int(box['ymin'])), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imwrite(os.path.join(out_folder, image_name), image)
# print(os.path.join(out_folder, image_name))
def read_pre(file_name, anns_folder, imgs_folder, out_folder):
with open(file_name) as file:
lines = file.readlines()
index = 0
results = {}
while index < len(lines):
line = lines[index]
if '#' in line:
org_name = lines[index + 1]
name = org_name[:org_name.rindex('.')]
num = int(lines[index + 2])
results[name] = []
for i in range(index + 3, index + 3 + num):
line = lines[i].strip('\r\n').split(' ')
line = [item for item in line if item != '']
results[name].append({
'xmin': int(float(line[1])),
'ymin': int(float(line[2])),
'xmax': int(float(line[3])),
'ymax': int(float(line[4])),
'type': CLASSES[int(line[0])],
'score': line[5],
})
index += (3 + num)
for xml_name in os.listdir(anns_folder):
name = xml_name[:xml_name.rindex('.')]
if name not in results:
results[name] = []
if imgs_folder is not None:
draw_result(imgs_folder, results, out_folder)
return results
def acc(anns_folder, imgs_folder, results_file, out_folder, iou_threshold=0.5):
gts = get_gts(anns_folder, )
results_pic = read_pre(results_file, anns_folder, imgs_folder, out_folder)
true_label_num = 0
gt_num = 0
gt_pre_class_num = {}
true_label_pre_class_num = {}
wrong_pic = 0
invalid_pic = 0
miss_pic = 0
for name in results_pic:
gts_ = gts[name]
results = results_pic[name]
for gt in gts_:
gt_num += 1
for result in results:
iou = calculate_iou([gt[2], gt[1], gt[4], gt[3], ],
[int(result['ymin']), int(result['xmin']), int(result['ymax']),
int(result['xmax'])])
# 预测正确
if gt[0] == result['type'] and iou >= iou_threshold:
true_label_num += 1
if gt[0] not in true_label_pre_class_num:
true_label_pre_class_num[gt[0]] = 1
else:
true_label_pre_class_num[gt[0]] += 1
break
# gt_pre_class数量
if gt[0] not in gt_pre_class_num:
gt_pre_class_num[gt[0]] = 1
else:
gt_pre_class_num[gt[0]] += 1
if len(gts_) == 0 and len(results) != 0:
wrong_pic += 1
if len(results) > len(gts_) * 100:
invalid_pic += 1
if len(gts_) != 0 and len(results) == 0:
miss_pic += 1
print('--' * 10)
for class_name in gt_pre_class_num:
if class_name not in true_label_pre_class_num:
true_label_pre_class_num[class_name] = 0
t = true_label_pre_class_num[class_name] / gt_pre_class_num[class_name]
print('%s acc: %d/%d = %.3f' % (
class_name, true_label_pre_class_num[class_name], gt_pre_class_num[class_name], t))
print('--' * 10)
print('avg acc : %d/%d = %.3f' % (true_label_num, gt_num, true_label_num / gt_num))
print('wrong pic : %d/%d = %.3f' % (wrong_pic, len(results_pic), wrong_pic / len(results_pic)))
print('invalid pic : %d/%d = %.3f' % (invalid_pic, len(results_pic), invalid_pic / len(results_pic)))
print('miss pic : %d/%d = %.3f' % (miss_pic, len(results_pic), miss_pic / len(results_pic)))
if __name__ == '__main__':
with open('config.json') as file:
config = json.load(file)
CLASSES = config['classes']
acc(config['anns_folder'], config['imgs_folder'], config['results_file'], config['out_folder'],
iou_threshold=config['overlap'])
| true |
84e94cdb8aa1d7570e4350de0f452ce50d9d3a67 | Python | okekefrancis112/PythonEncyclopedia | /proandissuesc.py | UTF-8 | 947 | 2.609375 | 3 | [] | no_license | from requests.auth import HTTPBasicAuth
import json
import requests
def get_project(domain_name,auth,headers, project_key):
url = f"https://{domain_name}.atlassian.net/rest/api/latest/project/{project_key}"
response = requests.request("GET", url, headers=headers, auth=auth)
log = json.loads(response.text)
name = log["name"]
id = log["id"]
key = log["key"]
print(f"Project Name=>", name)
print(f"Project Id=>", id)
print(f"Project Key=>", key)
def get_issue(domain_name,auth, headers, project_key):
url = f"https://{domain_name}.atlassian.net/rest/api/3/search?jql=project={project_key}"
response = requests.request("GET", url, headers=headers, auth=auth)
log = json.loads(response.text)
res = log["issues"]
for i, item in enumerate(res):
id = (item["id"])
key =(item["key"])
opt = (id, key)
data = ('"ID":"%s","KEY":"%s"') %(id, key)
print(data) | true |
4e1b3b45983679b192e1118119d0050f115c4e43 | Python | AdamZhouSE/pythonHomework | /Code/CodeRecords/2846/60677/234652.py | UTF-8 | 116 | 2.953125 | 3 | [] | no_license | n=input()
x=list(set(input().split()))
y=x.__len__()
for i in x:
if i=="0":
y-=1
break
print(y)
| true |
2a2bbe882cd75858bbe13e628cab8a758ab1cf0e | Python | akhilsai0099/Python-Practice | /Sorting_algorithms/sorting_visualizer1.py | UTF-8 | 6,622 | 2.953125 | 3 | [] | no_license | import pygame
import random
pygame.font.init()
screen = pygame.display.set_mode((900,650))
pygame.display.set_caption("Sorting Visualisation")
run = True
width = 900
height = 600
array = [0]*151
arr_clr = [(0, 204, 102)]*151
clr_ind = 0
clr = [(0, 204, 102), (255, 0, 0),
(0, 0, 153), (255, 102, 0)]
TIME = 20
fnt = pygame.font.SysFont("comicsans", 30)
fnt1 = pygame.font.SysFont("comicsans", 20)
fnt2 = pygame.font.SysFont("comicsans", 25)
def refill():
screen.fill((255,255,255))
draw()
pygame.display.update()
pygame.time.delay(TIME)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_i:
value = "Insertion Sort"
refill()
def mergesort(array, l, r):
mid =(l + r)//2
if l<r:
mergesort(array, l, mid)
mergesort(array, mid + 1, r)
merge(array, l, mid,
mid + 1, r)
def merge(array, x1, y1, x2, y2):
i = x1
j = x2
temp =[]
pygame.event.pump()
while i<= y1 and j<= y2:
for event in pygame.event.get():
# If we click Close button in window
if event.type == pygame.QUIT:
pygame.quit()
arr_clr[i]= clr[1]
arr_clr[j]= clr[1]
refill()
arr_clr[i]= clr[0]
arr_clr[j]= clr[0]
if array[i]<array[j]:
temp.append(array[i])
i+= 1
else:
temp.append(array[j])
j+= 1
while i<= y1:
for event in pygame.event.get():
# If we click Close button in window
if event.type == pygame.QUIT:
pygame.quit()
arr_clr[i]= clr[1]
refill()
arr_clr[i]= clr[0]
temp.append(array[i])
i+= 1
while j<= y2:
for event in pygame.event.get():
# If we click Close button in window
if event.type == pygame.QUIT:
pygame.quit()
arr_clr[j]= clr[1]
refill()
arr_clr[j]= clr[0]
temp.append(array[j])
j+= 1
j = 0
for i in range(x1, y2 + 1):
pygame.event.pump()
array[i]= temp[j]
j+= 1
arr_clr[i]= clr[2]
refill()
if y2-x1 == len(array)-2:
arr_clr[i]= clr[3]
else:
arr_clr[i]= clr[0]
def insertionSort(array):
for i in range(1, len(array)):
for event in pygame.event.get():
# If we click Close button in window
if event.type == pygame.QUIT:
pygame.quit()
pygame.event.pump()
refill()
key = array[i]
arr_clr[i] = clr[2]
j = i - 1
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
arr_clr[j] = clr[1]
refill()
arr_clr[j] = clr[3]
j = j - 1
array[j + 1] = key
refill()
arr_clr[i] = clr[3]
def selection_sort(list):
for i in range(0,len(list)-1):
for event in pygame.event.get():
# If we click Close button in window
if event.type == pygame.QUIT:
pygame.quit()
pygame.event.pump()
refill()
min_position = i
arr_clr[i] =clr[2]
for j in range(i+1, len(list)):
if list[j] < list[min_position]:
arr_clr[j] = clr[1]
refill()
min_position = j
arr_clr[j] = clr[0]
if min_position != i:
list[i], list[min_position] = list[min_position], list[i]
arr_clr[i] = clr[3]
refill()
def Bubble_sort(list):
for i in range(len(list)-1,0,-1):
for event in pygame.event.get():
# If we click Close button in window
if event.type == pygame.QUIT:
pygame.quit()
pygame.event.pump()
refill()
for j in range(i):
if list[j] > list[j+1]:
temp = list[j]
arr_clr[j] = clr[1]
refill()
list[j] = list[j+1]
arr_clr[j] = clr[2]
refill()
list[j+1] = temp
arr_clr[j] = clr[0]
arr_clr[i] = clr[3]
refill()
def generate_arr():
for i in range(1 ,151):
arr_clr[i] = clr[0]
array[i] = random.randrange(1,100)
generate_arr()
def draw():
txt = fnt.render("PRESS INITIAL LETTER OF THE ALGORITHM BELOW TO START SORTING" ,1,(0,0,0))
screen.blit(txt,(20,20))
txt1 = fnt.render("PRESS 'R' FOR NEW ARRAY",1,(0,0,0))
screen.blit(txt1,(20,60))
txt2 = fnt1.render("Selection sort , Merge sort , Insertion sort , Bubble sort",3,(0,0,0))
screen.blit(txt2,(20,40))
txt2 = fnt2.render("Press Up or Down arrows to increase or decrease the speed respectively",2,(0,0,0))
screen.blit(txt2,(310,60))
element_width = width //151
boundry_arr = 900 / 150
boundry_grp = 550 / 100
pygame.draw.line(screen, (0,0,0),(0,95),(900,95) , 6)
for i in range(1,100):
pygame.draw.line(screen,(224,224,224),(0,boundry_grp*i+100),(900 , boundry_grp*i+100),1)
for i in range(1,151):
pygame.draw.line(screen,arr_clr[i],(boundry_arr*i-3, 100),(boundry_arr * i-3, array[i]*boundry_grp + 100),element_width)
while run:
screen.fill((255,255,255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_i:
pygame.display.set_caption("Sorting Algorithm : Insertion sort")
insertionSort(array)
if event.key == pygame.K_s:
pygame.display.set_caption("Sorting Algorithm : Selection sort")
selection_sort(array)
if event.key == pygame.K_r:
pygame.display.set_caption("Generated New array")
generate_arr()
if event.key == pygame.K_m:
pygame.display.set_caption("Sorting Algorithm : Merge sort")
mergesort(array,1,len(array)-1)
if event.key == pygame.K_b:
pygame.display.set_caption("Sorting Algorithm : Bubble sort")
Bubble_sort(array)
if event.key == pygame.K_UP:
pygame.display.set_caption(f"speed : {TIME}")
TIME -= 5
if event.key == pygame.K_DOWN:
pygame.display.set_caption(f"speed : {TIME}")
TIME += 10
draw()
pygame.display.update()
pygame.quit()
| true |
09c9c62a28f3a0222d2df65551bcb62fea8e69ab | Python | Xiaoctw/LeetCode1_python | /字符串/把数字翻译成字符串_面试题46.py | UTF-8 | 456 | 3.421875 | 3 | [] | no_license | class Solution:
def translateNum(self, num: int) -> int:
"""
不要首先考虑搜索,动态规划更好用
:param num:
:return:
"""
p, q = 1, 1
num_str = str(num)
for i in range(1, len(num_str)):
p, q = q, p + q if 10 <= int(num_str[i - 1:i + 1]) <= 25 else q
return q
if __name__ == '__main__':
sol = Solution()
num = 25
print(sol.translateNum(num))
| true |
69af492b95693ff480f2c2e28242a816aac36419 | Python | PaulEcoffet/ipynbviewer | /src/ipynbviewer/ipynbview.py | UTF-8 | 747 | 3 | 3 | [
"MIT"
] | permissive | import json
import argparse
from .cell_readers import cell_readers
def read_ipynb(ipynb_dict: dict)-> str:
"""
Reads a whole notebook and output it in a human readable format
:param ipynb_dict:
:return: the human readable string
"""
outstr = []
try:
cells = ipynb_dict["cells"]
except KeyError:
raise ValueError("Not an ipython notebook")
for cell in cells:
outstr.append(cell_readers[cell["cell_type"]](cell))
return ("\n\n" + "-" * 80 + "\n\n").join(outstr)
def main():
agp = argparse.ArgumentParser()
agp.add_argument("file", type=argparse.FileType("r"))
args = agp.parse_args()
print(read_ipynb(json.load(args.file)))
if __name__ == "__main__":
main()
| true |
48f67aff4b0cdc61e15749ff2f85a01430a384fa | Python | subutux/gusic | /lib/core/SearchCompletion.py | UTF-8 | 2,377 | 2.59375 | 3 | [] | no_license | # This file is part of gusic.
# gusic is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# gusic is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with gusic. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2012-2013, Stijn Van Campenhout <stijn.vancampenhout@gmail.com>
from gi.repository import Gtk, GdkPixbuf
class SearchCompletion():
"""
Builds a ListStore with information of the mainStore
containing all the song, album an artist names for
matching angainst a completion form.
"""
def __init__(self,mainStore):
self.mainStore = mainStore
self.tmpStore = {
'albums' : [],
'artists' : []
}
self.matchStore = Gtk.ListStore(str,str,str,GdkPixbuf.Pixbuf)
# |
# | | id (if any, else 'none')
# | text
# type (song,album,artist)
self.iconSong = GdkPixbuf.Pixbuf.new_from_file('imgs/icon-song-16.png')
self.iconArtist = GdkPixbuf.Pixbuf.new_from_file('imgs/icon-artist-16.png')
self.iconAlbum = GdkPixbuf.Pixbuf.new_from_file('imgs/icon-album-16.png')
self.update_matchStore()
def update_matchStore(self):
"""
Updates the matchStore with the information of the mainStore
"""
self.matchStore.clear()
self.tmpStore['albums'] = []
self.tmpStore['artists'] = []
item = self.mainStore.get_iter_first()
while (item != None):
song = self.mainStore.get_value(item,1)
album = self.mainStore.get_value(item,3)
artist = self.mainStore.get_value(item,4)
#song
self.matchStore.append(['song',song,self.mainStore.get_value(item,5),self.iconSong])
#album
if album not in self.tmpStore['albums']:
self.tmpStore['albums'].append(album)
self.matchStore.append(['album',album,'none',self.iconAlbum])
#artist
if artist not in self.tmpStore['artists']:
self.tmpStore['artists'].append(artist)
self.matchStore.append(['artist',artist,'none',self.iconArtist])
item = self.mainStore.iter_next(item)
def get_matchStore(self):
return self.matchStore
| true |
afe769582b87e9c490c33dfb458bdb0e618bbe70 | Python | adalloul0928/Leetcode_Hell | /Archive/Amazon/minPathSum.py | UTF-8 | 698 | 3.28125 | 3 | [] | no_license | class Solution:
def minPathSum(self, grid) -> int:
rowLen = len(grid)
colLen = len(grid[0])
newGrid = [[0 for x in range(colLen)] for y in range(rowLen)]
newGrid[0][0] = grid[0][0]
for ind in range(1, colLen):
newGrid[0][ind] = newGrid[0][ind-1] + grid[0][ind]
for ind in range(1, rowLen):
newGrid[ind][0] = newGrid[ind-1][0] + grid[ind][0]
for r in range(1,rowLen):
for c in range(1, colLen):
newGrid[r][c] = min(newGrid[r-1][c], newGrid[r][c-1]) + grid[r][c]
return newGrid[-1][-1]
sol = Solution()
input = [
[1,3,1],
[1,5,1],
[4,2,1]
]
print(sol.minPathSum(input)) | true |
bb4b69505c115ef4b8b73fe435b1f1402611d0d1 | Python | Fxztam/sierra | /src/sierra/tTags.py | UTF-8 | 8,197 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | import traceback
class div():
def __init__(self, div_class=None, attr=None):
self.div_class = div_class
if div_class == None:
with open('index.html', 'a+') as f:
f.write("\n<div")
else:
with open('index.html', 'a+') as f:
f.write(f"\n<div class='{self.div_class}'")
if attr != None:
open('index.html', 'a+').write(attr)
open('index.html', 'a+').write(">")
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is not None:
traceback.print_exception(exc_type, exc_value, tb)
else:
open('index.html', 'a+').write("\n</div>")
def css(self, color='black', font_family='Arial', font_weight=False, text_align='left', font_size=False, background_color='white', \
background=False, margin_top='0px', margin_bottom='0px', margin_left='0px', margin_right='0px', border='0px', display='block', \
padding='0px', height=False, width=False, line_break=False, line_height=False, overflow=False, margin='0px', box_shadow=False):
"""
Args:
color (str, optional) : CSS color parameter. Defaults to 'black'.
font_family (str, optional) : CSS font-family parameter. Defaults to 'Arial'.
font_weight (str, optional) : CSS font-weight parameter. Defaults to False.
text_align (str, optional) : CSS text-align parameter. Defaults to 'left'.
font_size (str, optional) : CSS font-size parameter. Defaults to False.
background_color (str, optional) : CSS background-color parameter. Defaults to 'white'.
background (str, optional) : CSS background parameter. Defaults to False.
margin_top (str, optional) : CSS margin-top parameter. Defaults to '0px'.
margin_bottom (str, optional) : CSS margin-bottom parameter. Defaults to '0px'.
margin_left (str, optional) : CSS margin-left parameter. Defaults to '0px'.
margin_right (str, optional) : CSS margin-right parameter. Defaults to '0px'.
border (str, optional) : CSS border parameter. Defaults to '0px'.
display (str, optional) : CSS display parameter. Defaults to 'block'.
padding (str, optional) : CSS padding parameter. Defaults to '0px'.
height (str, optional) : CSS height parameter. Defaults to False.
width (str, optional) : CSS width parameter. Defaults to False.
line_break (str, optional) : CSS line-break parameter. Defaults to False.
line_height (str, optional) : CSS line-height parameter. Defaults to False.
overflow (str, optional) : CSS overflow parameter. Defaults to False.
margin (str, optional) : CSS margin parameter. Defaults to '0px'.
box_shadow (str, optional) : CSS box-shadow parameter. Defaults to False.
"""
with open('style.css', 'a+') as s:
s.write(f'''
.{self.div_class} {{
color: {color};
font-family: {font_family};
font-weight: {font_weight};
text-align: {text_align};
font-size: {font_size};
background-color: {background_color};
background: {background};
margin-top: {margin_top};
margin-bottom: {margin_bottom};
margin-left: {margin_left};
margin-right: {margin_right};
border: {border};
display: {display};
padding: {padding};
height: {height};
width: {width};
line-break: {line_break};
line-height: {line_height};
overflow: {overflow};
margin: {margin};
box-shadow: {box_shadow};
}}''')
class section():
def __init__(self, sec_class=None, attr=None):
self.sec_class = sec_class
if sec_class == None:
with open('index.html', 'a+') as f:
f.write("\n<section")
else:
with open('index.html', 'a+') as f:
f.write(f"\n<section class='section {self.sec_class}'")
if attr != None:
open('index.html', 'a+').write(f''' {attr}''')
open('index.html', 'a+').write(">")
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is not None:
traceback.print_exception(exc_type, exc_value, tb)
else:
open('index.html', 'a+').write("\n</section>")
def css(self, color='black', font_family='Arial', font_weight='False', text_align='False', font_size='False', background_color='False', \
background='False', margin_top='False', margin_bottom='False', margin_left='False', margin_right='False', border='False', \
display='block', padding='False', height='False', width='False', line_break='False', line_height='False', overflow='False', \
margin='False', box_shadow='False'):
"""
Args:
color (str, optional) : CSS color parameter. Defaults to 'black'.
font_family (str, optional) : CSS font-family parameter. Defaults to 'Arial'.
font_weight (str, optional) : CSS font-weight parameter. Defaults to False.
text_align (str, optional) : CSS text-align parameter. Defaults to False.
font_size (str, optional) : CSS font-size parameter. Defaults to False.
background_color (str, optional) : CSS background-color parameter. Defaults to 'white'.
background (str, optional) : CSS background parameter. Defaults to False.
margin_top (str, optional) : CSS margin-top parameter. Defaults to '0px'.
margin_bottom (str, optional) : CSS margin-bottom parameter. Defaults to '0px'.
margin_left (str, optional) : CSS margin-left parameter. Defaults to '0px'.
margin_right (str, optional) : CSS margin-right parameter. Defaults to '0px'.
border (str, optional) : CSS border parameter. Defaults to '0px'.
display (str, optional) : CSS display parameter. Defaults to 'block'.
padding (str, optional) : CSS padding parameter. Defaults to False.
height (str, optional) : CSS height parameter. Defaults to False.
width (str, optional) : CSS width parameter. Defaults to False.
line_break (str, optional) : CSS line-break parameter. Defaults to False.
line_height (str, optional) : CSS line-height parameter. Defaults to False.
overflow (str, optional) : CSS overflow parameter. Defaults to False.
margin (str, optional) : CSS margin parameter. Defaults to False.
box_shadow (str, optional) : CSS box-shadow parameter. Defaults to False.
"""
with open('style.css', 'a+') as s:
s.write(f'''
.{self.sec_class} {{
color: {color};
font-family: {font_family};
font-weight: {font_weight};
text-align: {text_align};
font-size: {font_size};
background-color: {background_color};
background: {background};
margin-top: {margin_top};
margin-bottom: {margin_bottom};
margin-left: {margin_left};
margin-right: {margin_right};
border: {border};
display: {display};
padding: {padding};
height: {height};
width: {width};
line-break: {line_break};
line-height: {line_height};
overflow: {overflow};
margin: {margin};
box-shadow: {box_shadow};
}}''')
def p(text, attr=None):
if attr != None:
with open('index.html', 'a+') as f:
f.write(f'''
<p {attr}>
{text}
</p>''')
else:
with open('index.html', 'a+') as f:
f.write(f'''
<p>
{text}
</p>''')
#with div(div_class='newClass', attr="id='some_id'") as d:
# p('This is some text')
# d.css(color='yellow')
#with section(sec_class="someClass", attr="id='new_id'") as s:
# p('Some more text', "class='anotherClass'")
# s.css(font_family='Times New Roman')
| true |
6a82ebe0257c5a01d110bc9deb3ee19ed19e49d3 | Python | Jackjet/pythonpachong | /代理ip/DL.py | UTF-8 | 2,354 | 2.703125 | 3 | [] | no_license | import requests
import re
import os
import time
class D(object):
def __init__(self):
self.url='https://www.kuaidaili.com/free/inha/'
def getIP(self,page):
'''
:param page: 页数
:return:
爬取ip代理
'''
head={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
}
with open('logs/dl.txt', 'w', encoding='utf-8') as f:
for i in range(1,page+1):
url='https://www.kuaidaili.com/free/inha/%d/'%(i)
print(url)
time.sleep(2)
response=requests.get(url=url,headers=head).content.decode()
# print(response)
par=r'<td data-title="IP">(.*?)</td>.*?<td data-title="PORT">(.*?)</td>'
p=re.compile(par,re.S)
html=p.findall(response)
print(html)
if(os.path.exists('logs')==0):
os.mkdir('logs')
for t in html:
f.write(t[0]+' '+t[1]+'\n')
print("爬取成功!")
def codeIP(self,path='logs/goodcode.txt'):
'''
严重ip代理是否可用
:param path: 保存ip代理路径
:return:
'''
head={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
}
with open('logs/dl.txt','r',encoding='utf-8') as f:
file=f.readlines()
if (os.path.exists('logs') == 0):
os.mkdir('logs')
with open(path,"w",encoding='utf-8') as f:
for t in file:
tmp=t.replace('\n','').split(' ')
ip={"http":"%s:%s"%(tmp[0],tmp[1])}
url= "https://www.baidu.com/"
print(ip['http'])
try:
r=requests.get(url,headers=head,proxies=ip)
# print(r.status_code)
if(r.status_code==200):
f.write(tmp[0] + ' ' + tmp[1] + '\n')
except:
print('ip异常')
print('完成验证')
t=D()
# t.getIP(5)
t.codeIP('logs/dl.txt')
| true |
74be3097c74eb9d29b28a63793231ef2b8418b74 | Python | cristianosoriopaz/Super-Mario | /proyecto mario/juego.py | UTF-8 | 84,370 | 2.625 | 3 | [] | no_license | import tkinter
import tkinter.ttk
import winsound
#creacion y titulacion de la ventana
v = tkinter.Tk()
v.title("Super Mario Game")
#inicializacion de variables de los enemigos y mario ademas de otras funcionalidades como sus limites en saltos, entre otras
posxm = 400
final=0
finall=0
both=0
nombres=[]
parejas=False
posym = 520
limite = False
estadopow=0
nivel=0
counterxm=0
counterym=0
estadom=0
estadoizdem=0
posxl = 400
posyl = 520
limite1 = False
counterxl=0
counteryl=0
estadol=0
estadoizdel=0
nombre1=""
nombre2=""
estadoe=0
estadoe1=0
estadoe2=0
estadoe3=0
estadoe4=1
estadoe5=0
estadoe6=0
estadoe7=0
estadoe8=0
estadoe9=0
estadoe10=0
estadoe11=0
estadoe12=1
estadoe13=0
estadoe14=0
estadoe15=0
estadoe16=0
posxe=790
posye=210
posxe1=790
posye1=210
posxe2=20
posye2=210
posxe3=20
posye3=210
posxe4=820
posye4=210
posxe5=820
posye5=210
posxe6=-20
posye6=210
posxe7=-20
posye7=210
posxe8=820
posye8=520
posxe9=820
posye9=520
posxe10=-20
posye10=520
posxe11=-20
posye11=520
posxe12=820
posye12=520
posxe13=820
posye13=520
posxe14=-20
posye14=520
posxe15=-20
posye15=520
posxe16=400
posye16=520
estadov1=1
estadov2=1
estadov3=1
estadov11=1
estadov21=1
estadov31=1
points=0
pointsl=0
presionado = [0,0,0,0,0,0,0]
#reproduccion del audio
winsound.PlaySound('track.wav',winsound.SND_ASYNC)
winsound.SND_LOOP
#funciones que permiten mover al personaje de mario
def saltar():
"""
funcion que permite saltar al personaje mario sin realizar ningun cambio en su posicion en x, determinando hacia que direccion esta orientado el personaje para realizarlo, tambien determinado por el limite de salto y un contador
"""
global canvas,lemario,posxm,posym,limite,counterym,estadoizdem
if estadoizdem==1:
if (limite!=True) and(counterym<=150):
canvas.delete(lemario)
counterym=counterym+5
posym=posym-5
lemario = canvas.create_image(posxm,posym, image=mario4)
v.after(10,saltar)
if (counterym>=150)or((posym==460)and(((posxm>=0)and(posxm<=300))or((posxm>=500)and(posxm<=800))))or((posym==340)and(((posxm>=220)and(posxm<=580))))or((posym==240)and(((posxm>=480)or(posxm<=320)))):
limite=True
if (limite==True)and (counterym>0):
canvas.delete(lemario)
counterym=counterym-5
posym=posym+5
lemario = canvas.create_image(posxm,posym, image=mario4)
if ((posym==450)and(((posxm>=0)and(posxm<=300))or((posxm>=500)and(posxm<=800))))or((posym==330)and(((posxm>=220)and(posxm<=580)))):
posym=450
counterym=0
v.after(10,saltar)
elif estadoizdem==0:
if (limite!=True) and(counterym<=150):
canvas.delete(lemario)
counterym=counterym+5
posym=posym-5
lemario = canvas.create_image(posxm,posym, image=mario14)
v.after(10,saltar)
if (counterym>=150) or((posym==460)and(((posxm>=0)and(posxm<=300))or((posxm>=500)and(posxm<=800))))or((posym==340)and(((posxm>=220)and(posxm<=580))))or((posym==240)and(((posxm>=480)or(posxm<=320)))):
limite=True
if (limite==True)and (counterym>0):
canvas.delete(lemario)
counterym=counterym-5
posym=posym+5
lemario = canvas.create_image(posxm,posym, image=mario14)
if ((posym==450)and(((posxm>=0)and(posxm<=300))or((posxm>=500)and(posxm<=800))))or((posym==330)and(((posxm>=220)and(posxm<=580)))):
posym=450
counterym=0
v.after(10,saltar)
def saltar2():
"""
Procedimiento que realiza el salto en parabola a la derecha, realizando un cambio positivo en la posicion en x, tambien determinado por el limite de salto y un contador
"""
global canvas,lemario,posxm,posym,limite,counterym,counterxm
if (limite!=True) and(counterym<=150):
canvas.delete(lemario)
counterym=counterym+5
posym=posym-5
posxm=posxm+3
lemario = canvas.create_image(posxm,posym, image=mario4)
v.after(10,saltar2)
if (counterym>=150) or((posym==460)and(((posxm>=0)and(posxm<=300))or((posxm>=500)and(posxm<=800))))or((posym==340)and(((posxm>=220)and(posxm<=580))))or((posym==80)and(((posxm>=0)and(posxm<=800))))or((posym==240)and(((posxm>=480)or(posxm<=320)))):
limite=True
if (limite==True)and (counterym>0):
canvas.delete(lemario)
counterym=counterym-5
posym=posym+5
posxm=posxm+3
lemario = canvas.create_image(posxm,posym, image=mario4)
v.after(10,saltar2)
if ((posym==420)and(((posxm>=0)and(posxm<=300))or((posxm>=500)and(posxm<=800)))):
posym=420
counterym=0
elif(posym==310)and(((posxm>=220)and(posxm<=580))):
posym=310
counterym=0
elif ((posym==210)and(((posxm>=0)and(posxm<=330))or((posxm>=480)and(posxm<=800)))):
posym=210
counterym=0
def saltar3():
"""
Procedimiento que realiza el salto en parabola a la izquierda, realizando un cambio negativo en la posicion en x, tambien determinado por el limite de salto y un contador
"""
global canvas,lemario,posxm,posym,limite,counterym,counterxm
if (limite!=True) and(counterym<=150):
canvas.delete(lemario)
counterym=counterym+5
posym=posym-5
posxm=posxm-3
counterxm=counterxm+3
lemario = canvas.create_image(posxm,posym, image=mario14)
v.after(10,saltar3)
if (counterym>=150) or((posym==460)and(((posxm>=0)and(posxm<=300))or((posxm>=500)and(posxm<=800))))or((posym==340)and((posxm>=220)and(posxm<=580)))or((posym==240)and(((posxm>=480)or(posxm<=320)))):
limite=True
if (limite==True)and (counterym>0):
canvas.delete(lemario)
counterym=counterym-5
posym=posym+5
posxm=posxm-3
lemario = canvas.create_image(posxm,posym, image=mario14)
v.after(10,saltar3)
if ((posym==420)and(((posxm>=0)and(posxm<=300))or((posxm>=500)and(posxm<=800)))):
posym=420
counterym=0
elif(posym==310)and(((posxm>=220)and(posxm<=580))):
posym=310
counterym=0
elif ((posym==210)and(((posxm>=0)and(posxm<=330))or((posxm>=480)and(posxm<=800)))):
posym=210
counterym=0
def saltar11():
"""
funcion que permite saltar al personaje luigi sin realizar ningun cambio en su posicion en x, determinando hacia que direccion esta orientado el personaje para realizarlo, tambien determinado por el limite de salto y un contador
"""
global canvas,leluigi,posxl,posyl,limite1,counteryl,estadoizdel
if estadoizdel==1:
if (limite1!=True) and(counteryl<=150):
canvas.delete(leluigi)
counteryl=counteryl+5
posyl=posyl-5
leluigi = canvas.create_image(posxl,posyl, image=luigi4)
v.after(10,saltar11)
if (counteryl>=150)or((posyl==460)and(((posxl>=0)and(posxl<=300))or((posxl>=500)and(posxl<=800))))or((posyl==340)and(((posxl>=220)and(posxl<=580))))or((posyl==240)and(((posxl>=480)or(posxl<=320)))):
limite1=True
if (limite1==True)and (counteryl>0):
canvas.delete(leluigi)
counteryl=counteryl-5
posyl=posyl+5
leluigi = canvas.create_image(posxl,posyl, image=luigi4)
if ((posyl==450)and(((posxl>=0)and(posxl<=300))or((posxl>=500)and(posxl<=800))))or((posyl==330)and(((posxl>=220)and(posxl<=580)))):
posyl=450
counteryl=0
v.after(10,saltar11)
elif estadoizdel==0:
if (limite1!=True) and(counteryl<=150):
canvas.delete(leluigi)
counteryl=counteryl+5
posyl=posyl-5
leluigi = canvas.create_image(posxl,posyl, image=luigi14)
v.after(10,saltar11)
if (counteryl>=150) or((posyl==460)and(((posxl>=0)and(posxl<=300))or((posxl>=500)and(posxl<=800))))or((posyl==340)and(((posxl>=220)and(posxl<=580))))or((posyl==240)and(((posxl>=480)or(posxl<=320)))):
limite1=True
if (limite1==True)and (counteryl>0):
canvas.delete(leluigi)
counteryl=counteryl-5
posyl=posyl+5
leluigi = canvas.create_image(posxl,posyl, image=luigi14)
if ((posyl==450)and(((posxl>=0)and(posxl<=300))or((posxl>=500)and(posxl<=800))))or((posyl==330)and(((posxl>=220)and(posxl<=580)))):
posyl=450
counteryl=0
v.after(10,saltar11)
def saltar21():
"""
Procedimiento que realiza el salto en parabola a la izquierda
"""
global canvas,leluigi,posxl,posyl,limite1,counteryl,counterxl
if (limite1!=True) and(counteryl<=150):
canvas.delete(leluigi)
counteryl=counteryl+5
posyl=posyl-5
posxl=posxl+3
leluigi = canvas.create_image(posxl,posyl, image=luigi4)
v.after(3,saltar21)
if (counteryl>=150) or((posyl==460)and(((posxl>=0)and(posxl<=300))or((posxl>=500)and(posxl<=800))))or((posyl==340)and(((posxl>=220)and(posxl<=580))))or((posyl==80)and(((posxl>=0)and(posxl<=800))))or((posyl==240)and(((posxl>=480)or(posxl<=320)))):
limite1=True
if (limite1==True)and (counteryl>0):
canvas.delete(leluigi)
counteryl=counteryl-5
posyl=posyl+5
posxl=posxl+3
leluigi = canvas.create_image(posxl,posyl, image=luigi4)
v.after(3,saltar21)
if ((posyl==420)and(((posxl>=0)and(posxl<=300))or((posxl>=500)and(posxl<=800)))):
posyl=420
counteryl=0
elif(posyl==310)and(((posxl>=220)and(posxl<=580))):
posyl=310
counteryl=0
elif ((posyl==210)and(((posxl>=0)and(posxl<=330))or((posxl>=480)and(posxl<=800)))):
posyl=210
counteryl=0
def saltar31():
"""
Procedimiento que realiza el salto en parabola a la derecha acordarse de acomodar el pinche codigo
"""
global canvas,leluigi,posxl,posyl,limite1,counteryl,counterxl
if (limite1!=True) and(counteryl<=150):
canvas.delete(leluigi)
counteryl=counteryl+5
posyl=posyl-5
posxl=posxl-3
counterxl=counterxl+3
leluigi = canvas.create_image(posxl,posyl, image=luigi14)
v.after(3,saltar31)
if (counteryl>=150) or((posyl==460)and(((posxl>=0)and(posxl<=300))or((posxl>=500)and(posxl<=800))))or((posyl==340)and(((posxl>=220)and(posxl<=580))))or((posyl==240)and(((posxl>=480)or(posxl<=320)))):
limite1=True
if (limite1==True)and (counteryl>0):
canvas.delete(leluigi)
counteryl=counteryl-5
posyl=posyl+5
posxl=posxl-3
leluigi = canvas.create_image(posxl,posyl, image=luigi14)
v.after(6,saltar31)
if ((posyl==420)and(((posxl>=0)and(posxl<=300))or((posxl>=500)and(posxl<=800)))):
posyl=420
counteryl=0
elif(posyl==310)and(((posxl>=220)and(posxl<=580))):
posyl=310
counteryl=0
elif ((posyl==210)and(((posxl>=0)and(posxl<=330))or((posxl>=480)and(posxl<=800)))):
posyl=210
counteryl=0
def pressed(event):
"""
funcion que recive los eventos del teclado, exactamente de cuando una tecla es presionada y los compara con las teclas asignadas para realizar movimientos en mario,
en esta misma funcion tambien se determinan las caracteristicas para obtener o simular un mapa continuo y se especifica la secuencia de animacion que tiene mario
"""
global canvas,lemario,posxm,posym,limite,counterym,counterxm,estadom,nivel,points,nombre1,estadov1,estadov2,estadov3,score,muestra1,leluigi,posxl,posyl,limite1,counteryl,counterxl,estadol,final
tecla = repr(event.char)
if final!=1:
if(tecla == "'w'"):
presionado[0] = True
if(presionado[2] == True):
limite = False
counterxm=0
counterym=0
saltar2()
elif(presionado[1]==True):
limite = False
counterxm=0
counterym=0
saltar3()
else:
limite = False
counterym=0
saltar()
elif(tecla == "'a'"):
presionado[1] = True
canvas.delete(lemario)
if (((posym<=440) and (posym>=240))or((posym>=460) and (posym<=530))or((posym<=230) and (posym>=80))) and (posxm<0):
posxm=800
if(posym>=460) and (posym<=530):
posym=210
elif(posym<=230) and (posym>=80):
posym=520
lemario = canvas.create_image(posxm,posym, image=mario11)
else:
if estadom==0:
posxm = posxm - 10
if ((posym==420)and(((posxm>=300)and(posxm<=500)))):
posym=520
lemario = canvas.create_image(posxm,posym, image=mario11)
elif ((posym==310)and(((posxm>=580)or(posxm<=220)))):
posym=420
lemario = canvas.create_image(posxm,posym, image=mario11)
elif ((posym==210)and(((posxm>=330)and(posxm<=480)))):
posym=310
lemario = canvas.create_image(posxm,posym, image=mario11)
else:
lemario = canvas.create_image(posxm,posym, image=mario11)
estadom=1
elif estadom==1:
posxm = posxm - 10
if ((posym==420)and(((posxm>=300)and(posxm<=500)))):
posym=520
lemario = canvas.create_image(posxm,posym, image=mario12)
elif ((posym==310)and(((posxm>=580)or(posxm<=220)))):
posym=420
lemario = canvas.create_image(posxm,posym, image=mario12)
elif ((posym==210)and(((posxm>=330)and(posxm<=480)))):
posym=310
lemario = canvas.create_image(posxm,posym, image=mario12)
else:
lemario = canvas.create_image(posxm,posym, image=mario12)
estadom=2
elif estadom==2:
posxm = posxm - 10
if ((posym==420)and(((posxm>=300)and(posxm<=500)))):
posym=520
lemario = canvas.create_image(posxm,posym, image=mario13)
elif ((posym==310)and(((posxm>=580)or(posxm<=220)))):
posym=420
lemario = canvas.create_image(posxm,posym, image=mario13)
elif ((posym==210)and(((posxm>=330)and(posxm<=480)))):
posym=310
lemario = canvas.create_image(posxm,posym, image=mario13)
else:
lemario = canvas.create_image(posxm,posym, image=mario13)
estadom=0
elif(tecla == "'d'"):
presionado[2] = True
canvas.delete(lemario)
if (((posym<=440) and (posym>=240))or((posym>=460) and (posym<=530))or((posym<=230) and (posym>=80))) and (posxm>800):
posxm=0
if(posym>=460) and (posym<=530):
posym=210
elif(posym<=230) and (posym>=80):
posym=520
lemario = canvas.create_image(posxm,posym, image=mario1)
else:
if estadom==0:
posxm = posxm + 10
if ((posym==420)and(((posxm>=300)and(posxm<=500)))):
posym=520
lemario = canvas.create_image(posxm,posym, image=mario1)
elif ((posym==310)and(((posxm>=580)or(posxm<=220)))):
posym=420
lemario = canvas.create_image(posxm,posym, image=mario1)
elif ((posym==210)and(((posxm>=330)and(posxm<=480)))):
posym=310
lemario = canvas.create_image(posxm,posym, image=mario1)
else:
lemario = canvas.create_image(posxm,posym, image=mario1)
estadom=1
elif estadom==1:
posxm = posxm + 10
if ((posym==420)and(((posxm>=300)and(posxm<=500)))):
posym=520
lemario = canvas.create_image(posxm,posym, image=mario2)
elif ((posym==310)and(((posxm>=580)or(posxm<=220)))):
posym=420
lemario = canvas.create_image(posxm,posym, image=mario2)
elif ((posym==210)and(((posxm>=330)and(posxm<=480)))):
posym=310
lemario = canvas.create_image(posxm,posym, image=mario2)
else:
lemario = canvas.create_image(posxm,posym, image=mario2)
estadom=2
elif estadom==2:
posxm = posxm + 10
if ((posym==420)and(((posxm>=300)and(posxm<=500)))):
posym=520
lemario = canvas.create_image(posxm,posym, image=mario3)
elif ((posym==310)and(((posxm>=580)or(posxm<=220)))):
posym=420
lemario = canvas.create_image(posxm,posym, image=mario3)
elif ((posym==210)and(((posxm>=330)and(posxm<=480)))):
posym=310
lemario = canvas.create_image(posxm,posym, image=mario3)
else:
lemario = canvas.create_image(posxm,posym, image=mario3)
estadom=0
elif(tecla == "'g'"):
presionado[3] = True
if parejas==False:
archivo=open('unjugadorg.txt','r')
nombre1=archivo.readlines(1)
archivo.close()
datos=[str(nombre1[0]),"\n",str(points),"\n",str(nivel),"\n",str(estadov1),"\n",str(estadov2),"\n",str(estadov3)]
archivo=open('unjugadorg.txt','w')
archivo.writelines(datos)
archivo.close()
if parejas==True:
archivo=open('dosjugadorg.txt','r')
nombres=archivo.readlines()
nombre1=nombres[0]
nombre2=nombres[1]
archivo.close()
datos1=[str(nombre1),"\n",str(points),"\n",str(nivel),"\n",str(estadov1),"\n",str(estadov2),"\n",str(estadov3),"\n",str(nombre2),"\n",str(pointsl),"\n",str(estadov11),"\n",str(estadov21),"\n",str(estadov31)]
print(datos1)
archivo=open('dosjugadorg.txt','w')
archivo.writelines(datos1)
archivo.close()
archivo=open('dosjugadorg.txt','r')
print(archivo.readlines())
archivo.close()
if parejas==True:
if finall!=1:
if(tecla == "'i'"):
presionado[4] = True
if(presionado[5] == True):
limite1 = False
counterxl=0
counteryl=0
saltar31()
elif(presionado[6]==True):
limite1 = False
counterxl=0
counteryl=0
saltar21()
else:
limite1 = False
counteryl=0
saltar11()
elif(tecla == "'j'"):
presionado[5] = True
canvas.delete(leluigi)
if (((posyl<=440) and (posyl>=240))or((posyl>=460) and (posyl<=530))or((posyl<=230) and (posyl>=80))) and (posxl<0):
posxl=800
if(posyl>=460) and (posyl<=530):
posyl=210
elif(posyl<=230) and (posyl>=80):
posyl=520
leluigi = canvas.create_image(posxl,posyl, image=luigi11)
else:
if estadol==0:
posxl = posxl - 10
if ((posyl==420)and(((posxl>=300)and(posxl<=500)))):
posyl=520
leluigi = canvas.create_image(posxl,posyl, image=luigi11)
elif ((posyl==310)and(((posxl>=580)or(posxl<=220)))):
posyl=420
leluigi = canvas.create_image(posxl,posyl, image=luigi11)
elif ((posyl==210)and(((posxl>=330)and(posxl<=480)))):
posyl=310
leluigi = canvas.create_image(posxl,posyl, image=luigi11)
else:
leluigi = canvas.create_image(posxl,posyl, image=luigi11)
estadol=1
elif estadol==1:
posxl = posxl - 10
if ((posyl==420)and(((posxl>=300)and(posxl<=500)))):
posyl=520
leluigi = canvas.create_image(posxl,posyl, image=luigi12)
elif ((posyl==310)and(((posxl>=580)or(posxl<=220)))):
posyl=420
leluigi = canvas.create_image(posxl,posyl, image=luigi12)
elif ((posyl==210)and(((posxl>=330)and(posxl<=480)))):
posyl=310
leluigi = canvas.create_image(posxl,posyl, image=luigi12)
else:
leluigi = canvas.create_image(posxl,posyl, image=luigi12)
estadol=2
elif estadol==2:
posxl = posxl - 10
if ((posyl==420)and(((posxl>=300)and(posxl<=500)))):
posyl=520
leluigi = canvas.create_image(posxl,posyl, image=luigi13)
elif ((posyl==310)and(((posxl>=580)or(posxl<=220)))):
posyl=420
leluigi = canvas.create_image(posxl,posyl, image=luigi13)
elif ((posyl==210)and(((posxl>=330)and(posxl<=480)))):
posyl=310
leluigi = canvas.create_image(posxl,posyl, image=luigi13)
else:
leluigi = canvas.create_image(posxl,posyl, image=luigi13)
estadol=0
elif(tecla == "'l'"):
presionado[6] = True
canvas.delete(leluigi)
if (((posyl<=440) and (posyl>=240))or((posyl>=460) and (posyl<=530))or((posyl<=230) and (posyl>=80))) and (posxl>800):
posxl=0
if(posyl>=460) and (posyl<=530):
posyl=210
elif(posyl<=230) and (posyl>=80):
posyl=520
leluigi = canvas.create_image(posxl,posyl, image=luigi1)
else:
if estadol==0:
posxl = posxl + 10
if ((posyl==420)and(((posxl>=300)and(posxl<=500)))):
posyl=520
leluigi = canvas.create_image(posxl,posyl, image=luigi1)
elif ((posyl==310)and(((posxl>=580)or(posxl<=220)))):
posyl=420
leluigi = canvas.create_image(posxl,posyl, image=luigi1)
elif ((posyl==210)and(((posxl>=330)and(posxl<=480)))):
posyl=310
leluigi = canvas.create_image(posxl,posyl, image=luigi1)
else:
leluigi = canvas.create_image(posxl,posyl, image=luigi1)
estadol=1
elif estadol==1:
posxl = posxl + 10
if ((posyl==420)and(((posxl>=300)and(posxl<=500)))):
posyl=520
leluigi = canvas.create_image(posxl,posyl, image=luigi2)
elif ((posyl==310)and(((posxl>=580)or(posxl<=220)))):
posyl=420
leluigi = canvas.create_image(posxl,posyl, image=luigi2)
elif ((posyl==210)and(((posxl>=330)and(posxl<=480)))):
posyl=310
leluigi = canvas.create_image(posxl,posyl, image=luigi2)
else:
leluigi = canvas.create_image(posxl,posyl, image=luigi2)
estadol=2
elif estadol==2:
posxl = posxl + 10
if ((posyl==420)and(((posxl>=300)and(posxl<=500)))):
posyl=520
leluigi = canvas.create_image(posxl,posyl, image=luigi3)
elif ((posyl==310)and(((posxl>=580)or(posxl<=220)))):
posyl=420
leluigi = canvas.create_image(posxl,posyl, image=luigi3)
elif ((posyl==210)and(((posxl>=330)and(posxl<=480)))):
posyl=310
leluigi = canvas.create_image(posxl,posyl, image=luigi3)
else:
leluigi = canvas.create_image(posxl,posyl, image=luigi3)
estadol=0
def released(event):
"""
esta funcion recive eventos de teclado exactamente cuando se ha dejado de presionar una tecla, asignando valores booleanos para su interpretacion en una lista
"""
global canvas,lemario,posxm,posym,limite,estadom,estadoizdem
tecla = repr(event.char)
if(tecla == "'w'"):
presionado[0] = False
elif(tecla == "'a'"):
estadoizdem=0
presionado[1] = False
elif(tecla == "'d'"):
estadoizdem=1
presionado[2] = False
elif(tecla == "'g'"):
presionado[3] = False
elif(tecla == "'i'"):
presionado[4] = False
elif(tecla == "'j'"):
estadoizdel=0
presionado[5] = False
elif(tecla == "'l'"):
estadoizdel=1
presionado[6] = False
canvas = tkinter.Canvas(v,bg="black",width=800,height=630)
for char in ["w","a","d","g","i","j","l"]:
canvas.bind("<KeyPress-%s>" % char, pressed)
canvas.bind("<KeyRelease-%s>" % char, released)
canvas.focus_set()
canvas.pack()
#definicion de las diferentes variables de imagenes que contienen desde enemigos hasta mario y sus animaciones
imagen = tkinter.PhotoImage(file='Mario_Bros(1).gif')
mario1=tkinter.PhotoImage(file='mario1.png')
mario2=tkinter.PhotoImage(file='mario2.png')
mario3=tkinter.PhotoImage(file='mario3.png')
mario4=tkinter.PhotoImage(file='mario4.png')
mario11=tkinter.PhotoImage(file='mario11.png')
mario12=tkinter.PhotoImage(file='mario12.png')
mario13=tkinter.PhotoImage(file='mario13.png')
mario14=tkinter.PhotoImage(file='mario14.png')
luigi1=tkinter.PhotoImage(file='luigi2.png')
luigi2=tkinter.PhotoImage(file='luigi1.png')
luigi3=tkinter.PhotoImage(file='luigi3.png')
luigi4=tkinter.PhotoImage(file='luigi4.png')
luigi11=tkinter.PhotoImage(file='luigi11.png')
luigi12=tkinter.PhotoImage(file='luigi12.png')
luigi13=tkinter.PhotoImage(file='luigi13.png')
luigi14=tkinter.PhotoImage(file='luigi14.png')
enemy1=tkinter.PhotoImage(file='enemigo1.png')
enemy2=tkinter.PhotoImage(file='enemigo2.png')
nube2=tkinter.PhotoImage(file='nube.png')
nube1=tkinter.PhotoImage(file='nube1.png')
goback=tkinter.PhotoImage(file='back.png')
life=tkinter.PhotoImage(file='vida.png')
muestra1=tkinter.Label(v,font=("Arial"),text=nombre1,width=20,bg=("black"),fg=("white"))
score=tkinter.Label(v,font=("Arial"),text=str(points),width=20,bg=("black"),fg=("white"))
scorel=tkinter.Label(v,font=("Arial"),text=str(pointsl),width=20,bg=("black"),fg=("white"))
#creacion de canvas
canvas.create_image(400,315, image=imagen)
#creacion de enemigos como imagenes y de las labels que se utilizaran para representar las vidas
lemario = canvas.create_image(posxm,posym, image=mario1)
leluigi = canvas.create_image(posxl,posyl, image=luigi1)
if parejas!=True:
canvas.delete(leluigi)
enemy=canvas.create_image(posxe,posye, image=enemy1)
enemy11=canvas.create_image(posxe1,posye1, image=enemy1)
enemy12=canvas.create_image(posxe1,posye1, image=enemy1)
enemy13=canvas.create_image(posxe1,posye1, image=enemy1)
nube=canvas.create_image(posxe4,posye4, image=nube1)
nube11=canvas.create_image(posxe5,posye5, image=nube1)
nube12=canvas.create_image(posxe6,posye6, image=nube2)
nube13=canvas.create_image(posxe7,posye7, image=nube2)
enemy14=canvas.create_image(posxe8,posye8, image=enemy1)
enemy15=canvas.create_image(posxe9,posye9, image=enemy1)
enemy16=canvas.create_image(posxe10,posye10, image=enemy1)
enemy17=canvas.create_image(posxe11,posye11, image=enemy1)
nube14=canvas.create_image(posxe12,posye12, image=nube1)
nube15=canvas.create_image(posxe13,posye13, image=nube1)
nube16=canvas.create_image(posxe14,posye14, image=nube2)
nube17=canvas.create_image(posxe15,posye15, image=nube2)
vida3=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida1=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida2=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida31=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida11=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida21=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
def mover():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe,enemy,posye,posym,posxm,estadoe,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas,parejas
canvas.delete(enemy)
posxe=posxe-1
if (((posxm<=(posxe+30))and(posxm>=(posxe-30)))and((posym==(posye+50))or(posym==(posye-45)))):
estadoe=0
puntaje(100)
empezar()
if (((posxm<=(posxe+30))and(posxm>=(posxe-30)))and(posym==posye))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if (((posxl<=(posxe+30))and(posxl>=(posxe-30)))and((posyl==(posye+50))or(posyl==(posye-45)))):
estadoe=0
puntajel(100)
empezar()
if (((posxl<=(posxe+30))and(posxl>=(posxe-30)))and(posyl==posye))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe!=0:
if (((posye<=440) and (posye>=240))or((posye>=460) and (posye<=530))or((posye<=230) and (posye>=80))) and (posxe<0):
posxe=800
if(posye>=460) and (posye<=530):
puntaje(-100)
if parejas==True:
puntajel(-100)
posye=210
elif(posye<=230) and (posye>=80):
posye=520
if ((posye==420)and(((posxe>=300)and(posxe<=500)))):
posye=520
enemy=canvas.create_image(posxe,posye, image=enemy1)
elif ((posye==310)and(((posxe>=580)or(posxe<=220)))):
posye=420
enemy=canvas.create_image(posxe,posye, image=enemy1)
elif ((posye==210)and(((posxe>=330)and(posxe<=480)))):
posye=310
enemy=canvas.create_image(posxe,posye, image=enemy1)
else:
enemy=canvas.create_image(posxe,posye, image=enemy1)
v.after(10,mover)
def mover1():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe1,enemy11,posye1,posym,posxm,estadoe1,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(enemy11)
posxe1=posxe1-1
if ((posxm<=(posxe1+30))and(posxm>=(posxe1-30)))and((posym==(posye1+50))or(posym==(posye1-45))):
estadoe1=0
puntaje(100)
empezar()
if (((posxm<=(posxe1+30))and(posxm>=(posxe1-30)))and(posym==posye1))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe1+30))and(posxl>=(posxe1-30)))and((posyl==(posye1+50))or(posyl==(posye1-45))):
estadoe1=0
puntajel(100)
empezar()
if (((posxl<=(posxe1+30))and(posxl>=(posxe1-30)))and(posyl==posye1))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe1!=0:
if (((posye1<=440) and (posye1>=240))or((posye1>=460) and (posye1<=530))or((posye1<=230) and (posye1>=80))) and (posxe1<0):
posxe1=800
if(posye1>=460) and (posye1<=530):
puntaje(-100)
if parejas==True:
puntajel(-100)
posye1=210
elif(posye1<=230) and (posye1>=80):
posye1=520
if ((posye1==420)and(((posxe1>=300)and(posxe1<=500)))):
posye1=520
enemy11=canvas.create_image(posxe1,posye1, image=enemy1)
elif ((posye1==310)and(((posxe1>=580)or(posxe1<=220)))):
posye1=420
enemy11=canvas.create_image(posxe1,posye1, image=enemy1)
elif ((posye1==210)and(((posxe1>=330)and(posxe1<=480)))):
posye1=310
enemy11=canvas.create_image(posxe1,posye1, image=enemy1)
else:
enemy11=canvas.create_image(posxe1,posye1, image=enemy1)
v.after(10,mover1)
def mover2():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe2,enemy12,posye2,posym,posxm,estadoe2,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(enemy12)
posxe2=posxe2+1
if ((posxm<=(posxe2+30))and(posxm>=(posxe2-30)))and((posym==(posye2+50))or(posym==(posye2-45))):
estadoe2=0
puntaje(100)
empezar()
if (((posxm<=(posxe2+30))and(posxm>=(posxe2-30)))and(posym==posye2))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe2+30))and(posxl>=(posxe2-30)))and((posyl==(posye2+50))or(posyl==(posye2-45))):
estadoe2=0
puntajel(100)
empezar()
if (((posxl<=(posxe2+30))and(posxl>=(posxe2-30)))and(posyl==posye2))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe2!=0:
if (((posye2<=440) and (posye2>=240))or((posye2>=460) and (posye2<=530))or((posye2<=230) and (posye2>=80))) and (posxe2>800):
posxe2=0
if(posye2>=460) and (posye2<=530):
puntaje(-100)
if parejas==True:
puntajel(-100)
posye2=210
elif(posye2<=230) and (posye2>=80):
posye2=520
if ((posye2==420)and(((posxe2>=300)and(posxe2<=500)))):
posye2=520
enemy12=canvas.create_image(posxe2,posye2, image=enemy2)
elif ((posye2==310)and(((posxe2>=580)or(posxe2<=220)))):
posye2=420
enemy12=canvas.create_image(posxe2,posye2, image=enemy2)
elif ((posye2==210)and(((posxe2>=330)and(posxe2<=480)))):
posye2=310
enemy12=canvas.create_image(posxe2,posye2, image=enemy2)
else:
enemy12=canvas.create_image(posxe2,posye2, image=enemy2)
v.after(10,mover2)
def mover3():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe3,enemy13,posye3,posym,posxm,estadoe3,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(enemy13)
posxe3=posxe3+1
if ((posxm<=(posxe3+30))and(posxm>=(posxe3-30)))and((posym==(posye3+50))or(posym==(posye3-45))):
estadoe3=0
puntaje(100)
empezar()
if (((posxm<=(posxe3+30))and(posxm>=(posxe3-30)))and(posym==posye3))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe3+30))and(posxl>=(posxe3-30)))and((posyl==(posye3+50))or(posyl==(posye3-45))):
estadoe3=0
puntajel(100)
empezar()
if (((posxl<=(posxe3+30))and(posxl>=(posxe3-30)))and(posyl==posye3))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe3!=0:
if (((posye3<=440) and (posye3>=240))or((posye3>=460) and (posye3<=530))or((posye3<=230) and (posye3>=80))) and (posxe3>800):
posxe3=0
if(posye3>=460) and (posye3<=530):
puntaje(-100)
if parejas==True:
puntajel(-100)
posye3=210
elif(posye3<=230) and (posye3>=80):
posye3=520
if ((posye3==420)and(((posxe3>=300)and(posxe3<=500)))):
posye3=520
enemy13=canvas.create_image(posxe3,posye3, image=enemy2)
elif ((posye3==310)and(((posxe3>=580)or(posxe3<=220)))):
posye3=420
enemy13=canvas.create_image(posxe3,posye3, image=enemy2)
elif ((posye3==210)and(((posxe3>=330)and(posxe3<=480)))):
posye3=310
enemy13=canvas.create_image(posxe3,posye3, image=enemy2)
else:
enemy13=canvas.create_image(posxe3,posye3, image=enemy2)
v.after(10,mover3)
def mover4():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe4,nube,posye4,posym,posxm,estadoe4,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(nube)
posxe4=posxe4-1
if ((posxm<=(posxe4+30))and(posxm>=(posxe4-30)))and((posym==(posye4+50))or(posym==(posye4-45))):
estadoe4=0
puntaje(150)
empezar()
if (((posxm<=(posxe4+30))and(posxm>=(posxe4-30)))and(posym==posye4))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe4+30))and(posxl>=(posxe4-30)))and((posyl==(posye4+50))or(posyl==(posye4-45))):
estadoe4=0
puntajel(150)
empezar()
if (((posxl<=(posxe4+30))and(posxl>=(posxe4-30)))and(posyl==posye4))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe4!=0:
if (((posye4<=440) and (posye4>=240))or((posye4>=460) and (posye4<=530))or((posye4<=230) and (posye4>=80))) and (posxe4<0):
posxe4=800
if(posye4>=460) and (posye4<=530):
puntaje(-100)
if parejas==True:
puntajel(-100)
posye4=210
elif(posye4<=230) and (posye4>=80):
posye4=520
if ((posye4==420)and(((posxe4>=300)and(posxe4<=500)))):
posye4=520
nube=canvas.create_image(posxe4,posye4, image=nube1)
elif ((posye4==310)and(((posxe4>=580)or(posxe4<=220)))):
posye4=420
nube=canvas.create_image(posxe4,posye4, image=nube1)
elif ((posye4==210)and(((posxe4>=330)and(posxe4<=480)))):
posye4=310
nube=canvas.create_image(posxe4,posye4, image=nube1)
else:
nube=canvas.create_image(posxe4,posye4, image=nube1)
v.after(10,mover4)
def mover5():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe5,nube11,posye5,posym,posxm,estadoe5,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(nube11)
posxe5=posxe5-1
if ((posxm<=(posxe5+30))and(posxm>=(posxe5-30)))and((posym==(posye5+50))or(posym==(posye5-45))):
estadoe5=0
puntaje(150)
empezar()
if (((posxm<=(posxe5+30))and(posxm>=(posxe5-30)))and(posym==posye5))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe5+30))and(posxl>=(posxe5-30)))and((posyl==(posye5+50))or(posyl==(posye5-45))):
estadoe5=0
puntajel(150)
empezar()
if (((posxl<=(posxe5+30))and(posxl>=(posxe5-30)))and(posyl==posye5))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe5!=0:
if (((posye5<=440) and (posye5>=240))or((posye5>=460) and (posye5<=530))or((posye5<=230) and (posye5>=80))) and (posxe5<0):
posxe5=800
if(posye5>=460) and (posye5<=530):
puntaje(-100)
if parejas==True:
puntajel(-100)
posye5=210
elif(posye5<=230) and (posye5>=80):
posye5=520
if ((posye5==420)and(((posxe5>=300)and(posxe5<=500)))):
posye5=520
nube11=canvas.create_image(posxe5,posye5, image=nube1)
elif ((posye5==310)and(((posxe5>=580)or(posxe5<=220)))):
posye5=420
nube11=canvas.create_image(posxe5,posye5, image=nube1)
elif ((posye5==210)and(((posxe5>=330)and(posxe5<=480)))):
posye5=310
nube11=canvas.create_image(posxe5,posye5, image=nube1)
else:
nube11=canvas.create_image(posxe5,posye5, image=nube1)
v.after(10,mover5)
def mover6():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe6,nube12,posye6,posym,posxm,estadoe6,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(nube12)
posxe6=posxe6+1
if ((posxm<=(posxe6+30))and(posxm>=(posxe6-30)))and((posym==(posye6+50))or(posym==(posye6-45))):
estadoe6=0
puntaje(150)
empezar()
if (((posxm<=(posxe6+30))and(posxm>=(posxe6-30)))and(posym==posye6))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe6+30))and(posxl>=(posxe6-30)))and((posyl==(posye6+50))or(posyl==(posye6-45))):
estadoe6=0
puntajel(150)
empezar()
if (((posxl<=(posxe6+30))and(posxl>=(posxe6-30)))and(posyl==posye6))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe6!=0:
if (((posye6<=440) and (posye6>=240))or((posye6>=460) and (posye6<=530))or((posye6<=230) and (posye6>=80))) and (posxe6>800):
posxe6=0
if(posye6>=460) and (posye6<=530):
puntaje(-100)
if parejas==True:
puntajel(-100)
posye6=210
elif(posye6<=230) and (posye6>=80):
posye6=520
if ((posye6==420)and(((posxe6>=300)and(posxe6<=500)))):
posye6=520
nube12=canvas.create_image(posxe6,posye6, image=nube2)
elif ((posye6==310)and(((posxe6>=580)or(posxe6<=220)))):
posye6=420
nube12=canvas.create_image(posxe6,posye6, image=nube2)
elif ((posye6==210)and(((posxe6>=330)and(posxe6<=480)))):
posye6=310
nube12=canvas.create_image(posxe6,posye6, image=nube2)
else:
nube12=canvas.create_image(posxe6,posye6, image=nube2)
v.after(10,mover6)
def mover7():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe7,nube13,posye7,posym,posxm,estadoe7,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(nube13)
posxe7=posxe7+1
if ((posxm<=(posxe7+30))and(posxm>=(posxe7-30)))and((posym==(posye7+50))or(posym==(posye7-45))):
estadoe7=0
puntaje(150)
empezar()
if (((posxm<=(posxe7+30))and(posxm>=(posxe7-30)))and(posym==posye7))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe7+30))and(posxl>=(posxe7-30)))and((posyl==(posye7+50))or(posyl==(posye7-45))):
estadoe7=0
puntajel(150)
empezar()
if (((posxl<=(posxe7+30))and(posxl>=(posxe7-30)))and(posyl==posye7))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe7!=0:
if (((posye7<=440) and (posye7>=240))or((posye7>=460) and (posye7<=530))or((posye7<=230) and (posye7>=80))) and (posxe7>800):
posxe7=0
if(posye7>=460) and (posye7<=530):
posye7=210
puntaje(-100)
if parejas==True:
puntajel(-100)
elif(posye7<=230) and (posye7>=80):
posye7=520
if ((posye7==420)and(((posxe7>=300)and(posxe7<=500)))):
posye7=520
nube13=canvas.create_image(posxe7,posye7, image=nube2)
elif ((posye7==310)and(((posxe7>=580)or(posxe7<=220)))):
posye7=420
nube13=canvas.create_image(posxe7,posye7, image=nube2)
elif ((posye7==210)and(((posxe7>=330)and(posxe7<=480)))):
posye7=310
nube13=canvas.create_image(posxe7,posye7, image=nube2)
else:
nube13=canvas.create_image(posxe7,posye7, image=nube2)
v.after(10,mover7)
def mover8():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe8,enemy15,posye8,posym,posxm,estadoe8,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(enemy15)
posxe8=posxe8-1
if ((posxm<=(posxe8+30))and(posxm>=(posxe8-30)))and((posym==(posye8+50))or(posym==(posye8-45))):
estadoe8=0
puntaje(100)
empezar()
if (((posxm<=(posxe8+30))and(posxm>=(posxe8-30)))and(posym==posye8))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe8+30))and(posxl>=(posxe8-30)))and((posyl==(posye8+50))or(posyl==(posye8-45))):
estadoe8=0
puntajel(100)
empezar()
if (((posxl<=(posxe8+30))and(posxl>=(posxe8-30)))and(posyl==posye8))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe8!=0:
if (((posye8<=440) and (posye8>=240))or((posye8>=460) and (posye8<=530))or((posye8<=230) and (posye8>=80))) and (posxe8<0):
posxe8=800
if(posye8>=460) and (posye8<=530):
posye8=210
puntaje(-100)
if parejas==True:
puntajel(-100)
elif(posye8<=230) and (posye8>=80):
posye8=520
if ((posye8==420)and(((posxe8>=300)and(posxe8<=500)))):
posye8=520
enemy15=canvas.create_image(posxe8,posye8, image=enemy1)
elif ((posye8==310)and(((posxe8>=580)or(posxe8<=220)))):
posye8=420
enemy15=canvas.create_image(posxe8,posye8, image=enemy1)
elif ((posye8==210)and(((posxe8>=330)and(posxe8<=480)))):
posye8=310
enemy15=canvas.create_image(posxe8,posye8, image=enemy1)
else:
enemy15=canvas.create_image(posxe8,posye8, image=enemy1)
v.after(10,mover8)
def mover9():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe9,enemy14,posye9,posym,posxm,estadoe9,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(enemy14)
posxe9=posxe9-1
if ((posxm<=(posxe9+30))and(posxm>=(posxe9-30)))and((posym==(posye9+50))or(posym==(posye9-45))):
estadoe9=0
puntaje(100)
empezar()
if (((posxm<=(posxe9+30))and(posxm>=(posxe9-30)))and(posym==posye9))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe9+30))and(posxl>=(posxe9-30)))and((posyl==(posye9+50))or(posyl==(posye9-45))):
estadoe9=0
puntajel(100)
empezar()
if (((posxl<=(posxe9+30))and(posxl>=(posxe9-30)))and(posyl==posye9))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe9!=0:
if (((posye9<=440) and (posye9>=240))or((posye9>=460) and (posye9<=530))or((posye9<=230) and (posye9>=80))) and (posxe9<0):
posxe9=800
if(posye9>=460) and (posye9<=530):
posye9=210
puntaje(-100)
if parejas==True:
puntajel(-100)
elif(posye9<=230) and (posye9>=80):
posye9=520
if ((posye9==420)and(((posxe9>=300)and(posxe9<=500)))):
posye9=520
enemy14=canvas.create_image(posxe9,posye9, image=enemy1)
elif ((posye9==310)and(((posxe9>=580)or(posxe9<=220)))):
posye9=420
enemy14=canvas.create_image(posxe9,posye9, image=enemy1)
elif ((posye9==210)and(((posxe9>=330)and(posxe9<=480)))):
posye9=310
enemy14=canvas.create_image(posxe9,posye9, image=enemy1)
else:
enemy14=canvas.create_image(posxe9,posye9, image=enemy1)
v.after(10,mover9)
def mover10():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe10,enemy16,posye10,posym,posxm,estadoe10,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(enemy16)
posxe10=posxe10+1
if ((posxm<=(posxe10+30))and(posxm>=(posxe10-30)))and((posym==(posye10+50))or(posym==(posye10-45))):
estadoe10=0
puntaje(100)
empezar()
if (((posxm<=(posxe10+30))and(posxm>=(posxe10-30)))and(posym==posye10))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe10+30))and(posxl>=(posxe10-30)))and((posyl==(posye10+50))or(posyl==(posye10-45))):
estadoe10=0
puntajel(100)
empezar()
if (((posxl<=(posxe10+30))and(posxl>=(posxe10-30)))and(posyl==posye10))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe10!=0:
if (((posye10<=440) and (posye10>=240))or((posye10>=460) and (posye10<=530))or((posye10<=230) and (posye10>=80))) and (posxe10>800):
posxe10=0
if(posye10>=460) and (posye10<=530):
posye10=210
puntaje(-100)
if parejas==True:
puntajel(-100)
elif(posye10<=230) and (posye10>=80):
posye10=520
if ((posye10==420)and(((posxe10>=300)and(posxe10<=500)))):
posye10=520
enemy16=canvas.create_image(posxe10,posye10, image=enemy2)
elif ((posye10==310)and(((posxe10>=580)or(posxe10<=220)))):
posye10=420
enemy16=canvas.create_image(posxe10,posye10, image=enemy2)
elif ((posye10==210)and(((posxe10>=330)and(posxe10<=480)))):
posye10=310
enemy16=canvas.create_image(posxe10,posye10, image=enemy2)
else:
enemy16=canvas.create_image(posxe10,posye10, image=enemy2)
v.after(10,mover10)
def mover11():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe11,enemy17,posye11,posym,posxm,estadoe11,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(enemy17)
posxe11=posxe11+1
if ((posxm<=(posxe11+30))and(posxm>=(posxe11-30)))and((posym==(posye11+50))or(posym==(posye11-45))):
estadoe11=0
puntaje(100)
empezar()
if (((posxm<=(posxe11+30))and(posxm>=(posxe11-30)))and(posym==posye11))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe11+30))and(posxl>=(posxe11-30)))and((posyl==(posye11+50))or(posyl==(posye11-45))):
estadoe11=0
puntajel(100)
empezar()
if (((posxl<=(posxe11+30))and(posxl>=(posxe11-30)))and(posyl==posye11))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe11!=0:
if (((posye11<=440) and (posye11>=240))or((posye11>=460) and (posye11<=530))or((posye11<=230) and (posye11>=80))) and (posxe11>800):
posxe11=0
if(posye11>=460) and (posye11<=530):
posye11=210
puntaje(-100)
if parejas==True:
puntajel(-100)
elif(posye11<=230) and (posye11>=80):
posye11=520
if ((posye11==420)and(((posxe11>=300)and(posxe11<=500)))):
posye11=520
enemy17=canvas.create_image(posxe11,posye11, image=enemy2)
elif ((posye11==310)and(((posxe11>=580)or(posxe11<=220)))):
posye11=420
enemy17=canvas.create_image(posxe11,posye11, image=enemy2)
elif ((posye11==210)and(((posxe11>=330)and(posxe11<=480)))):
posye11=310
enemy17=canvas.create_image(posxe11,posye11, image=enemy2)
else:
enemy17=canvas.create_image(posxe11,posye11, image=enemy2)
v.after(10,mover11)
def mover12():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe12,nube14,posye12,posym,posxm,estadoe12,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(nube14)
posxe12=posxe12-1
if ((posxm<=(posxe12+30))and(posxm>=(posxe12-30)))and((posym==(posye12+50))or(posym==(posye12-45))):
estadoe12=0
puntaje(150)
empezar()
if (((posxm<=(posxe12+30))and(posxm>=(posxe12-30)))and(posym==posye12))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe12+30))and(posxl>=(posxe12-30)))and((posyl==(posye12+50))or(posyl==(posye12-45))):
estadoe12=0
puntajel(150)
empezar()
if (((posxl<=(posxe12+30))and(posxl>=(posxe12-30)))and(posyl==posye12))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe12!=0:
if (((posye12<=440) and (posye12>=240))or((posye12>=460) and (posye12<=530))or((posye12<=230) and (posye12>=80))) and (posxe12<0):
posxe12=800
if(posye12>=460) and (posye12<=530):
posye12=210
puntaje(-100)
if parejas==True:
puntajel(-100)
elif(posye12<=230) and (posye12>=80):
posye12=520
if ((posye12==420)and(((posxe12>=300)and(posxe12<=500)))):
posye12=520
nube14=canvas.create_image(posxe12,posye12, image=nube1)
elif ((posye12==310)and(((posxe12>=580)or(posxe12<=220)))):
posye12=420
nube14=canvas.create_image(posxe12,posye12, image=nube1)
elif ((posye12==210)and(((posxe12>=330)and(posxe12<=480)))):
posye12=310
nube14=canvas.create_image(posxe12,posye12, image=nube1)
else:
nube14=canvas.create_image(posxe12,posye12, image=nube1)
v.after(10,mover12)
def mover13():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe13,nube15,posye13,posym,posxm,estadoe13,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(nube15)
posxe13=posxe13-1
if ((posxm<=(posxe13+30))and(posxm>=(posxe13-30)))and((posym==(posye13+50))or(posym==(posye13-45))):
estadoe13=0
puntaje(150)
empezar()
if (((posxm<=(posxe13+30))and(posxm>=(posxe13-30)))and(posym==posye13))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe13+30))and(posxl>=(posxe13-30)))and((posyl==(posye13+50))or(posyl==(posye13-45))):
estadoe13=0
puntajel(150)
empezar()
if (((posxl<=(posxe13+30))and(posxl>=(posxe13-30)))and(posyl==posye13))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe13!=0:
if (((posye13<=440) and (posye13>=240))or((posye13>=460) and (posye13<=530))or((posye13<=230) and (posye13>=80))) and (posxe13<0):
posxe13=800
if(posye13>=460) and (posye13<=530):
puntaje(-100)
if parejas==True:
puntajel(-100)
posye13=210
elif(posye13<=230) and (posye13>=80):
posye13=520
if ((posye13==420)and(((posxe13>=300)and(posxe13<=500)))):
posye13=520
nube15=canvas.create_image(posxe13,posye13, image=nube1)
elif ((posye13==310)and(((posxe13>=580)or(posxe13<=220)))):
posye13=420
nube15=canvas.create_image(posxe13,posye13, image=nube1)
elif ((posye13==210)and(((posxe13>=330)and(posxe13<=480)))):
posye13=310
nube15=canvas.create_image(posxe13,posye13, image=nube1)
else:
nube15=canvas.create_image(posxe13,posye13, image=nube1)
v.after(10,mover13)
def mover14():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe14,nube16,posye14,posym,posxm,estadoe14,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(nube16)
posxe14=posxe14+1
if ((posxm<=(posxe14+30))and(posxm>=(posxe14-30)))and((posym==(posye14+50))or(posym==(posye14-45))):
estadoe14=0
puntaje(150)
empezar()
if (((posxm<=(posxe14+30))and(posxm>=(posxe14-30)))and(posym==posye14))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe14+30))and(posxl>=(posxe14-30)))and((posyl==(posye14+50))or(posyl==(posye14-45))):
estadoe14=0
puntajel(150)
empezar()
if (((posxl<=(posxe14+30))and(posxl>=(posxe14-30)))and(posyl==posye14))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe14!=0:
if (((posye14<=440) and (posye14>=240))or((posye14>=460) and (posye14<=530))or((posye14<=230) and (posye14>=80))) and (posxe14>800):
posxe14=0
if(posye14>=460) and (posye14<=530):
puntaje(-100)
if parejas==True:
puntajel(-100)
posye14=210
elif(posye14<=230) and (posye14>=80):
posye14=520
if ((posye14==420)and(((posxe14>=300)and(posxe14<=500)))):
posye14=520
nube16=canvas.create_image(posxe14,posye14, image=nube2)
elif ((posye14==310)and(((posxe14>=580)or(posxe14<=220)))):
posye14=420
nube16=canvas.create_image(posxe14,posye14, image=nube2)
elif ((posye14==210)and(((posxe14>=330)and(posxe14<=480)))):
posye14=310
nube16=canvas.create_image(posxe14,posye14, image=nube2)
else:
nube16=canvas.create_image(posxe14,posye14, image=nube2)
v.after(10,mover14)
def mover15():
"""
esta funcion realiza el movimiento de un enemigo, haciendo tambien la simulacion de mapa continuo en este y los diferentes tipos de colisiones que puede tener desde matar
a mario y morir a manos de este
"""
global posxe15,nube17,posye15,posym,posxm,estadoe15,vida3,vida1,vida2,counterym,posxl,posyl,counteryl,vida31,vida11,vida21,parejas
canvas.delete(nube17)
posxe15=posxe15+1
if ((posxm<=(posxe15+30))and(posxm>=(posxe15-30)))and((posym==(posye15+50))or(posym==(posye15-45))):
estadoe15=0
puntaje(150)
empezar()
if (((posxm<=(posxe15+30))and(posxm>=(posxe15-30)))and(posym==posye15))and (counterym==0):
posxm = 400
posym = 520
quitarvida()
if ((posxl<=(posxe15+30))and(posxl>=(posxe15-30)))and((posyl==(posye15+50))or(posyl==(posye15-45))):
estadoe15=0
puntajel(150)
empezar()
if (((posxl<=(posxe15+30))and(posxl>=(posxe15-30)))and(posyl==posye15))and (counteryl==0):
posxl = 400
posyl = 520
quitarvidal()
if estadoe15!=0:
if (((posye15<=440) and (posye15>=240))or((posye15>=460) and (posye15<=530))or((posye15<=230) and (posye15>=80))) and (posxe15>800):
posxe15=0
if(posye15>=460) and (posye15<=530):
puntaje(-100)
if parejas==True:
puntajel(-100)
posye15=210
elif(posye15<=230) and (posye15>=80):
posye15=520
if ((posye15==420)and(((posxe15>=300)and(posxe15<=500)))):
posye15=520
nube17=canvas.create_image(posxe15,posye15, image=nube2)
elif ((posye15==310)and(((posxe15>=580)or(posxe15<=220)))):
posye15=420
nube17=canvas.create_image(posxe15,posye15, image=nube2)
elif ((posye15==210)and(((posxe15>=330)and(posxe15<=480)))):
posye15=310
nube17=canvas.create_image(posxe15,posye15, image=nube2)
else:
nube17=canvas.create_image(posxe15,posye15, image=nube2)
v.after(10,mover15)
def ganar():
"""
funcion que da por terminado el juego al haber ganado y dando como ultima opcion el salir de este
"""
global v,final,finall
final=0
finall=0
v.withdraw
h=tkinter.Toplevel(v)
canvas3 = tkinter.Canvas(h,width=600,height=450)
gb=tkinter.PhotoImage(file='won.png')
canvas3.create_image(300,225, image=gb)
canvas3.focus_set()
canvas3.pack()
salir=tkinter.Button(h,text="Salir",font=("Agency FB",30),command=v.destroy,width=10,height=(1),bg=("blue"),fg=("white"))
salir.place(x=325,y=225)
h.resizable(0,0)
h.mainloop()
def empezar():
"""
esta funcion es la superior a todas las que realizan el movimiento de los enemigos, ya que esta da las direcctrices basadas en el nivel en el que se encuentra siendo estos ultimos
son reglamentados por el puntaje actual del jugador
"""
global nivel,posxe,posye,estadoe,posxe1,posye1,estadoe1,posxe2,posye2,estadoe2,posxe3,posye3,estadoe3,posxe4,posye4,estadoe4,posxe5,posye5,estadoe5,posxe6,posye6,estadoe6,posxe7,posye7,estadoe7,posxe8,posye8,estadoe8,posxe9,posye9,estadoe9,posxe10,posye10,estadoe10,posxe11,posye11,estadoe11,posxe12,posye12,estadoe12,posxe13,posye13,estadoe13,posxe14,posye14,estadoe14,posxe15,posye15,estadoe15,posxe16,posye16,estadoe16
if nivel==0:
v.after(10,mover)
v.after(1000,mover1)
v.after(10,mover2)
v.after(1000,mover3)
nivel=1
if nivel>=1:
if estadoe==0:
posxe=790
posye=210
estadoe=1
if estadoe1==0:
posxe1=790
posye1=210
estadoe1=1
if estadoe2==0:
posxe2=20
posye2=210
estadoe2=1
if estadoe3==0:
posxe3=20
posye3=210
estadoe3=1
if points>=2000 and nivel==1:
v.after(20,mover4)
v.after(1000,mover5)
v.after(20,mover6)
v.after(1000,mover7)
nivel=2
if nivel>=2:
if estadoe4==0:
posxe4=790
posye4=210
estadoe=1
if estadoe5==0:
posxe5=790
posye5=210
estadoe5=1
if estadoe6==0:
posxe6=20
posye6=210
estadoe6=1
if estadoe7==0:
posxe7=20
posye7=210
estadoe7=1
if points>=4000 and nivel==2:
v.after(20,mover8)
v.after(1000,mover9)
v.after(20,mover10)
v.after(1000,mover11)
nivel=3
if nivel>=3:
if estadoe8==0:
posxe8=790
posye8=210
estadoe8=1
if estadoe9==0:
posxe9=790
posye9=210
estadoe9=1
if estadoe10==0:
posxe10=20
posye10=210
estadoe10=1
if estadoe11==0:
posxe11=20
posye11=210
estadoe11=1
if points>=6000 and nivel==3:
v.after(20,mover12)
v.after(1000,mover13)
v.after(20,mover14)
v.after(1000,mover15)
nivel=4
if nivel>=4:
if estadoe12==0:
posxe12=790
posye12=210
estadoe12=1
if estadoe13==0:
posxe13=790
posye13=210
estadoe13=1
if estadoe14==0:
posxe14=20
posye14=210
estadoe14=1
if estadoe15==0:
posxe15=20
posye15=210
estadoe15=1
if points>=8000 and nivel==4:
nivel=5
if points>=10000 and nivel==5:
nivel=6
if points>=12000 and nivel==6:
ganar()
muestran=tkinter.Label(v,font=("Arial"),text=nivel,width=10,bd=5,bg=("black"),fg=("white"))
muestran.place(x=350,y=30)
def puntaje(b):
"""
funcion que con base en la muerte de un enemigo suma el puntaje que puede dar ese enemigo a el puntaje actual del jugador representandolo en un label en pantalla y que en caso
de que este puntaje sea u multiplo de cierto numero llamara a la funcion que da una vida
"""
global points,estadov1,estadov2,estadov3,nivel
points=points+b
score=tkinter.Label(v,font=("Arial"),text=str(points),width=20,bg=("black"),fg=("white"))
score.place(x=0,y=50)
muestran=tkinter.Label(v,font=("Arial"),text=nivel,width=10,bd=5,bg=("black"),fg=("white"))
muestran.place(x=350,y=30)
if points%2000==0:
darvida()
def puntajel(b):
"""
funcion que con base en la muerte de un enemigo suma el puntaje que puede dar ese enemigo a el puntaje actual del jugador representandolo en un label en pantalla y que en caso
de que este puntaje sea u multiplo de cierto numero llamara a la funcion que da una vida
"""
global pointsl,estadov11,estadov21,estadov31,nivel
pointsl=pointsl+b
scorel=tkinter.Label(v,font=("Arial"),text=str(pointsl),width=20,bg=("black"),fg=("white"))
scorel.place(x=600,y=50)
muestran1=tkinter.Label(v,font=("Arial"),text=nivel,width=10,bd=5,bg=("black"),fg=("white"))
muestran1.place(x=350,y=30)
if pointsl%2000==0:
darvidal()
def darvida():
"""
funcion que interactua con los labels que representan las vidas, entregando una en tal caso de que le falte, en caso de tener las vidas completas, la vida que se iba a
entregar se pierde
"""
global vida1,vida3,vida2,estadov1,estadov2,estadov3
if (estadov3==0)and((estadov2==1)and(estadov3==1)):
vida3=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida3.place(x=300,y=0)
estadov3=1
elif (estadov1==1)and((estadov3==0)and(estadov2==0)):
vida2=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida2.place(x=250,y=0)
estadov2=1
elif ((estadov1==0)and(estadov3==0)and(estadov2==0)):
vida1=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida1.place(x=200,y=0)
estadov1=1
def darvidal():
"""
funcion que interactua con los labels que representan las vidas, entregando una en tal caso de que le falte, en caso de tener las vidas completas, la vida que se iba a
entregar se pierde
"""
global vida11,vida31,vida21,estadov11,estadov21,estadov31
if (estadov31==0)and((estadov21==1)and(estadov31==1)):
vida31=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida31.place(x=500,y=0)
estadov31=1
elif (estadov11==1)and((estadov31==0)and(estadov2==0)):
vida21=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida21.place(x=550,y=0)
estadov21=1
elif ((estadov11==0)and(estadov31==0)and(estadov21==0)):
vida11=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida11.place(x=600,y=0)
estadov11=1
def gameover():
"""
funcion que da por terminado el juego al haber perdido y dando como ultima opcion el salir de este
"""
global v
v.withdraw
h=tkinter.Toplevel(v)
canvas3 = tkinter.Canvas(h,width=800,height=450)
gb=tkinter.PhotoImage(file='gameover.png')
canvas3.create_image(400,225, image=gb)
canvas3.focus_set()
canvas3.pack()
salir=tkinter.Button(h,text="Salir",font=("Agency FB",30),command=v.destroy,width=15,height=(1),bg=("black"),fg=("white"))
salir.place(x=285,y=300)
h.resizable(0,0)
h.mainloop()
def quitarvida():
"""
funcion que interactua con los labels que representan las vidas, quitando una en tal caso de que haya muerto algun personaje, al ya no tener mas vidas que quitar se determina
que ha perdido el juego
"""
global estadov3,estadov2,estadov1,vida3,vida1,vida2,lemario,canvas,estadov31,estadov21,estadov11,vida31,vida11,vida21,lemario,leluigi,final,finall,both
canvas.delete(lemario)
if ((estadov1==1)and(estadov3==1)and(estadov2==1)):
vida3.destroy()
estadov3=0
lemario=canvas.create_image(posxm,posym, image=mario1)
elif (estadov3==0)and(estadov2==1):
vida2.destroy()
estadov2=0
lemario=canvas.create_image(posxm,posym, image=mario1)
elif (estadov3==0)and(estadov2==0)and(estadov1==1):
vida1.destroy()
estadov1=0
lemario=canvas.create_image(posxm,posym, image=mario1)
elif ((estadov3==0)and(estadov2==0)and(estadov1==0))and(final==0):
if parejas==False:
final=1
gameover()
else:
final=1
if (final==1 and finall==1)and (parejas==True)and(both==0):
both=1
gameover()
def quitarvidal():
"""
funcion que interactua con los labels que representan las vidas, quitando una en tal caso de que haya muerto algun personaje, al ya no tener mas vidas que quitar se determina
que ha perdido el juego
"""
global estadov31,estadov21,estadov11,vida31,vida11,vida21,lemario,canvas,leluigi,estadov3,estadov2,estadov1,vida3,vida1,vida2,final,finall,both
canvas.delete(leluigi)
if parejas==True:
if ((estadov11==1)and(estadov31==1)and(estadov21==1)):
vida31.destroy()
estadov31=0
leluigi=canvas.create_image(posxl,posyl, image=luigi1)
elif (estadov31==0)and(estadov21==1):
vida21.destroy()
estadov21=0
leluigi=canvas.create_image(posxl,posyl, image=luigi1)
elif (estadov31==0)and(estadov21==0)and(estadov11==1):
vida11.destroy()
estadov11=0
leluigi=canvas.create_image(posxl,posyl, image=luigi1)
elif ((estadov31==0)and(estadov21==0)and(estadov11==0))and(finall==0):
finall=1
if (final==1 and finall==1)and (parejas==True)and(both==0):
both=1
gameover()
v.withdraw()
def menu():
"""
esta funcion despliega el menu como toplevel del juego
"""
global v,nombre1,nombre2,vida1,vida3,vida2,vida11,vida31,vida21,estadov3,estadov2,estadov1,estadov31,estadov21,estadov11
m=tkinter.Toplevel(v)
canvas1 = tkinter.Canvas(m,width=800,height=630)
menu=tkinter.PhotoImage(file='menu.png')
canvas1.create_image(400,315, image=menu)
canvas1.focus_set()
canvas1.pack()
def nombres1():
"""
esta funcion despliega la pantalla para el ingreso de el nombre de un jugador como toplevel del juego
"""
global v
m.withdraw()
n=tkinter.Toplevel(v)
canvas2 = tkinter.Canvas(n,width=800,height=630)
nombres=tkinter.PhotoImage(file='N1.png')
canvas2.create_image(400,315, image=nombres)
canvas2.focus_set()
canvas2.pack()
def juego2():
"""
esta funcion inicia el juego en el modo un jugador
"""
nombre1=str(jugador1.get())
muestra1=tkinter.Label(v,font=("Arial"),text=nombre1,width=20,bg=("black"),fg=("white"))
muestra1.place(x=0,y=0)
vida1.place(x=200,y=0)
estadov1=1
vida2.place(x=250,y=0)
estadov2=1
vida3.place(x=300,y=0)
estadov3=1
v.iconify()
n.withdraw()
muestran1=tkinter.Label(v,font=("Arial"),text="NIVEL:",width=10,bd=5,bg=("black"),fg=("white"))
muestran1.place(x=350,y=0)
muestran=tkinter.Label(v,font=("Arial"),text=nivel,width=10,bd=5,bg=("black"),fg=("white"))
muestran.place(x=350,y=30)
nombres=[nombre1]
archivo=open('unjugadorg.txt','w')
archivo.writelines(nombres)
archivo.close()
empezar()
def atras():
"""
esta funcion nos devuelve al menu desde cualquier pantalla donde se ingresan los nombres
"""
n.withdraw()
m.iconify()
jugar=tkinter.Button(n,text="jugar",font=("Agency FB",30),command=juego2,width=10,height=(1),bg=("black"),fg=("white"))
jugar.place(x=315,y=500)
jugador1=tkinter.Entry(n,font=("Arial"),width=50,bd=5,bg=("black"),fg=("white"))
jugador1.place(x=230,y=185)
atras=tkinter.Button(n,image=goback,command=atras,width=20,height=(20),bg=("black"),fg=("white"))
atras.place(x=0,y=0)
n.resizable(0,0)
n.mainloop()
def nombres2():
"""
esta funcion despliega la pantalla para el ingreso de el nombre de dos jugadores como toplevel del juego
"""
global v,parejas
parejas=True
m.withdraw()
n=tkinter.Toplevel(v)
canvas2 = tkinter.Canvas(n,width=800,height=630)
nombres=tkinter.PhotoImage(file='N.png')
canvas2.create_image(400,315, image=nombres)
canvas2.focus_set()
canvas2.pack()
def juego2():
"""
esta funcion inicia el juego en el modo dos jugadores
"""
nombre1=str(jugador1.get())
nombre2=str(jugador2.get())
muestra1=tkinter.Label(v,font=("Arial"),text=nombre1,width=20,bg=("black"),fg=("white"))
muestra1.place(x=0,y=0)
muestra2=tkinter.Label(v,font=("Arial"),text=nombre2,width=20,bd=5,bg=("black"),fg=("white"))
muestra2.place(x=610,y=0)
vida1=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida1.place(x=150,y=0)
estadov1=1
vida2=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida2.place(x=200,y=0)
estadov2=1
vida3=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida3.place(x=250,y=0)
estadov3=1
vida11=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida11.place(x=600,y=0)
estadov11=1
vida21=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida21.place(x=550,y=0)
estadov21=1
vida31=tkinter.Label(v,image=life,width=50,bg=("black"),fg=("white"))
vida31.place(x=500,y=0)
estadov31=1
muestran1=tkinter.Label(v,font=("Arial"),text="NIVEL:",width=10,bd=5,bg=("black"),fg=("white"))
muestran1.place(x=350,y=0)
muestran=tkinter.Label(v,font=("Arial"),text=nivel,width=10,bd=5,bg=("black"),fg=("white"))
muestran.place(x=350,y=30)
nombres=[nombre1,"\n",nombre2]
archivo=open('dosjugadorg.txt','w')
archivo.writelines(nombres)
archivo.close()
empezar()
v.iconify()
n.withdraw()
empezar()
def atras():
"""
esta funcion nos devuelve al menu desde cualquier pantalla donde se ingresan los nombres
"""
n.withdraw()
m.iconify()
jugador1=tkinter.Entry(n,font=("Arial"),width=50,bd=5,bg=("black"),fg=("white"))
jugador1.place(x=230,y=185)
jugador2=tkinter.Entry(n,font=("Arial"),width=50,bd=5,bg=("black"),fg=("white"))
jugador2.place(x=230,y=300)
jugar=tkinter.Button(n,text="jugar",font=("Agency FB",30),command=juego2,width=10,height=(1),bg=("black"),fg=("white"))
jugar.place(x=315,y=500)
atras=tkinter.Button(n,image=goback,command=atras,width=20,height=(20),bg=("black"),fg=("white"))
atras.place(x=0,y=0)
n.resizable(0,0)
n.mainloop()
def juego1():
"""
esta funcion carga una partida existente de un jugador
"""
archivo=open("unjugadorg.txt","r")
datos=archivo.readlines()
nombre1=datos[0]
muestra1=tkinter.Label(v,font=("Arial"),text=nombre1,width=20,bg=("black"),fg=("white"))
muestra1.place(x=0,y=0)
estadov2=datos[4]
estadov1=datos[3]
estadov3=datos[5]
if estadov1==1:
vida1.place(x=200,y=0)
if estadov2==1:
vida2.place(x=250,y=0)
if estadov3==1:
vida3.place(x=300,y=0)
muestran1=tkinter.Label(v,font=("Arial"),text="NIVEL:",width=10,bd=5,bg=("black"),fg=("white"))
muestran1.place(x=350,y=0)
puntaje(int(datos[1]))
nivel=(datos[2])
muestran=tkinter.Label(v,font=("Arial"),text=nivel,width=10,bd=5,bg=("black"),fg=("white"))
muestran.place(x=350,y=30)
v.iconify()
m.withdraw()
empezar()
archivo.close()
def juego3():
"""
esta funcion carga una partida existente de dos jugadores
"""
global v,parejas
parejas=True
archivo=open("dosjugadorg.txt","r")
datos=archivo.readlines()
nombre1=datos[0]
muestra1=tkinter.Label(v,font=("Arial"),text=nombre1,width=20,bg=("black"),fg=("white"))
muestra1.place(x=0,y=0)
estadov2=datos[5]
estadov1=datos[4]
estadov3=datos[6]
estadov21=datos[10]
estadov11=datos[9]
estadov31=datos[11]
if estadov1==1:
vida1.place(x=200,y=0)
if estadov2==1:
vida2.place(x=250,y=0)
if estadov3==1:
vida3.place(x=300,y=0)
if estadov11==1:
vida11.place(x=600,y=0)
if estadov21==1:
vida21.place(x=550,y=0)
if estadov31==1:
vida31.place(x=500,y=0)
v.iconify()
m.withdraw()
muestran1=tkinter.Label(v,font=("Arial"),text="NIVEL:",width=10,bd=5,bg=("black"),fg=("white"))
muestran1.place(x=350,y=0)
puntaje(int(datos[2]))
puntajel(int(datos[8]))
nivel=(datos[3])
muestran=tkinter.Label(v,font=("Arial"),text=nivel,width=10,bd=5,bg=("black"),fg=("white"))
muestran.place(x=350,y=30)
empezar()
archivo.close()
def control():
"""
esta funcion despliega la pantalla para el ingreso de el nombre de dos jugadores como toplevel del juego
"""
global v
m.withdraw()
n=tkinter.Toplevel(v)
canvas2 = tkinter.Canvas(n,width=800,height=450)
contro=tkinter.PhotoImage(file='controles.png')
canvas2.create_image(400,225, image=contro)
canvas2.focus_set()
canvas2.pack()
def atras():
"""
esta funcion nos devuelve al menu desde cualquier desde donde se muestran
"""
n.withdraw()
m.iconify()
atras=tkinter.Button(n,image=goback,command=atras,width=20,height=(20),bg=("black"),fg=("white"))
atras.place(x=0,y=0)
n.resizable(0,0)
n.mainloop()
unjugador=tkinter.Button(m,text="Un Jugador",font=("Agency FB",30),command=nombres1,width=15,bg=("black"),fg=("white"))
unjugador.place(x=0,y=315)
COOP=tkinter.Button(m,text="Dos Jugadores",font=("Agency FB",30),command=nombres2,width=15,height=(1),bg=("black"),fg=("white"))
COOP.place(x=280,y=315)
cargar=tkinter.Button(m,text="Cargar Partida",font=("Agency FB",30),command=juego1,width=15,bg=("black"),fg=("white"))
cargar.place(x=0,y=405)
cargar2=tkinter.Button(m,text="Cargar Partida",font=("Agency FB",30),command=juego3,width=15,bg=("black"),fg=("white"))
cargar2.place(x=280,y=405)
controles=tkinter.Button(m,text="Controles",font=("Agency FB",30),command=control,width=15,height=(1),bg=("black"),fg=("white"))
controles.place(x=565,y=315)
salir=tkinter.Button(m,text="Salir",font=("Agency FB",30),command=v.destroy,width=15,height=(1),bg=("black"),fg=("white"))
salir.place(x=565,y=405)
m.resizable(0,0)
m.mainloop()
menu()
v.resizable(0,0)
v.mainloop()
| true |
bfbdedcb7c4212f38c38d17b88ee935fbf7a5b71 | Python | zengchenchen/OJ-Practice | /11.Cotainer with Most Water.py | UTF-8 | 379 | 3.125 | 3 | [] | no_license | class Solution(object):
def maxArea(self, height):
i, j, S = 0, len(height) - 1, 0
while j > i:
s = (j - i) * min(height[i], height[j])
S = max(S, s)
if height[i] < height[j]:
i = i + 1
else:
j = j - 1
return S
a = Solution()
print(a.maxArea([3, 2, 4, 7, 5, 2, 6, 1]))
| true |
417cca6f6e05aa711d929aed3442559badab4fca | Python | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_copy_odd_lines_of_one_file_to_other.py | UTF-8 | 397 | 2.578125 | 3 | [] | no_license | fhandle1=open('G:\Desktop\Dta structures and algorithms using python\Top_interview_questions_in_data_structures_in_python\\all_lines.txt')
fhandle2=open('G:\Desktop\Dta structures and algorithms using python\Top_interview_questions_in_data_structures_in_python\\vamsi.txt','w')
count=1
for line in fhandle1:
if count%2 != 0:
fhandle2.write(line)
count+=1
fhandle2.close() | true |
47d1f81d362d7ee99e3d132e5a4e516aa50c3375 | Python | ZNNNNZ/pratice_code | /code21.py | UTF-8 | 1,046 | 3.65625 | 4 | [] | no_license | '''
大数乘法
大数指超过int64_t 可承载范围的数字
输入描述:
输入两行数n1, n2 (0 < n* < 2^100)
输出描述:
输出两数之积
输入例子1:
2
3
输出例子1:
6
输入例子2:
9223372024429430685
34223371424429430685
输出例子2:
315654886577740006976078312593219569225
'''
class Solution:
def mul_longnums(self,n1,n2):
len1=len(n1)
len2=len(n2)
new_list=[0]*(len1+len2)
for i in range(1,len1+1):
for j in range(1,len2+1):
s1=int(n1[i-1])
s2=int(n2[j - 1])
new_list[i+j-1]+=s1*s2
for k in range(1,len(new_list))[::-1]:
if new_list[k]>=10:
new_list[k-1]+=new_list[k]//10
new_list[k]=new_list[k]%10
m=0
while new_list[m]==0:
m=m+1
for q in range(m,len(new_list)):
print(new_list[q],end='')
S=Solution()
input1=input('输入第一个大数:')
input2=input('输入第二个大数:')
S.mul_longnums(input1,input2)
| true |
cfc72f6d70a0c8e6b6cb5ae57e752233549976cb | Python | Brimes7/recursive-sorting | /src/recursive_sorting/recursive_sorting.py | UTF-8 | 3,394 | 4.34375 | 4 | [] | no_license | # TO-DO: complete the helper function below to merge 2 sorted arrays
# arrA = [1, 3, 5, 7]
# arrB = [2, 4, 6, 8]
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# Left
x = 0
# right
y = 0
# new array
z = 0
# Your code here
# This will traverse over both of the arrays
while x < len(arrA) and y < len(arrB):
# We need to check if the current element of the first
# array is smaller than the curr of the second array
if arrA[x] < arrB[y]:
merged_arr[z] = arrA[x]
z = z + 1
x = x + 1
else:
merged_arr[z] = arrB[y]
z = z + 1
y = y + 1
# THESE WHILE LOOPS WILL STORE THE REMAINING ELEMENTS
while x < len(arrA):
merged_arr[z] = arrA[x]
#same as z += 1
z = z + 1
x = x + 1
while y < len(arrB):
merged_arr[z] = arrB[x]
z = z + 1
y = y + 1
# range returns a sequence of numbers starting at 0
for x in range(elements):
print(str(merged_arr[x]))
return merged_arr
# TO-DO: implement the Merge Sort function below USING RECURSION
def merge_sort(arr):
# Your code here
if len(arr) > 1:
#This will find the middle
middle = len(arr)//2
#Dividing the array elements
left = arr[:middle]
#Splits into 2 halves
right = arr[middle:]
merge_sort(left)
merge_sort(right)
x = y = z = 0
#This will copy data over int the temoprary array
while x < len(left) and y < len(right):
if left[x] < right[y]:
arr[z] = left[x]
x += 1
else:
arr[z] = right[y]
y += 1
z += 1
#Checks all the remainder
while x < len(left):
arr[z] = left[x]
x += 1
z += 1
while y < len(right):
arr[z] = right[y]
y += 1
z += 1
return arr
# implement an in-place merge sort algorithm
def merge_in_place(arr, start, mid, end):
# Your code here
startii = mid + 1
#This is if it is already sorted
if arr[mid] <= arr[startii]:
return arr
#Need to check both arrays
while start <= mid and startii <= end:
# If start is right place
if arr[start] <= arr[startii]:
start += 1
else:
value = arr[startii]
index = startii
# This will shift the elements over by 1
# to make room
while index != start:
arr[index] = arr[index - 1]
index -= 1
arr[start] = value # slot in lower value
# This will update all the pointers
start += 1
mid += 1
startii += 1
def merge_sort_in_place(arr, l, r):
if l < r:
# This will avoid overflow
# for l and r already given
m = l + (r - l) // 2
# Sort first and second halves
merge_sort_in_place(arr, l, m)
merge_sort_in_place(arr, m + 1, r)
merge_in_place(arr, l, m, r)
return arr
# STRETCH: implement the Timsort function below
# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
def timsort(arr):
# Your code here
return arr
| true |
ef61094adc98ca4e37e2dc917d27f53566224dfc | Python | liuguoyou/gtnet | /utils/os.py | UTF-8 | 212 | 2.765625 | 3 | [] | no_license | import os
import json
def makedir(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
def load_json(dict_path):
with open(dict_path) as f:
dict_data = json.load(f)
return dict_data
| true |
0f9e2590f1fe25a9ee27162f9d17bac8c9b9fbc2 | Python | blopblopy/excel_manipulations | /cluster/test_cluster.py | UTF-8 | 2,520 | 2.9375 | 3 | [] | no_license | import unittest
import cluster
from cluster import Vector, Cluster
class ClusterAlgoTest(unittest.TestCase):
def test_one(self):
center = cluster.Vector("1",[0,0,0])
points = set([center])
expected_clusters = cluster.Cluster(center=center, covers=set([center]))
result_clusters = cluster.ClusterAlgo(r=1, points=points).solve()
self.assertEqual(result_clusters, [expected_clusters])
def test_another(self):
center = cluster.Vector("2",[1,1,1])
points = set([center])
expected_clusters = cluster.Cluster(center=center, covers=set([center]))
result_clusters = cluster.ClusterAlgo(r=1, points=points).solve()
self.assertEqual(result_clusters, [expected_clusters])
def test_three(self):
center = Vector("0",[0,0,0])
points = set([center,
Vector("1",[1,0,0]),
Vector("-1",[0,0,-1])
])
expected_clusters = cluster.Cluster(center=center, covers=points)
result_clusters = cluster.ClusterAlgo(r=1, points=points).solve()
self.assertEqual(result_clusters, [expected_clusters])
def test_two_cluster(self):
center1 = Vector("0_1",[0,0,0])
points1 = set([center1,
Vector("1_1",[1,0,0]),
Vector("-1_1",[0,0,-1])
])
center2 = Vector("0_2",[0,100,0])
points2 = set([center2,
Vector("1_2",[1,100,0]),
Vector("-1_2",[0,100,-1])
])
expected_clusters = [Cluster(center=center1, covers=points1),
Cluster(center=center2, covers=points2)]
result_clusters = cluster.ClusterAlgo(r=1, points=points1|points2).solve()
self.assertEqual(result_clusters, expected_clusters)
class VectorTest(unittest.TestCase):
def setUp(self):
self.vector1 = Vector("0", [0,0])
self.vector2 = Vector("1", [3,4])
def test_self_distance(self):
self.assertEquals(self.vector1.distance(self.vector1), 0)
def test_distance(self):
self.assertEquals(self.vector1.distance(self.vector2), 5)
def test_equivalence(self):
self.assertEquals(self.vector1.distance(self.vector2),
self.vector2.distance(self.vector1))
if __name__ == "__main__":
unittest.main()
| true |
17c7fd497eef364ec95fcc9210bf8e5627108097 | Python | jwodder/ghutil | /src/ghutil/regex.py | UTF-8 | 2,059 | 2.671875 | 3 | [
"MIT"
] | permissive | #: Regular expression for a valid GitHub username or organization name. As of
#: 2017-07-23, trying to sign up to GitHub with an invalid username or create
#: an organization with an invalid name gives the message "Username may only
#: contain alphanumeric characters or single hyphens, and cannot begin or end
#: with a hyphen". Additionally, trying to create a user named "none" (case
#: insensitive) gives the message "Username name 'none' is a reserved word."
#:
#: Unfortunately, there are a number of users who made accounts before the
#: current name restrictions were put in place, and so this regex also needs to
#: accept names that contain underscores, contain multiple consecutive hyphens,
#: begin with a hyphen, and/or end with a hyphen.
GH_USER_RGX = r"(?![Nn][Oo][Nn][Ee]($|[^-A-Za-z0-9]))[-_A-Za-z0-9]+"
# GH_USER_RGX_DE_JURE = r'(?![Nn][Oo][Nn][Ee]($|[^-A-Za-z0-9]))'\
# r'[A-Za-z0-9](?:-?[A-Za-z0-9])*'
#: Regular expression for a valid GitHub repository name. Testing as of
#: 2017-05-21 indicates that repository names can be composed of alphanumeric
#: ASCII characters, hyphens, periods, and/or underscores, with the names ``.``
#: and ``..`` being reserved and names ending with ``.git`` forbidden.
GH_REPO_RGX = r"(?:\.?[-A-Za-z0-9_][-A-Za-z0-9_.]*|\.\.[-A-Za-z0-9_.]+)" r"(?<!\.git)"
_REF_COMPONENT = r"(?!\.)[^\x00-\x20/~^:?*[\\\x7F]+(?<!\.lock)"
#: Regular expression for a (possibly one-level) valid normalized Git refname
#: (e.g., a branch or tag name) as specified in
#: :manpage:`git-check-ref-format(1)`
#: <https://git-scm.com/docs/git-check-ref-format> as of 2017-07-23 (Git
#: 2.13.1)
GIT_REFNAME_RGX = r"(?!@/?$)(?!.*(?:\.\.|@\{{)){0}(?:/{0})*(?<!\.)".format(
_REF_COMPONENT
)
#: Convenience regular expression for ``<owner>/<repo>``, including named
#: capturing groups
OWNER_REPO_RGX = fr"(?P<owner>{GH_USER_RGX})/(?P<repo>{GH_REPO_RGX})"
API_REPO_RGX = r"(?:https?://)?api\.github\.com/repos/" + OWNER_REPO_RGX
WEB_REPO_RGX = r"(?:https?://)?(?:www\.)?github\.com/" + OWNER_REPO_RGX
| true |
db2c8f46c22155ec0948fb61ae58d88c0ca696b8 | Python | Maplexc/UQ-IT | /CSSE7030/assign1/a1.py | UTF-8 | 7,824 | 3.890625 | 4 | [] | no_license | #!/usr/bin/env python3
## assignment 1 in 1 line
## enrypt = lambda string, offset: "".join([chr((ord(char) - ord('A') + offset) % ord('A')) for char in string])
"""
Assignment 1
CSSE1001/7030
Semester 2, 2018
"""
import a1_support
import string
from a1_support import is_word_english
__author__ = "Xin Chen 45189915"
# Write your functions here
def encrypt(text, offset):
"""Encrypts text by replacing each letter with the letter some fixed number of positions(the offset) down the alphabet
Parameters:
text(str): text want to encrypt
offset(int): the position of the letter that will replace the letter in text
Return:
str: the encrypted text
"""
offset_lowercase = list(string.ascii_lowercase)
offset_uppercase = list(string.ascii_uppercase)
offset_text = ''
# offset each character in the sentence
for i in range(0, len(text)):
if text[i].islower():
# find the index of the text character in lowercase alphabet
pos_offset = string.ascii_lowercase.index(text[i])
total_offset = pos_offset + offset
if total_offset >= 26:
total_offset = total_offset - 26
offset_text += offset_lowercase[total_offset]
elif text[i].isupper():
# find the index of the text character in upppercase alphabet
pos_offset = string.ascii_uppercase.index(text[i])
total_offset = pos_offset + offset
if total_offset >= 26:
total_offset = total_offset - 26
offset_text += offset_uppercase[total_offset]
else:
offset_text += text[i]
return offset_text
def decrypt(text, offset):
"""Decrypts text that was encrypted by the encrypt function above
Parameters:
text (str): text want to decrypt
offset: the position of the letter that will replace the letter in text
Return:
str: the decrypted text
"""
offset_text = encrypt(text, -offset)
return offset_text
def find_encryption_offsets(encrypted_text):
"""Return a tuple containing all possible offsets that can decrypt the text into English
Parameter:
encrypted_text (str): text want to find the offset number
Return:
tuple containing all possible offsets that can decrypt the text into English
"""
valid = []
encrypted_text_test = ''
# to remove all the punctuations and convert text to lowercase
for i in range(0, len(encrypted_text)):
if encrypted_text[i].islower() or encrypted_text[i] == ' ':
encrypted_text_test += encrypted_text[i]
elif encrypted_text[i].isupper():
lower_text = encrypted_text[i].lower()
encrypted_text_test += lower_text
elif encrypted_text[i] == '-':
encrypted_text_test += ' '
else:
encrypted_text_test += ''
# find the offset number where it can decrypt the input text into English
for offset_all in range(1, 26):
string = decrypt(encrypted_text_test, offset_all)
words = string.split()
is_valid = True
# check if each word in the sentence is English (True if all words are English)
for is_english in words:
if a1_support.is_word_english(is_english) == False:
is_valid = False
break
if is_valid:
valid.append(offset_all)
return tuple(valid)
def main():
# Add your main code here
"""This is a simple encryption tool which use to encrypted and decrypted text.
It has 4 options:
e: encrypt text
you will be asked to enter some text that you want to encrypt and a shift offset number between 1 and 25
it will return an encrypted text, if you enter a valid number
0 can enter as the offset number, encrypted text should be shown for all offsets (1 to 25, inclusive) when enter 0
otherwise, it will show 'invalid command'
d: decrypt text
you will be asked to enter some text that you want to decrypt and a shift offset number between 1 and 25
it will return an decrypted text, if you enter a valid number
0 can enter as the offset number, decrypted text should be shown for all offsets (1 to 25, inclusive)
otherwise, it will show 'invalid command'
a: automatically decrypt English text
you will be asked to enter some text that you want to decrypt
it will return all the possible offset number if the text you enter can be decrypted to English text
if it cannot find any offset number, it will show 'No valid encryption offset'
if it finds only one offset number, it will return the offset number and show the decrypted English text
if it finds more than one offset number, it will return all the offset number
q: quit
"""
option = ''
print('Welcome to the simple encryption tool!')
while option != 'q':
option = input('\n'
'Please choose an option [e/d/a/q]:\n'
' e) Encrypt some text\n'
' d) Decrypt some text\n'
' a) Automatically decrypt English text\n'
' q) Quit\n'
'> ')
if option == 'q':
break
# to encrypt text if user choose 'e'
elif option == 'e':
text = input('Please enter some text to encrypt: ')
offset = int(input('Please enter a shift offset (1-25): '))
if offset >= 1 and offset <= 25:
print('The encrypted text is:', encrypt(text, offset))
elif offset == 0:
print('The encrypted text is:')
for offset_all in range(1, 26):
print(' ', "%02d" % offset_all, ': ',
encrypt(text, offset_all), sep='')
else:
print('Invalid command')
# to decrypt text if user choose 'd'
elif option == 'd':
text = input('Please enter some text to decrypt: ')
offset = int(input('Please enter a shift offset (1-25): '))
if 1 <= offset <= 25:
print('The decrypted text is:', decrypt(text, offset))
elif offset == 0:
print('The decrypted text is:')
for offset_all in range(1, 26):
print(' ', "%02d" % offset_all, ': ',
decrypt(text, offset_all), sep='')
else:
print('Invalid command')
# to automatically decrypt English text if user choose 'a'
elif option == 'a':
text = input('Please enter some encrypted text: ')
valid = find_encryption_offsets(text)
if len(valid) == 1:
print('Encryption offset:', valid[0])
print('Decrypted message:', decrypt(text, valid[0]))
elif len(valid) == 0:
print('No valid encryption offset')
else:
print('Multiple encryption offsets:',
end=' '), print(*valid, sep=', ')
else:
print('Invalid command')
print('Bye!')
##################################################
# !! Do not change (or add to) the code below !! #
#
# This code will run the main function if you use
# Run -> Run Module (F5)
# Because of this, a "stub" definition has been
# supplied for main above so that you won't get a
# NameError when you are writing and testing your
# other functions. When you are ready please
# change the definition of main above.
###################################################
if __name__ == '__main__':
main()
| true |
fc868a4ad73c0649342f962aaf820c62cd07a3a3 | Python | ahmedramzygi/Website-Blocker | /WebSite_Blocker.py | UTF-8 | 1,059 | 2.578125 | 3 | [] | no_license | import time
from datetime import datetime as dt
hosts_file= r"C:\Windows\System32\drivers\etc\hosts"
hosts_temp=r"C:\Users\aeram\Desktop\Projects\PythonBlocker\hosts"
redirect="127.0.0.1"
blocked_sites=["www.facebook.com","www.instagram.com"]
while(True):
if dt(dt.now().year,dt.now().month,dt.now().day,17) < dt.now() < dt(dt.now().year,dt.now().month,dt.now().day,19): # We want to block these sites in this range
print('Working Hours')
with open (hosts_file,'r+') as file:
content=file.read()
for website in blocked_sites:
if website in content:
pass
else:
file.write(redirect+" "+website+"\n")
else:
with open(hosts_file,'r+') as file:
content=file.readlines()
file.seek(0)
for line in content:
if not any(website in line for website in blocked_sites):
file.write(line)
file.truncate()
print('fun')
time.sleep(5)
| true |
1c9618aa0d9197c0509bd6a26715e339a70c9d3b | Python | ivankohut/spravodaj | /booklet-tool/classes.py | UTF-8 | 4,537 | 2.859375 | 3 | [] | no_license | from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.pdf import PageObject
from collections.abc import Iterable
class OutputFiles:
def __init__(self, *files):
self.__files = files
def write(self):
for file in self.__files:
file.write()
class OutputPdfFileWithSuffix:
def __init__(self, pages, input_file_name, suffix):
self.output_pdf_file = OutputPdfFile(
pages,
FileNameWithSuffix(input_file_name, "-" + suffix)
)
def write(self):
self.output_pdf_file.write()
class OutputPdfFile:
def __init__(self, pages, filename):
self.__pages = pages
self.__filename = filename
def write(self):
writer = PdfFileWriter()
for page in self.__pages:
writer.addPage(page)
if writer.getNumPages() > 0:
with open(str(self.__filename), 'wb') as file:
writer.write(file)
class BookletOrderedPages(Iterable):
def __init__(self, pages):
self.__pages = pages
def __iter__(self):
pages_list = list(self.__pages)
pages_count = len(pages_list)
quadruples_count = divmod(pages_count, 4)[0]
return [
page
for i in range(0, quadruples_count)
for page in [
pages_list[pages_count - 1 - (i * 2)],
pages_list[i * 2],
pages_list[i * 2 + 1],
pages_list[pages_count - 2 - (i * 2)]
]
].__iter__()
class Pages2in1(Iterable):
def __init__(self, pages, two_to_one_mapping):
self.__two_to_one_mapping = two_to_one_mapping
self.__pages = pages
def __iter__(self):
pages = list(self.__pages)
if not pages:
return [].__iter__()
else:
return [
self.__two_to_one_mapping.map(pages[i * 2], pages[i * 2 + 1])
for i in range(0, divmod(len(pages), 2)[0])
].__iter__()
# Non-OOP class unfortunately because we cannot create own implementation of PyPDF2's PageObject class
class SecondPageRightOfFirstMapping:
def map(self, page1, page2):
box1 = page1.mediaBox
box2 = page2.mediaBox
page = PageObject.createBlankPage(
None,
box1.getWidth() + box2.getWidth(),
max(box1.getHeight(), box2.getHeight())
)
page.mergePage(page1)
page.mergeTranslatedPage(page2, box1.getWidth(), 0)
return page
class InputPdfFile(Iterable):
def __init__(self, filename):
self.__filename = filename
def __iter__(self):
reader = PdfFileReader(open(str(self.__filename), 'rb'))
return [(reader.getPage(i)) for i in range(0, reader.getNumPages())].__iter__()
class GreatestMultiple(Iterable):
def __init__(self, items, divisor):
self.__items = items
self.__divisor = divisor
def __iter__(self):
count = len(list(self.__items))
remainder = divmod(count, self.__divisor)[1]
return (list(self.__items)[0:count - remainder]).__iter__()
class RemainingItems(Iterable):
def __init__(self, items, items_to_remove):
self.__items = items
self.__items_to_remove = items_to_remove
def __iter__(self):
return [item for item in self.__items if item not in self.__items_to_remove].__iter__()
class FileNameWithSuffix:
def __init__(self, obj, suffix):
self.__obj = obj
self.__suffix = suffix
def __str__(self):
parts = str(self.__obj).rsplit('.', 1)
return parts[0] + self.__suffix + (("." + parts[1]) if len(parts) == 2 else "")
class CachingIterable(Iterable):
def __init__(self, iterable):
# TODO make lazy
self.__iterable = list(iterable)
def __iter__(self):
return self.__iterable.__iter__()
class ConcatenatedIterables(Iterable):
def __init__(self, iterable1, iterable2):
self.__iterable1 = iterable1
self.__iterable2 = iterable2
def __iter__(self):
return [item for items in [self.__iterable1, self.__iterable2] for item in items].__iter__()
class DoubledIterable(Iterable):
def __init__(self, iterable):
self.__iterable = ConcatenatedIterables(iterable, iterable)
def __iter__(self):
return self.__iterable.__iter__()
class InputFileName():
def __init__(self, arguments):
self.__arguments = arguments
def __str__(self):
return self.__arguments[1]
| true |
9ff66d5826297d51a9c84e600c4b5fa4a3620532 | Python | iamsuryakant/100-days-of-code | /PYTHON/text_wrap.py | UTF-8 | 388 | 3.75 | 4 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 19:42:16 2020
@author: Suryakant Thakur
HackerRank Text Wrap problem
https://www.hackerrank.com/challenges/text-wrap/problem
"""
import textwrap
def wrap(string, max_width):
return textwrap.fill(string,max_width)
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
| true |
f305c2f3c569756d56c2ca02b633ce4352c98f9c | Python | patmanteau/sql2graph | /sql2graph/graph.py | UTF-8 | 5,029 | 2.75 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
#
# Copyright 2013 Paul Tremberth, Newlynn Labs
# See LICENSE for details.
import collections
import schema
# ----------------------------------------------------------------------
class DictLookup(object):
def __init__(self):
self.container = {}
def append(self, entity, entity_pk, node_position):
if not self.container.get(entity):
self.container[entity] = {}
self.container[entity][entity_pk] = node_position
def lookup(self, entity, entity_pk):
if self.container.get(entity):
if self.container[entity].get(entity_pk):
return self.container[entity][entity_pk]
def start_entity(self, entity):
pass
def stop_entity(self, entity):
pass
class Node(object):
def __init__(self, record, entity):
if not isinstance(record, dict):
raise TypeError
self.record = record
if not isinstance(entity, schema.Entity) or not entity.get_primary_key_field():
raise TypeError
self.entity = entity
# convert record to properties per entity schema definition
self.properties = {}
for field in entity.fields:
if field.column and isinstance(field.column, schema.Column):
self.properties[field.name] = record.get(field.column.name)
else:
self.properties[field.name] = field.value
#self.pk_column = pk_column
#self.entity_name = entity.name
#print entity.get_primary_key_field().column.name
self.entity_pk = int(record.get(entity.get_primary_key_field().column.name))
self.properties['kind'] = self.entity.name
self.properties['node_id'] = None
def get_dict(self, fields):
return dict((e, self.properties.get(e, '')) for e in fields)
def save_node_id(self, node_id):
self.properties['node_id'] = node_id
def get_node_id(self):
return self.properties['node_id']
def get_entity_pk(self):
return self.entity_pk
def __repr__(self):
return "entity [%s/pk=%s]: %s" % (self.entity.name, self.entity_pk, str(self.properties))
class Relation(object):
def __init__(self, start, end, properties):
self.start = start
self.end = end
self.properties = properties
# used when we could not resolve on the fly
self.start_fk = None
self.start_target_entity = None
def get_dict(self, fields):
if self.end:
values = dict((
('start', self.start),
('end', self.end),
))
values.update(self.properties)
return dict((e, values.get(e, '')) for e in fields)
else:
return None
def set_deferred_resolution(self, fk, target_entity):
self.start_fk = fk
self.start_target_entity = target_entity
def __repr__(self):
return "(%d)-[%s]->(%d)" % (
self.start, self.property, self.end or 0,)
class NodeList(object):
def __init__(self):
self.node_list_size = 0
self.reverse_lookup = DictLookup()
self.entity_fields = set()
self.last_lookup = None
self.last_lookup_result = None
def get_all_fields(self):
return self.entity_fields
def update_entity_fields(self, record):
self.entity_fields.update(record.iterkeys())
def add_node(self, node):
"""
Add a node to the node list
Returns the node position in the list
"""
# self.node_list.append(node)
# do not actually store the Node,
# just pretend it is at position X (current size of list)
self.node_list_size += 1
node.save_node_id(self.node_list_size)
node_pk = node.get_entity_pk()
if node_pk:
self.reverse_lookup.append(node.entity.name, node_pk, node.get_node_id())
else:
print node, "has no entity PK"
raise RuntimeError
# reset last lookup cache
self.last_lookup, self.last_lookup_result = None, None
return node.get_node_id()
def lookup_node_pos(self, entity_name, entity_pk):
if self.last_lookup == (entity_name, entity_pk):
return self.last_lookup_result
else:
result = self.reverse_lookup.lookup(entity_name, entity_pk)
self.last_lookup = (entity_name, entity_pk)
self.last_lookup_result = result
return result
def iter_nodes(self):
while True:
try:
yield self.node_list.popleft()
except:
break
class RelationList(object):
def __init__(self):
self.relation_list = collections.deque()
def add_relation(self, relation):
self.relation_list.append(relation)
def iter_rels(self):
while True:
try:
yield self.relation_list.popleft()
except:
break
| true |
9bdb150e1d10ebbdb0479011517e3d25527c1a96 | Python | lrq3000/pyFileFixity | /pyFileFixity/lib/profilers/visual/runsnakerun/squaremap/squaremap.py | UTF-8 | 21,515 | 2.890625 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env python
import wx, sys, os, logging, operator
import wx.lib.newevent
log = logging.getLogger( 'squaremap' )
#log.setLevel( logging.DEBUG )
SquareHighlightEvent, EVT_SQUARE_HIGHLIGHTED = wx.lib.newevent.NewEvent()
SquareSelectionEvent, EVT_SQUARE_SELECTED = wx.lib.newevent.NewEvent()
SquareActivationEvent, EVT_SQUARE_ACTIVATED = wx.lib.newevent.NewEvent()
class HotMapNavigator(object):
''' Utility class for navigating the hot map and finding nodes. '''
@classmethod
def findNode(class_, hot_map, targetNode, parentNode=None):
''' Find the target node in the hot_map. '''
for index, (rect, node, children) in enumerate(hot_map):
if node == targetNode:
return parentNode, hot_map, index
result = class_.findNode(children, targetNode, node)
if result:
return result
return None
if hasattr( wx.Rect, 'Contains' ):
# wx 2.8+
@classmethod
def findNodeAtPosition(class_, hot_map, position, parent=None):
''' Retrieve the node at the given position. '''
for rect, node, children in hot_map:
if rect.Contains(position):
return class_.findNodeAtPosition(children, position, node)
return parent
else:
# wx 2.6
@classmethod
def findNodeAtPosition(class_, hot_map, position, parent=None):
''' Retrieve the node at the given position. '''
for rect, node, children in hot_map:
if rect.Inside(position):
return class_.findNodeAtPosition(children, position, node)
return parent
@staticmethod
def firstChild(hot_map, index):
''' Return the first child of the node indicated by index. '''
children = hot_map[index][2]
if children:
return children[0][1]
else:
return hot_map[index][1] # No children, return the node itself
@staticmethod
def nextChild(hotmap, index):
''' Return the next sibling of the node indicated by index. '''
nextChildIndex = min(index + 1, len(hotmap) - 1)
return hotmap[nextChildIndex][1]
@staticmethod
def previousChild(hotmap, index):
''' Return the previous sibling of the node indicated by index. '''
previousChildIndex = max(0, index - 1)
return hotmap[previousChildIndex][1]
@staticmethod
def firstNode(hot_map):
''' Return the very first node in the hot_map. '''
return hot_map[0][1]
@classmethod
def lastNode(class_, hot_map):
''' Return the very last node (recursively) in the hot map. '''
children = hot_map[-1][2]
if children:
return class_.lastNode(children)
else:
return hot_map[-1][1] # Return the last node
class SquareMap( wx.Panel ):
"""Construct a nested-box trees structure view"""
BackgroundColor = wx.Colour( 128,128,128 )
max_depth = None
max_depth_seen = None
def __init__(
self, parent=None, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.TAB_TRAVERSAL|wx.NO_BORDER|wx.FULL_REPAINT_ON_RESIZE,
name='SquareMap', model = None,
adapter = None,
labels = True,
highlight = True,
padding = 2,
margin = 0,
square_style = False,
):
"""Initialise the SquareMap
adapter -- a DefaultAdapter or same-interface instance providing SquareMap data api
labels -- set to True (default) to draw textual labels within the boxes
highlight -- set to True (default) to highlight nodes on mouse-over
padding -- spacing within each square and its children (within the square's border)
margin -- spacing around each square (on all sides)
square_style -- use a more-recursive, less-linear, more "square" layout style which
works better on objects with large numbers of children, such as Meliae memory
dumps, works fine on profile views as well, but the layout is less obvious wrt
what node is "next" "previous" etc.
"""
super( SquareMap, self ).__init__(
parent, id, pos, size, style, name
)
self.model = model
self.padding = padding
self.square_style = square_style
self.margin = margin
self.labels = labels
self.highlight = highlight
self.selectedNode = None
self.highlightedNode = None
self._buffer = wx.EmptyBitmap(20, 20) # Have a default buffer ready
self.Bind( wx.EVT_PAINT, self.OnPaint)
self.Bind( wx.EVT_SIZE, self.OnSize )
if highlight:
self.Bind( wx.EVT_MOTION, self.OnMouse )
self.Bind( wx.EVT_LEFT_UP, self.OnClickRelease )
self.Bind( wx.EVT_LEFT_DCLICK, self.OnDoubleClick )
self.Bind( wx.EVT_KEY_UP, self.OnKeyUp )
self.hot_map = []
self.adapter = adapter or DefaultAdapter()
self.DEFAULT_PEN = wx.Pen( wx.BLACK, 1, wx.SOLID )
self.SELECTED_PEN = wx.Pen( wx.WHITE, 2, wx.SOLID )
self.OnSize(None)
def OnMouse( self, event ):
"""Handle mouse-move event by selecting a given element"""
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
self.SetHighlight( node, event.GetPosition() )
def OnClickRelease( self, event ):
"""Release over a given square in the map"""
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
self.SetSelected( node, event.GetPosition() )
def OnDoubleClick(self, event):
"""Double click on a given square in the map"""
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
if node:
wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) )
def OnKeyUp(self, event):
event.Skip()
if not self.selectedNode or not self.hot_map:
return
if event.KeyCode == wx.WXK_HOME:
self.SetSelected(HotMapNavigator.firstNode(self.hot_map))
return
elif event.KeyCode == wx.WXK_END:
self.SetSelected(HotMapNavigator.lastNode(self.hot_map))
return
try:
parent, children, index = HotMapNavigator.findNode(self.hot_map, self.selectedNode)
except TypeError, err:
log.info( 'Unable to find hot-map record for node %s', self.selectedNode )
else:
if event.KeyCode == wx.WXK_DOWN:
self.SetSelected(HotMapNavigator.nextChild(children, index))
elif event.KeyCode == wx.WXK_UP:
self.SetSelected(HotMapNavigator.previousChild(children, index))
elif event.KeyCode == wx.WXK_RIGHT:
self.SetSelected(HotMapNavigator.firstChild(children, index))
elif event.KeyCode == wx.WXK_LEFT and parent:
self.SetSelected(parent)
elif event.KeyCode == wx.WXK_RETURN:
wx.PostEvent(self, SquareActivationEvent(node=self.selectedNode,
map=self))
def GetSelected(self):
return self.selectedNode
def SetSelected( self, node, point=None, propagate=True ):
"""Set the given node selected in the square-map"""
if node == self.selectedNode:
return
self.selectedNode = node
self.UpdateDrawing()
if node:
wx.PostEvent( self, SquareSelectionEvent( node=node, point=point, map=self ) )
def SetHighlight( self, node, point=None, propagate=True ):
"""Set the currently-highlighted node"""
if node == self.highlightedNode:
return
self.highlightedNode = node
# TODO: restrict refresh to the squares for previous node and new node...
self.UpdateDrawing()
if node and propagate:
wx.PostEvent( self, SquareHighlightEvent( node=node, point=point, map=self ) )
def SetModel( self, model, adapter=None ):
"""Set our model object (root of the tree)"""
self.model = model
if adapter is not None:
self.adapter = adapter
self.UpdateDrawing()
def OnPaint(self, event):
dc = wx.BufferedPaintDC(self, self._buffer)
def OnSize(self, event):
# The buffer is initialized in here, so that the buffer is always
# the same size as the Window.
width, height = self.GetClientSizeTuple()
if width <= 0 or height <=0:
return
# Make new off-screen bitmap: this bitmap will always have the
# current drawing in it, so it can be used to save the image to
# a file, or whatever.
if width and height:
# Macs can generate events with 0-size values
self._buffer = wx.EmptyBitmap(width, height)
self.UpdateDrawing()
def UpdateDrawing(self):
dc = wx.BufferedDC(wx.ClientDC(self), self._buffer)
self.Draw(dc)
def Draw(self, dc):
''' Draw the tree map on the device context. '''
self.hot_map = []
dc.BeginDrawing()
brush = wx.Brush( self.BackgroundColour )
dc.SetBackground( brush )
dc.Clear()
if self.model:
self.max_depth_seen = 0
font = self.FontForLabels(dc)
dc.SetFont(font)
self._em_size_ = dc.GetFullTextExtent( 'm', font )[0]
w, h = dc.GetSize()
self.DrawBox( dc, self.model, 0,0,w,h, hot_map = self.hot_map )
dc.EndDrawing()
def FontForLabels(self, dc):
''' Return the default GUI font, scaled for printing if necessary. '''
font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
scale = dc.GetPPI()[0] / wx.ScreenDC().GetPPI()[0]
font.SetPointSize(scale*font.GetPointSize())
return font
def BrushForNode( self, node, depth=0 ):
"""Create brush to use to display the given node"""
if node == self.selectedNode:
color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
elif node == self.highlightedNode:
color = wx.Colour( red=0, green=255, blue=0 )
else:
color = self.adapter.background_color(node, depth)
if not color:
red = (depth * 10)%255
green = 255-((depth * 5)%255)
blue = (depth * 25)%255
color = wx.Colour( red, green, blue )
return wx.Brush( color )
def PenForNode( self, node, depth=0 ):
"""Determine the pen to use to display the given node"""
if node == self.selectedNode:
return self.SELECTED_PEN
return self.DEFAULT_PEN
def TextForegroundForNode(self, node, depth=0):
"""Determine the text foreground color to use to display the label of
the given node"""
if node == self.selectedNode:
fg_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
else:
fg_color = self.adapter.foreground_color(node, depth)
if not fg_color:
fg_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)
return fg_color
def DrawBox( self, dc, node, x,y,w,h, hot_map, depth=0 ):
"""Draw a model-node's box and all children nodes"""
log.debug( 'Draw: %s to (%s,%s,%s,%s) depth %s',
node, x,y,w,h, depth,
)
if self.max_depth and depth > self.max_depth:
return
self.max_depth_seen = max( (self.max_depth_seen,depth))
dc.SetBrush( self.BrushForNode( node, depth ) )
dc.SetPen( self.PenForNode( node, depth ) )
# drawing offset by margin within the square...
dx,dy,dw,dh = x+self.margin,y+self.margin,w-(self.margin*2),h-(self.margin*2)
if sys.platform == 'darwin':
# Macs don't like drawing small rounded rects...
if w < self.padding*2 or h < self.padding*2:
dc.DrawRectangle( dx,dy,dw,dh )
else:
dc.DrawRoundedRectangle( dx,dy,dw,dh, self.padding )
else:
dc.DrawRoundedRectangle( dx,dy,dw,dh, self.padding*3 )
# self.DrawIconAndLabel(dc, node, x, y, w, h, depth)
children_hot_map = []
hot_map.append( (wx.Rect( int(x),int(y),int(w),int(h)), node, children_hot_map ) )
x += self.padding
y += self.padding
w -= self.padding*2
h -= self.padding*2
empty = self.adapter.empty( node )
icon_drawn = False
if self.max_depth and depth == self.max_depth:
self.DrawIconAndLabel(dc, node, x, y, w, h, depth)
icon_drawn = True
elif empty:
# is a fraction of the space which is empty...
log.debug( ' empty space fraction: %s', empty )
new_h = h * (1.0-empty)
self.DrawIconAndLabel(dc, node, x, y, w, h-new_h, depth)
icon_drawn = True
y += (h-new_h)
h = new_h
if w >self.padding*2 and h> self.padding*2:
children = self.adapter.children( node )
if children:
log.debug( ' children: %s', children )
self.LayoutChildren( dc, children, node, x,y,w,h, children_hot_map, depth+1 )
else:
log.debug( ' no children' )
if not icon_drawn:
self.DrawIconAndLabel(dc, node, x, y, w, h, depth)
else:
log.debug( ' not enough space: children skipped' )
def DrawIconAndLabel(self, dc, node, x, y, w, h, depth):
''' Draw the icon, if any, and the label, if any, of the node. '''
if w-2 < self._em_size_//2 or h-2 < self._em_size_ //2:
return
dc.SetClippingRegion(x+1, y+1, w-2, h-2) # Don't draw outside the box
try:
icon = self.adapter.icon(node, node==self.selectedNode)
if icon and h >= icon.GetHeight() and w >= icon.GetWidth():
iconWidth = icon.GetWidth() + 2
dc.DrawIcon(icon, x+2, y+2)
else:
iconWidth = 0
if self.labels and h >= dc.GetTextExtent('ABC')[1]:
dc.SetTextForeground(self.TextForegroundForNode(node, depth))
dc.DrawText(self.adapter.label(node), x + iconWidth + 2, y+2)
finally:
dc.DestroyClippingRegion()
def LayoutChildren( self, dc, children, parent, x,y,w,h, hot_map, depth=0, node_sum=None ):
"""Layout the set of children in the given rectangle
node_sum -- if provided, we are a recursive call that already has sizes and sorting,
so skip those operations
"""
if node_sum is None:
nodes = [ (self.adapter.value(node,parent),node) for node in children ]
nodes.sort(key=operator.itemgetter(0))
total = self.adapter.children_sum( children,parent )
else:
nodes = children
total = node_sum
if total:
if self.square_style and len(nodes) > 5:
# new handling to make parents with large numbers of parents a little less
# "sliced" looking (i.e. more square)
(head_sum,head),(tail_sum,tail) = split_by_value( total, nodes )
if head and tail:
# split into two sub-boxes and render each...
head_coord,tail_coord = split_box( head_sum/float(total), x,y,w,h )
if head_coord:
self.LayoutChildren(
dc, head, parent, head_coord[0],head_coord[1],head_coord[2],head_coord[3],
hot_map, depth,
node_sum = head_sum,
)
if tail_coord and coord_bigger_than_padding( tail_coord, self.padding+self.margin ):
self.LayoutChildren(
dc, tail, parent, tail_coord[0],tail_coord[1],tail_coord[2],tail_coord[3],
hot_map, depth,
node_sum = tail_sum,
)
return
(firstSize,firstNode) = nodes[-1]
fraction = firstSize/float(total)
head_coord,tail_coord = split_box( firstSize/float(total), x,y,w,h )
if head_coord:
self.DrawBox(
dc, firstNode, head_coord[0],head_coord[1],head_coord[2],head_coord[3],
hot_map, depth+1
)
else:
return # no other node will show up as non-0 either
if len(nodes) > 1 and tail_coord and coord_bigger_than_padding( tail_coord, self.padding+self.margin ):
self.LayoutChildren(
dc, nodes[:-1], parent,
tail_coord[0],tail_coord[1],tail_coord[2],tail_coord[3],
hot_map, depth,
node_sum = total - firstSize,
)
def coord_bigger_than_padding( tail_coord, padding ):
return (
tail_coord and
tail_coord[2] > padding * 2 and
tail_coord[3] > padding * 2
)
def split_box( fraction, x,y, w,h ):
"""Return set of two boxes where first is the fraction given"""
if w >= h:
new_w = int(w*fraction)
if new_w:
return (x,y,new_w,h),(x+new_w,y,w-new_w,h)
else:
return None,None
else:
new_h = int(h*fraction)
if new_h:
return (x,y,w,new_h),(x,y+new_h,w,h-new_h)
else:
return None,None
def split_by_value( total, nodes, headdivisor=2.0 ):
"""Produce, (sum,head),(sum,tail) for nodes to attempt binary partition"""
head_sum,tail_sum = 0,0
divider = 0
for node in nodes[::-1]:
if head_sum < total/headdivisor:
head_sum += node[0]
divider -= 1
else:
break
return (head_sum,nodes[divider:]),(total-head_sum,nodes[:divider])
class DefaultAdapter( object ):
"""Default adapter class for adapting node-trees to SquareMap API"""
def children( self, node ):
"""Retrieve the set of nodes which are children of this node"""
return node.children
def value( self, node, parent=None ):
"""Return value used to compare size of this node"""
return node.size
def label( self, node ):
"""Return textual description of this node"""
return node.path
def overall( self, node ):
"""Calculate overall size of the node including children and empty space"""
return sum( [self.value(value,node) for value in self.children(node)] )
def children_sum( self, children,node ):
"""Calculate children's total sum"""
return sum( [self.value(value,node) for value in children] )
def empty( self, node ):
"""Calculate empty space as a fraction of total space"""
overall = self.overall( node )
if overall:
return (overall - self.children_sum( self.children(node), node))/float(overall)
return 0
def background_color(self, node, depth):
''' The color to use as background color of the node. '''
return None
def foreground_color(self, node, depth):
''' The color to use for the label. '''
return None
def icon(self, node, isSelected):
''' The icon to display in the node. '''
return None
def parents( self, node ):
"""Retrieve/calculate the set of parents for the given node"""
return []
class TestApp(wx.App):
"""Basic application for holding the viewing Frame"""
def OnInit(self):
"""Initialise the application"""
wx.InitAllImageHandlers()
self.frame = frame = wx.Frame( None,
)
frame.CreateStatusBar()
model = model = self.get_model( sys.argv[1])
self.sq = SquareMap( frame, model=model)
EVT_SQUARE_HIGHLIGHTED( self.sq, self.OnSquareSelected )
frame.Show(True)
self.SetTopWindow(frame)
return True
def get_model( self, path ):
nodes = []
for f in os.listdir( path ):
full = os.path.join( path,f )
if not os.path.islink( full ):
if os.path.isfile( full ):
nodes.append( Node( full, os.stat( full ).st_size, () ) )
elif os.path.isdir( full ):
nodes.append( self.get_model( full ))
return Node( path, sum([x.size for x in nodes]), nodes )
def OnSquareSelected( self, event ):
text = self.sq.adapter.label( event.node )
self.frame.SetToolTipString( text )
class Node( object ):
"""Really dumb file-system node object"""
def __init__( self, path, size, children ):
self.path = path
self.size = size
self.children = children
def __repr__( self ):
return '%s( %r, %r, %r )'%( self.__class__.__name__, self.path, self.size, self.children )
usage = 'squaremap.py somedirectory'
def main():
"""Mainloop for the application"""
if not sys.argv[1:]:
print usage
else:
app = TestApp(0)
app.MainLoop()
if __name__ == "__main__":
main()
| true |
8324fa28f571944426acc35ad5f1ee6b0cbd945d | Python | Krispy2009/work_play | /sb2.py | UTF-8 | 3,672 | 3.4375 | 3 | [] | no_license |
from string import ascii_lowercase
import sys
global finished
global queue
global my_words
queue = []
class Node:
def __init__(self, word, parent=None):
self.word = word
self.children = []
self.parent = parent
def get_children(self):
global my_words
#change the word to a list to change its letters
word = list(self.word)
for position in range(len(word)):
temp = word[:]
for letter in list(ascii_lowercase):
temp[position] = letter
new_word = ''.join(temp)
if my_words.has_key(new_word) and my_words[new_word] == 0:
new_node = Node(new_word,parent=self)
self.children.append(new_node)
my_words[new_word] = 1
def load_words(location):
f = file(location).read()
return f
def get_words(all_words,word_length):
global my_words
my_words = {}
for word in all_words.split():
if len(word) is word_length:
my_words[word.lower()] = 0
return my_words
def process(my_words, start_node, end):
global finished
global queue
#words reached by changing 1 letter
similar_words ={}
#starting temporary word
top_temp = list(start_node.word)
#hold parent of current node
parent = start_node.parent
#delete start word from list
if my_words[start_node.word] == 0:
my_words[start_node.word] = 1
#get the children of the current(start) node
start_node.get_children()
curr_children = start_node.children
#for everyone of the new children, build queue
for child in curr_children:
#if we reach the end word we are finished
if child.word == end:
finished = True
print 'reached end word'
path = []
#print the path from the end to the start word
while child.parent is not None:
path.append(child.word)
child = child.parent
path.append(child.word)
path.reverse()
print path
break
#if current_node word is in the english dictionary then add
# to similar and remove from my_words
if child not in similar_words:
parent = child.parent
similar_words[child] = 1
#add every node from similar words into queue if it is not there
for node in similar_words:
if node not in queue:
queue.append(node)
if __name__ == '__main__':
global finished
args = sys.argv
start_word = args[1]
end_word = args[2]
start_node = Node(start_word)
finished = False
w = load_words('/usr/share/dict/words')
if len(start_word) == len(end_word):
word_length = len(start_word)
else:
print """ Word length does not match! Make sure you are using two words of the same length """
sys.exit(0)
#start the process with the start_node
process(get_words(w,len(start_word)),start_node,end_word)
while queue:
#first node from queue
first_node = queue.pop(0)
#if it is in my_words delete it
if first_node.word in my_words:
my_words[first_node.word] = 1
#if no valid path is found, inform the user
if finished == False and len(queue) == 0:
print ("There is no way to reach %s from %s "
"through the English dictionary") % (start_word,end_word)
#if we are still looking, continue with the first node from queue
if finished == False:
process(my_words, first_node, end_word)
| true |
0168715b4c52906c130662e8ecbb11b04cbe6551 | Python | sashkab/updaters | /pip_depend.py | UTF-8 | 471 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env python
# Dependency finder for python packages
import pip
from pprint import pprint
d = {}
for dist in pip.get_installed_distributions():
p = dist.project_name
rev_dep = [
pkg.project_name for pkg in pip.get_installed_distributions() if p in
[requirement.project_name for requirement in pkg.requires()]
]
for x in rev_dep:
if p in d:
d[p].append(x)
else:
d[p] = [x]
pprint(d)
| true |
32bd1bfad6a6ce89562a12dc09a313f70ffc4114 | Python | Gu-Youngfeng/Config-Optimization | /experiments/min_flash.py | UTF-8 | 1,475 | 3.15625 | 3 | [
"Apache-2.0"
] | permissive | #!\usr\bin\python
# coding=utf-8
# Author: youngfeng
# Update: 07/17/2018
"""
This code is used to find the lowest rank in validation pool (top-10) by using flash method
"""
import sys
sys.path.append("../")
import os
from Flash import find_lowest_rank
from Flash import predict_by_flash
from Flash import split_data_by_fraction
import numpy as np
if __name__ == "__main__":
projs = ["../data/"+name for name in os.listdir("../data") if ".csv" in name]
ave_rank_lst = []
for proj in projs:
print(proj)
ave_top_10_act_rank = []
for round in range(50):
# print(">> Using FLASH Method to Predict the Validation Pool\n")
# select 80% data
dataset = split_data_by_fraction(proj, 0.8)
# print("### initialzation")
# for i in dataset:
# print(str(i.index), ",", end="")
# print("\n-------------")
data = predict_by_flash(dataset)
# print("### finally split")
train_set = data[0]
uneval_set = data[1]
# for i in train_set:
# print(str(i.index), ",", end="")
# print("\n-------------")
# for i in uneval_set:
# print(str(i.index), ",", end="")
# print("\n-------------")
lowest_rank = find_lowest_rank(train_set, uneval_set)
ave_top_10_act_rank.append(lowest_rank)
print("[mini rank]: ", ave_top_10_act_rank)
minest_rank = np.mean(ave_top_10_act_rank)
print("[mean rank]: ", minest_rank, "\n")
ave_rank_lst.append(minest_rank)
print("-------------------------------")
print(ave_rank_lst)
| true |
a4dc1e68f1666f70c0ba0f73113fde616bf7b41b | Python | slauniainen/pyAPES-MXL | /wind_profile_inoue.py | UTF-8 | 630 | 2.65625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu May 16 12:45:13 2019
@author: slauniai
"""
import numpy as np
import matplotlib.pyplot as plt
#: machine epsilon
EPS = np.finfo(float).eps
Uo = 0.1
usto = 0.1
LAI = 5.0
a = LAI / 2.0
hc = 0.1
N = 20
dz = hc / N
z = np.arange(0, hc + dz, dz)
tau = usto**2 * np.exp(2*a*(z / hc - 1.0))
U = Uo * np.exp(a * (z / hc - 1.0))
dUdz = Uo * a / hc * np.exp(a * (z / hc - 1.0))
dU = np.diff(U)/dz
b = (usto / Uo)**2
L = 2*b*hc/LAI
plt.figure()
plt.subplot(221); plt.plot(U, z)
plt.subplot(222); plt.plot(tau, z)
plt.subplot(223); plt.plot(dUdz, z)
plt.subplot(223); plt.plot(dU, z[1:])
| true |
db293663fe920cbde83da9d297bd213f3474907c | Python | xiantang/AsianGames | /MedalRankRobot.py | UTF-8 | 779 | 2.546875 | 3 | [] | no_license | import json
import re
from lxml import etree
from WebRequest import WebRequest
class MedalRankRobot(WebRequest):
def __init__(self, start_url):
super().__init__()
self.start_url = start_url
def parse_start_html(self):
raw_json = self.get(self.start_url).text
raw_json = re.findall("nkSucc\((.*?)\)", raw_json)[0]
return raw_json
def to_local(self, medal_json):
with open("json/MedalRank.json", "w") as f:
f.write(medal_json)
def run(self):
medal_json = self.parse_start_html()
self.to_local(medal_json)
if __name__ == '__main__':
url = "https://2018ag.sports.qq.com/api/rank.php?callback=callbackYayunhuiRankSucc&_=1535865899219"
mrb = MedalRankRobot(url)
mrb.run()
| true |
8505a0a29430cb2630e68180078dc937df0a6c6d | Python | Mahad-Khan/Verification_API | /pipeline/utils/pdf417reader.py | UTF-8 | 1,464 | 2.703125 | 3 | [] | no_license | import zxing
import os
from PIL import Image
import sys
# get barcode directory full path
test_barcode_dir = os.path.join(os.path.dirname(__file__), "barcodes")
# get actual barcodereader
test_reader = zxing.BarCodeReader()
# filenames = ["vert_rev", "vert_norm", "horz_right", "horz_left"]
filenames = ["free_bottom", "free_mid", "free_top"]
# we have jpg filenames, now iterate and create bmps in barcodes
test_barcodes = []
for name in filenames:
temp = name + ".bmp"
try:
dl_img = Image.open(os.path.join(test_barcode_dir, name + ".jpg"))
except IOError:
print("unable to load image")
sys.exit(1)
dl_img.save("barcodes/" + temp, "bmp")
test_barcodes.append([(temp, "PDF_417", "This should be PDF_417")])
dl_img.close()
print(test_barcodes)
def try_barcode(obj):
global test_reader
for filename, expected_format, expected_raw in obj:
path = os.path.join(test_barcode_dir, filename)
print("trying ", filename)
try:
dec = test_reader.decode(
path, possible_formats=expected_format, try_harder=True
)
if dec.parsed != "":
print("it worked!")
print(dec.parsed)
else:
print("no!")
except zxing.BarCodeReaderException:
print("no scan!")
for barcode in test_barcodes:
try_barcode(barcode)
| true |
adb7d3ce201a3df94010d0fe4c543b3044e4b191 | Python | bajram-a/Basic-Programing-Examples | /Inputs and Basic Math/Exercise1.2.py | UTF-8 | 245 | 3.65625 | 4 | [] | no_license | """Write a program that takes from the user a value 'r' that signifies a radius.
The program then calculates the surface area of the circle and its circumference"""
from math import pi
r = float(input())
sur_area = r**2 * pi
cir = 2 * pi * r
| true |
29c4939e576d583c7582bbc890dc704d92c8f6c8 | Python | rkuo2000/cv2 | /jpg_houghlinesP.py | UTF-8 | 453 | 2.6875 | 3 | [] | no_license | import numpy as np
import cv2
img = cv2.imread('testpic.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
edge = cv2.Canny(blur, 100, 200)
cv2.imshow("edge", edge)
lines = cv2.HoughLinesP(edge, 1, np.pi/180, 100)
print(lines)
for i in range(0, len(lines)):
for x1,y1,x2,y2 in lines[i]:
cv2.line(img,(x1,y1),(x2,y2),(0,0,255), 2)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
| true |
bc828fbc7227dac4cdfee351ffc690ab299bf2ea | Python | awslabs/aws-emr-launch | /examples/spark_batch_orchestration/infrastructure/emr_orchestration/steps/data_preparation.py | UTF-8 | 2,572 | 2.671875 | 3 | [
"MIT-0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | import argparse
import functools
import sys
import boto3
from pyspark.sql import SparkSession # noqa
from pyspark.sql import functions as F # noqa
def union_all(dfs):
return functools.reduce(lambda df1, df2: df1.union(df2.select(df1.columns)), dfs)
def parse_arguments(args):
parser = argparse.ArgumentParser()
parser.add_argument("--batch-metadata-table-name", required=True)
parser.add_argument("--batch-id", required=True)
parser.add_argument("--input-bucket", required=True)
parser.add_argument("--region", required=True)
return parser.parse_args(args=args)
def get_batch_file_metadata(table_name, batch_id, region):
dynamodb = boto3.resource("dynamodb", region_name=region)
table = dynamodb.Table(table_name)
response = table.query(KeyConditions={"BatchId": {"AttributeValueList": [batch_id], "ComparisonOperator": "EQ"}})
data = response["Items"]
while "LastEvaluatedKey" in response:
response = table.query(ExclusiveStartKey=response["LastEvaluatedKey"])
data.update(response["Items"])
return data
def load_partition(spark, bucket, partition):
s3path = "s3://" + bucket + "/" + partition + "/*"
df = spark.read.load(s3path)
return df
def load_and_union_data(spark, batch_metadata, input_bucket):
distinct_partitions = list(set([x["FilePartition"] for x in batch_metadata]))
partition_dfs = {}
for partition in distinct_partitions:
dfs = [
load_partition(spark, bucket=input_bucket, partition=partition)
for x in batch_metadata
if x["FilePartition"] == partition
]
partition_dfs[partition] = union_all(dfs)
return partition_dfs
def main(args, spark):
arguments = parse_arguments(args)
# Load metadata to process
batch_metadata = get_batch_file_metadata(
table_name=arguments.batch_metadata_table_name, batch_id=arguments.batch_id, region=arguments.region
)
input_bucket = arguments.input_bucket
input_data = load_and_union_data(spark, batch_metadata, input_bucket)
input_dfs = []
for dataset, df in input_data.items():
input_dfs.append(df)
# get input dataframe
input_df = union_all(input_dfs)
# add extra column to input dataframe
input_df = input_df.withColumn("current_ts", F.current_timestamp())
input_df.printSchema()
input_df.show()
if __name__ == "__main__":
spark = SparkSession.builder.appName("data-preparation").getOrCreate()
sc = spark.sparkContext
main(sys.argv[1:], spark)
sc.stop()
| true |
be85be354798334c2e42afe2440c847bde1f6876 | Python | lirun-sat/brahe | /brahe/astro.py | UTF-8 | 12,441 | 3.28125 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""This module provides functions to convert between different representations
of orbital coordinates. As well as functions to compute properties of the orbits
themselves.
"""
# Imports
import logging
import typing
import math as math
import copy as copy
import numpy as np
# Brahe Imports
from brahe.utils import logger, AbstractArray, fcross
import brahe.constants as _constants
# Get Logger
logger = logging.getLogger(__name__)
###########################
# Astrodynamic Properties #
###########################
def mean_motion(a:float, use_degrees:bool=False, gm:float=_constants.GM_EARTH) -> float:
"""Compute the mean motion given a semi-major axis.
Args:
a (:obj:`float`): Semi-major axis. Units: *m*
use_degrees (bool): If ``True`` returns result in units of degrees.
gm (:obj:`float`): Gravitational constant of central body. Defaults to
``brahe.constants.GM_EARTH`` if not provided. Units: *m^3/s^2*
Returns:
n (:obj:`float`): Orbital mean motion. Units: *rad/s* or *deg/s*
"""
n = math.sqrt(gm/a**3)
if use_degrees:
n *= 180.0/math.pi
return n
def semimajor_axis(n:float, use_degrees:bool=False, gm:float=_constants.GM_EARTH) -> float:
"""Compute the semi-major axis given the mean-motion
Args:
n (:obj:`float`): Orbital mean motion. Units: *rad/s* or *deg/s*
use_degrees (bool): If ``True`` returns result in units of degrees.
gm (:obj:`float`): Gravitational constant of central body. Defaults to
``brahe.constants.GM_EARTH`` if not provided. Units: *m^3/s^2*
Returns:
a (:obj:`float`): Semi-major axis. Units: *m*
"""
if use_degrees:
n *= math.pi/180.0
a = (gm/n**2)**(1.0/3.0)
return a
def orbital_period(a:float, gm:float=_constants.GM_EARTH) -> float:
"""Compute the orbital period given the semi-major axis.
Arguments:
a (:obj:`float`): Semi-major axis. Units: *m*
gm (:obj:`float`): Gravitational constant of central body. Defaults to
``brahe.constants.GM_EARTH`` if not provided. Units: *m^3/s^2*
Returns:
T (:obj:`float`): Orbital period. Units: *s*
"""
return 2.0*math.pi*math.sqrt(a**3/gm)
def perigee_velocity(a:typing.Union[float, AbstractArray], e:float, gm:float=_constants.GM_EARTH) -> float:
'''Compute the perigee velocity from orbital element state. Accepts input as
semi-major axis and eccentricity or a Keplerian state vector.
Args:
a (:obj:`Union[float, AbstractArray]`): Input semi-major axis or Keplerian state vector
e (:obj:`Union[float, AbstractArray]`): Input eccentricity. Unused if a vector is provided for first argument.
gm (:obj:`float`): Gravitational constant of central body. Defaults to
``brahe.constants.GM_EARTH`` if not provided. Units: *m^3/s^2*
Returns:
v_per (:obj:`float`): Velocity at perigee
'''
# Expand array inputs
if type(a) in [list, tuple, np.ndarray]:
a, e = a[0], a[1]
return math.sqrt(gm/a)*math.sqrt((1+e)/(1-e))
def apogee_velocity(a:typing.Union[float, AbstractArray], e:float, gm:float=_constants.GM_EARTH) -> float:
'''Compute the apogee velocity from orbital element state. Accepts input as
semi-major axis and eccentricity or a Keplerian state vector.
Args:
a (:obj:`Union[float, AbstractArray]`): Input semi-major axis or Keplerian state vector
e (:obj:`Union[float, AbstractArray]`): Input eccentricity. Unused if a vector is provided for first argument.
gm (:obj:`float`): Gravitational constant of central body. Defaults to
``brahe.constants.GM_EARTH`` if not provided. Units: *m^3/s^2*
Returns:
v_apo (:obj:`float`): Velocity at apogee
'''
# Expand array inputs
if type(a) in [list, tuple, np.ndarray]:
a, e = a[0], a[1]
return math.sqrt(gm/a)*math.sqrt((1-e)/(1+e))
def sun_sync_inclination(a:float, e:float, use_degrees:bool=False) -> float:
"""Compute the required inclination for a Sun-synchronous Earth orbit.
Algorithm assumes the nodal precession is entirely due to the J2 perturbation,
and no other perturbations are considered. The inclination is computed using
a first-order, non-iterative approximation.
Args:
a (:obj:`float`): Semi-major axis. Units: *m*
e (:obj:`float`) Eccentricity. Units: *dimensionless*
use_degrees (obj:`bool`): Return output in degrees (Default: false)
Returns:
i (:obj:`float`): Required inclination for a sun-synchronous orbit. Units: *rad* or *deg*
"""
# Compute the required RAAN precession of a sun-synchronous orbit
OMEGA_DOT_SS = 2.0*math.pi/365.2421897/86400.0
# Inclination required for sun-synchronous orbits
i = math.acos(-2.0 * a**(7/2) * OMEGA_DOT_SS * (1-e**2)**2 /
(3*(_constants.R_EARTH**2) * _constants.J2_EARTH * math.sqrt(_constants.GM_EARTH)))
if use_degrees:
i *= 180.0/math.pi
return i
def anm_eccentric_to_mean(E:float, e:float, use_degrees:bool=False) -> float:
"""Convert eccentric anomaly into mean anomaly.
Args:
E (:obj:`float`): Eccentric anomaly. Units: *rad* or *deg*
e (:obj:`float`): Eccentricity. Units: *dimensionless*
use_degrees (bool): Handle input and output in degrees (Default: false)
Returns:
M (:obj:`float`): Mean anomaly. Units: *rad* or *deg*
"""
# Convert degree input
if use_degrees:
E *= math.pi/180.0
# Convert eccentric to mean
M = E - e*math.sin(E)
# Convert degree output
if use_degrees:
M *= 180.0/math.pi
return M
def anm_mean_to_eccentric(M:float, e:float, use_degrees:bool=False) -> float:
"""Convert mean anomaly into eccentric anomaly.
Args:
M (:obj:`float`): Mean anomaly. Units: *rad* or *deg*
e (:obj:`float`): Eccentricity. Units: *dimensionless*
use_degrees (bool): Handle input and output in degrees (Default: false)
Returns:
E (:obj:`float`): Eccentric anomaly. Units: *rad* or *deg*
"""
# Convert degree input
if use_degrees:
M *= math.pi/180.0
# Convert mean to eccentric
max_iter = 15
eps = np.finfo(float).eps*100
# Initialize starting values
M = math.fmod(M, 2.0*math.pi)
if e < 0.8:
E = M
else:
E = math.pi
# Initialize working variable
f = E - e*math.sin(E) - M
i = 0
# Iterate until convergence
while math.fabs(f) > eps:
f = E - e*math.sin(E) - M
E = E - f / (1.0 - e*math.cos(E))
# Increase iteration counter
i += 1
if i == max_iter:
raise RuntimeError("Maximum number of iterations reached before convergence.")
# Convert degree output
if use_degrees:
E *= 180.0/math.pi
return E
##########################
# Orbital Element States #
##########################
def sOSCtoCART(x_oe:AbstractArray, use_degrees:bool=False, gm:float=_constants.GM_EARTH) -> np.ndarray:
"""Given an orbital state expressed in osculating orbital elements compute
the equivalent Cartesean position and velocity of the inertial state.
The osculating elements are assumed to be (in order):
1. _a_, Semi-major axis Units: *m*
2. _e_, Eccentricity. Units: *dimensionless*
3. _i_, Inclination. Units: *rad* or *deg*
4. _Ω_, Right Ascension of the Ascending Node (RAAN). Units: *rad*
5. _ω_, Argument of Perigee. Units: *rad* or *deg*
6. _M_, Mean anomaly. Units: *rad* or *deg*
Args:
x_oe (np.array_like): Osculating orbital elements. See above for desription of
the elements and their required order.
use_degrees (bool): Handle input and output in degrees (Default: ``False``)
gm (:obj:`float`): Gravitational constant of central body. Defaults to
``brahe.constants.GM_EARTH`` if not provided. Units: *m**3/s**2*
Returns:
x (np.array_like): Cartesean inertial state. Returns position and
velocity. Units: [*m*; *m/s*]
"""
# Ensure input is numpy array
x_oe = np.asarray(x_oe)
# Conver input
if use_degrees:
# Copy and convert input from degrees to radians if necessary
oe = copy.deepcopy(x_oe)
oe[2:6] = oe[2:6]*math.pi/180.0
else:
oe = x_oe
# Unpack input
a, e, i, RAAN, omega, M = oe
E = anm_mean_to_eccentric(M, e)
# Create perifocal coordinate vectors
P = np.zeros((3,))
P[0] = math.cos(omega)*math.cos(RAAN) - math.sin(omega)*math.cos(i)*math.sin(RAAN)
P[1] = math.cos(omega)*math.sin(RAAN) + math.sin(omega)*math.cos(i)*math.cos(RAAN)
P[2] = math.sin(omega)*math.sin(i)
Q = np.zeros((3,))
Q[0] = -math.sin(omega)*math.cos(RAAN) - math.cos(omega)*math.cos(i)*math.sin(RAAN)
Q[1] = -math.sin(omega)*math.sin(RAAN) + math.cos(omega)*math.cos(i)*math.cos(RAAN)
Q[2] = math.cos(omega)*math.sin(i)
# Find 3-Dimensional Position
x = np.zeros((6,))
x[0:3] = a*(math.cos(E)-e)*P + a*math.sqrt(1-e*e)*math.sin(E)*Q
x[3:6] = math.sqrt(gm*a)/np.linalg.norm(x[0:3])*(-math.sin(E)*P + math.sqrt(1-e*e)*math.cos(E)*Q)
return x
def sCARTtoOSC(x:AbstractArray, use_degrees:bool=False, gm:float=_constants.GM_EARTH) -> np.ndarray:
"""Given a Cartesean position and velocity in the inertial frame, return the
state expressed in terms of osculating orbital elements.
The osculating elements are assumed to be (in order):
1. _a_, Semi-major axis Units: *m*
2. _e_, Eccentricity. Units: *dimensionless*
3. _i_, Inclination. Units: *rad* or *deg*
4. _Ω_, Right Ascension of the Ascending Node (RAAN). Units: *rad*
5. _ω_, Argument of Perigee. Units: *rad* or *deg*
6. _M_, Mean anomaly. Units: *rad* or *deg*
Args:
x (np.array_like): Cartesean inertial state. Returns position and
velocity. Units: [*m*; *m/s*]
use_degrees (bool): Handle input and output in degrees (Default: ``False``)
gm (:obj:`float`): Gravitational constant of central body. Defaults to
``brahe.constants.GM_EARTH`` if not provided. Units: *m**3/s**2*
Returns:
x_oe (np.array_like): Osculating orbital elements. See above for
desription of the elements and their required order.
"""
# Ensure input is numpy array
x = np.asarray(x)
# Initialize Cartesian Polistion and Velocity
r = x[0:3]
v = x[3:6]
h = fcross(r, v) # Angular momentum vector
W = h/np.linalg.norm(h) # Unit vector along angular momentum vector
i = math.atan2(math.sqrt(W[0]*W[0] + W[1]*W[1]), W[2]) # Compute inclination
OMEGA = math.atan2(W[0], -W[1]) # Right ascension of ascending node # Compute RAAN
p = np.linalg.norm(h)*np.linalg.norm(h)/gm # Semi-latus rectum
a = 1.0/(2.0/np.linalg.norm(r) - np.linalg.norm(v)*np.linalg.norm(v)/gm) # Semi-major axis
n = math.sqrt(gm/(a**3)) # Mean motion
# Numerical stability hack for circular and near-circular orbits
# Ensures that (1-p/a) is always positive
if np.isclose(a, p, atol=1e-9, rtol=1e-8):
p = a
e = math.sqrt(1 - p/a) # Eccentricity
E = math.atan2(np.dot(r, v)/(n*a**2), (1-np.linalg.norm(r)/a)) # Eccentric Anomaly
M = anm_eccentric_to_mean(E, e) # Mean Anomaly
u = math.atan2(r[2], -r[0]*W[1] + r[1]*W[0]) # Mean longiude
nu = math.atan2(math.sqrt(1-e*e)*math.sin(E), math.cos(E)-e) # True Anomaly
omega = u - nu # Argument of perigee
# Correct angles to run from 0 to 2PI
OMEGA = OMEGA + 2.0*math.pi
omega = omega + 2.0*math.pi
M = M + 2.0*math.pi
OMEGA = math.fmod(OMEGA, 2.0*math.pi)
omega = math.fmod(omega, 2.0*math.pi)
M = math.fmod(M, 2.0*math.pi)
# Create Orbital Element Vector
x_oe = np.array([a, e, i, OMEGA, omega, M])
# Convert output to degrees if necessary
if use_degrees:
x_oe[2:6] = x_oe[2:6]*180.0/math.pi
return x_oe | true |
5b12bc77e20454d73602c713a0ecf1aba71c0458 | Python | epistimos/opendata-client-samples-python | /sample_revocation_request.py | UTF-8 | 910 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import opendata
# ADA of the decision to revoke
ada = u'ΑΔΑ...'
# Comment for the revocation request
comment = "reason..."
# Send request
client = opendata.OpendataClient()
client.set_credentials('10599_api', 'User@10599')
response = client.submit_revocation_request(ada, comment)
if response.status_code == 200:
decision = response.json()
print "Το αίτημα ανάκλησης έχει υποβληθεί."
elif response.status_code == 400:
print "Σφάλμα στην υποβολή της πράξης"
elif response.status_code == 401:
print str(response.status_code) + " Σφάλμα αυθεντικοποίησης"
elif response.status_code == 403:
print str(response.status_code) + " Απαγόρευση πρόσβασης"
else:
print("ERROR " + str(response.status_code))
| true |
04a1a95916762c652dfd106eb04d54d53585cd70 | Python | EightFawn/GruppoScommesseBot | /plugins/random_gioco.py | UTF-8 | 753 | 2.828125 | 3 | [] | no_license | import random
from pyrogram import Client, filters
from config.variabili import chatScommesse
@Client.on_message(filters.command("random") & filters.chat(chatScommesse) | filters.regex(r"^Random ❓$"))
def gioco_random(_, message):
giochi = ["Carte", "Tiro Con L'Arco", "Freccette", "Rune", "Dado"]
modalita = ["BO3", "Secca"]
gioco_scelto = random.choice(giochi)
if gioco_scelto == "Tiro Con L'Arco":
modalita_scelta = "Secca"
else:
modalita_scelta = random.choice(modalita)
message.reply(
f"@{message.from_user.username}, sei talmente indeciso da affidare a un computer la tua scelta, immetti i "
f"dati e pochi secondi dopo esce il risultato: giocherai a **{gioco_scelto} {modalita_scelta}**!"
)
| true |
13a49964fa9e908068c82ea217b21ef99d32424e | Python | toreis/ML | /fapprox_q_replay_fixedtarget.py | UTF-8 | 10,846 | 2.90625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
@author: ligraf
basic code from: https://keon.io/deep-q-learning/
target net from: https://towardsdatascience.com/reinforcement-learning-w-keras-openai-dqns-1eed3a5338c
"""
import random
import gym
import numpy as np
import pandas as pd
from collections import deque
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
import time
import matplotlib.pylab as plt
# define directory
# path_to_file = "/Users/linus/Documents/OneDrive/Uni/Master/Reinforcment Learning/project"
path_to_file = r"C:\Users\tobia\OneDrive\Studium\Reinforcement Learning\project"
# path_to_file = r"./Documents/OneDrive/Uni/Master/Reinforcment Learning/project"
#%%
"""
Deep Q-learning Neural Network
"""
# Deep Q-learning Agent
class DQNAgent:
def __init__(self, state_size, action_size, gamma = 0.95, epsilon_decay = 0.99, learning_rate = 0.001):
self.state_size = state_size
self.action_size = action_size
self.memory = deque(maxlen=5000)
self.gamma = gamma # discount rate
self.epsilon = 1.0 # exploration rate
self.epsilon_min = 0.01
self.epsilon_decay = epsilon_decay
self.learning_rate = learning_rate
self.model = self._build_model()
# initiate fixed target model
self.target_model = self._build_model()
self.tau = 0.05
def _build_model(self):
# Neural Net for Deep-Q learning Model
model = Sequential()
model.add(Dense(64, input_dim=self.state_size, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(self.action_size, activation='linear'))
model.compile(loss='mse',
optimizer=Adam(lr=self.learning_rate))
return model
def model_summary(self):
# Neural Net for Deep-Q learning Model
return self.model.summary()
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def act(self, state):
if np.random.rand() <= self.epsilon:
return random.randrange(self.action_size)
act_values = self.model.predict(state)
return np.argmax(act_values[0]) # returns action
def replay(self, batch_size):
minibatch = random.sample(self.memory, batch_size)
for state, action, reward, next_state, done in minibatch:
target = reward
if not done:
target = reward + self.gamma * \
np.amax(self.model.predict(next_state)[0])
target_f = self.model.predict(state)
target_f[0][action] = target
self.model.fit(state, target_f, epochs=1, verbose=0)
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
def replay_new(self, batch_size):
"""
Work in progress based on https://towardsdatascience.com/reinforcement-learning-w-keras-openai-dqns-1eed3a5338c
"""
minibatch = random.sample(self.memory, batch_size)
for state, action, reward, new_state, done in minibatch:
target = self.target_model.predict(state)
if done:
target[0][action] = reward
else:
target[0][action] = reward + self.gamma * np.amax(self.target_model.predict(new_state)[0])
self.model.fit(state, target, epochs=1, verbose=0)
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
def target_train(self):
"""
Work in progress
"""
weights = self.model.get_weights()
target_weights = self.target_model.get_weights()
for i in range(len(target_weights)):
target_weights[i] = weights[i] * self.tau + target_weights[i] * (1 - self.tau)
self.target_model.set_weights(target_weights)
def play(self, state):
act_values = self.model.predict(state)
return np.argmax(act_values[0])
def load_weights(self, name):
self.model.load_weights(name)
print("Loaded estimated model")
def save_weights(self, name):
self.model.save_weights(name)
print("Saved model to disk")
#%% FUNCTIONS
# define function to create state vector (dummy vector)
def state_vec(state,state_size):
vec = np.identity(state_size)[state:state + 1]
return vec
# plot learning curve
from statsmodels.nonparametric.smoothers_lowess import lowess
def plot_learning_rate(dataset, ylabel="", xlabel=""):
loess = pd.DataFrame(lowess(dataset.iloc[:,0], exog = dataset.iloc[:,1] ,frac=0.1, return_sorted=False))
result = pd.concat([dataset,loess], axis=1)
result.columns = ['r', 'epochs','loess']
# create plot
plt.plot('epochs','r', data=result, color='gray')
plt.plot('epochs','loess', data=result, color='red')
plt.ylabel(ylabel)
plt.xlabel(xlabel)
def play_game(env, agent, num_episodes, print_reward = False, text = True):
"""
Play the game given in the env based on the policy in the given q- table.
"""
total_epochs, reward_total = 0, 0
n = env.observation_space.n
for i in range(num_episodes):
# print(i)
state = env.reset()
epochs, reward, cum_reward = 0, 0, 0
done = False
steps = 0
while not done:
action = agent.play(state_vec(state,n))
state, reward, done, info = env.step(action)
cum_reward += reward
epochs += 1
steps += 1
total_epochs += epochs
reward_total += cum_reward
if print_reward == True:
print(f"Epoch: {i} Steps: {epochs} Reward: {cum_reward}")
if text == True:
print("-----------------------------------------")
print(f"Results after {num_episodes} episodes:")
print(f"Average timesteps per episode: {total_epochs / num_episodes}")
print(f"Average reward per episode: {reward_total / num_episodes}")
avr_timesteps = total_epochs / num_episodes
avr_reward = reward_total / num_episodes
return avr_reward, avr_timesteps
#%%
#"""
#Play CartPole
#"""
EPISODES = 10
env = gym.make('CartPole-v1')
state_size = env.observation_space.shape[0]
action_size = env.action_space.n
agent = DQNAgent(state_size, action_size)
# agent.load("./save/cartpole-dqn.h5")
done = False
batch_size = 32
for e in range(EPISODES):
state = env.reset()
state = np.reshape(state, [1, state_size])
for episode in range(500):
# env.render()
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
reward = reward if not done else -10
next_state = np.reshape(next_state, [1, state_size])
agent.remember(state, action, reward, next_state, done)
state = next_state
if done:
print("episode: {}/{}, score: {}, e: {:.2}"
.format(e, EPISODES, episode, agent.epsilon))
break
if len(agent.memory) > batch_size:
agent.replay(batch_size)
#%%
"""
Play Taxi-v2
"""
game_name = "taxi_64_64_32_v2"
store = pd.HDFStore(path_to_file + "/saved_models/" + game_name +".h5")
# store['df'] # load it
episodes = 1001
gamma = 0.95
epsilon_decay = 0.9999
learning_rate = 0.001
env = gym.make("Taxi-v2")
state_size = env.observation_space.n
action_size = env.action_space.n
agent = DQNAgent(state_size, action_size,
gamma=gamma,
epsilon_decay=epsilon_decay,
learning_rate=learning_rate)
# load the saved weights
# agent.load("./save/cartpole-dqn.h5")
done = False
batch_size = 32
r_avg_list = []
r_list = []
start_time = time.time()
max_steps = 500
for episode in range(episodes):
state = env.reset()
state = state_vec(state,state_size)
r_sum = 0
for step in range(max_steps):
# env.render()
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
reward = reward # if not done else 100 # hack to not get stuck in a local minimum (agent could just always play 199 steps)
next_state = state_vec(next_state,state_size)
agent.remember(state, action, reward, next_state, done)
state = next_state
r_sum += reward
if done:
break
if len(agent.memory) > batch_size:
agent.replay_new(batch_size)
agent.target_train()
r_avg_list.append(r_sum / step)
r_list.append(r_sum)
print("episode: {}/{}, steps: {}, reward:{}, e: {:.2}"
.format(episode, episodes, step, r_sum, agent.epsilon))
# safe the weights from time to time
if episode % 100 == 0:
agent.save_weights(path_to_file + "/saved_models/" + game_name +"_weights.h5")
run_time = round(((time.time() - start_time)/60),2)
avr_time = round(run_time/episodes,4)
# safe the learning progress
r_avg_list_table = pd.DataFrame(r_avg_list)
r_list_table = pd.DataFrame(r_list)
r_avg_list_table.to_hdf(store,'r_avg')
r_list_table.to_hdf(store,'r')
print("Time to run: {} min for {} episodes -- avr per episode: {} min".format(run_time, episodes, avr_time))
plt.plot(r_avg_list)
plt.ylabel('Average reward per step')
plt.xlabel('Number of games')
plt.show()
plt.plot(r_list)
plt.ylabel('Reward per episode')
plt.xlabel('Number of games')
plt.show()
#%% Load the model and analyse its performance
game_name = "taxi_1000ep_48_24"
# first set up the agent
env = gym.make("Taxi-v2")
state_size = env.observation_space.n
action_size = env.action_space.n
agent = DQNAgent(state_size, action_size)
# load the model weights
agent.load_weights(path_to_file + "/saved_models/" + game_name +"_weights.h5")
# inspect keys in hdf store
with pd.HDFStore(path_to_file + "/saved_models/" + game_name +".h5") as hdf:
print("HDF Keys:")
print(hdf.keys())
learning_return = hdf.get(key="r")
# load learning curve and plot it
learning_return["epochs"] = learning_return.index.tolist()
learning_return.columns = ['r', 'epochs']
plot_learning_rate(learning_return,"Return","Iteration")
print(agent.model_summary())
# play game
num_episodes = 100
play_game(env, agent, num_episodes, print_reward = True, text = True)
| true |
ef912acd1a87b58b4041a84f6d855692a1907bba | Python | calvetalex/codewars | /python/unique/index.py | UTF-8 | 192 | 3.3125 | 3 | [] | no_license | def unique_in_order(iterable):
if not iterable:
return []
res = [iterable[0]]
return res + [it for i, it in enumerate(iterable[1:], start=1) if it is not iterable[(i - 1)]] | true |
a333511402c73d363fd42d6f37a493ed6758a732 | Python | cambridgeltl/jp-pred-arg | /bp_pas/ling/pas.py | UTF-8 | 1,202 | 3.265625 | 3 | [
"MIT"
] | permissive | class PAS(object):
def __init__(self, pred, args):
self.pred = pred
self.args = args
def prd_index(self):
return self.pred.word_index
def __str__(self):
pstr = "{}({}) -> ".format(self.pred.word_form,
self.pred.word_index)
for arg in self.args:
pstr += "{}({}, {})".format(arg.word_form,
arg.word_index,
arg.arg_type)
return pstr
class Predicate(object):
def __init__(self, word_index, word_form):
self.word_index = word_index
self.word_form = word_form
def __eq__(self, other):
return self.word_index == other.word_index and self.word_form == other.word_form
class Argument(object):
def __init__(self, word_index, word_form, arg_type):
self.word_index = word_index
self.word_form = word_form
self.arg_type = arg_type
def __eq__(self, other):
return self.word_index == other.word_index and self.arg_type == other.arg_type
def __str__(self):
return "-> {}({},{})".format(self.word_form, self.word_index, self.arg_type)
| true |
ba47c17d014ae19113e5a2861a7b63d763cb4084 | Python | hmchen47/Programming | /Python/MIT-CompThinking/MITx600.1x/Quiz/final-2015/p3-1.py | UTF-8 | 511 | 3.46875 | 3 | [] | no_license | #!/usr/bin/env python2
# _*_ coding: utf-8 _*_
def sort1(lst):
swapFlag = True
iteration = 0
while swapFlag:
swapFlag = False
for i in range(len(lst)-1):
if lst[i] > lst[i+1]:
temp = lst[i+1]
lst[i+1] = lst[i]
lst[i] = temp
swapFlag = True
L = lst[:] # the next 3 questions assume this line just executed
print iteration, L
iteration += 1
return lst
sort1([4, 3 ,1, 6, 2, 8]) | true |
ce52390dc68472019b82adb3b4c08a2fffdbb473 | Python | zhora0412/py-crypt | /finalProject/venv/Lib/site-packages/tests/test_configuration.py | UTF-8 | 2,517 | 2.609375 | 3 | [] | no_license | import functools
import os
from pathlib import Path
import pytest
from smtpdfix.configuration import Config
values = [
("host", "mail.localhost", "mail.localhost", str),
("port", 5025, 5025, int),
("port", "5025", 5025, int),
("login_name", "name", "name", str),
("login_password", "word", "word", str),
("enforce_auth", "True", True, bool),
("enforce_auth", True, True, bool),
("enforce_auth", 1, True, bool),
("auth_require_tls", 0, False, bool),
("auth_require_tls", "0", False, bool),
("auth_require_tls", False, False, bool),
("auth_require_tls", "False", False, bool),
("ssl_certs_path", "./certs", "./certs", str),
("ssl_cert_files",
("./certs/cert.pem", "./certs/key.pem"),
("./certs/cert.pem", "./certs/key.pem"),
tuple),
("ssl_cert_files",
"./certs/key.pem",
("./certs/key.pem", None),
tuple),
("use_starttls", False, False, bool),
("use_tls", True, True, bool),
("use_ssl", True, True, bool),
]
props = [p for p in dir(Config) if isinstance(getattr(Config, p), property)]
@pytest.fixture
def handler():
class Handler():
def handle(self, result):
result.append(True)
yield Handler()
def test_init():
config = Config()
assert isinstance(config, Config)
def test_init_envfile():
original_env = os.environ.copy()
config_file = Path(__file__).parent.joinpath("assets/.test.env")
config = Config(filename=config_file, override=True)
assert config.port == 5025
os.environ.clear()
os.environ.update(original_env)
@pytest.mark.parametrize("attr, value, expected, type", values)
def test_set_values(attr, value, expected, type):
config = Config()
setattr(config, attr, value)
assert isinstance(getattr(config, attr), type)
assert getattr(config, attr) == expected
@pytest.mark.parametrize("prop", props)
def test_event_handler_fires(prop, handler):
config = Config()
result = []
config.OnChanged += functools.partial(handler.handle, result)
setattr(config, prop, 1)
assert result.pop() is True
def test_unset_event_handler(handler):
config = Config()
result = []
prop = "auth_require_tls" # chosen because it is alphabetically mo. 1
func = functools.partial(handler.handle, result)
config.OnChanged += func
setattr(config, prop, 1)
assert result.pop() is True
config.OnChanged -= func
setattr(config, prop, 0)
assert not result
| true |
50764a242d0eef672e750dcfde1d0196042178e9 | Python | 2heeesss/Problem_Solving | /reBOJ/1339.py | UTF-8 | 1,763 | 3.375 | 3 | [] | no_license | # import sys
# input = sys.stdin.readline
# n = int(input())
# arr = []
# for _ in range(n):
# arr.append(list(input().rstrip()))
# wordArr = [0]*10
# wordSize = 9
# result = 0
# while True:
# maxLength, maxIndex = 0, 0
# for i in range(len(arr)):
# if len(arr[i]) > maxLength:
# maxLength = len(arr[i])
# maxIndex = i
# elif len(arr[i]) == maxLength:
# a, b = 0, 0
# if len(arr[maxIndex]) == 0:
# break
# for p in range(len(arr)):
# a += arr[p].count(arr[maxIndex][0])
# b += arr[p].count(arr[i][0])
# if a > b:
# continue
# else:
# maxIndex = len(arr[i])
# maxIndex = i
# if len(arr[maxIndex]) == 0:
# break
# else:
# alphabet = arr[maxIndex].pop(0)
# if alphabet in wordArr:
# for j in range(len(wordArr)):
# if alphabet == wordArr[j]:
# result += j*(10**(maxLength-1))
# else:
# wordArr[wordSize] = alphabet
# result += wordSize*(10**(maxLength-1))
# wordSize -= 1
# print(result)
import sys
input = sys.stdin.readline
n = int(input())
arr = []
for _ in range(n):
arr.append(list(input().rstrip()))
wordDict = {}
for word in arr:
k = len(word)-1
for alphabet in word:
if alphabet in wordDict:
wordDict[alphabet] += 10 ** k
else:
wordDict[alphabet] = 10 ** k
k -= 1
print(wordDict)
sortWords = sorted(wordDict.values(), reverse=True)
p = 9
result = 0
for word in sortWords:
print(word)
result += word*p
p -= 1
print(result)
# 딕셔너리 사용법
# 딕셔너리 정렬방법
| true |
dde9596739b296b43b51e1d7c84c2ddfded4c3d4 | Python | yeon4032/STUDY | /GIT_NOTE/03_python/chap08_MariaDB/exams/exam01.py | UTF-8 | 2,135 | 3.5 | 4 | [] | no_license | '''
문제1) goods 테이블을 이용하여 다음과 같은 형식으로 출력하시오.
<조건1> 전자레인지 수량, 단가 수정
<조건2> HDTV 수량 수정
[ goods 테이블 현황 ]
1 냉장고 2 850000
2 세탁기 3 550000
3 전자레인지 5 400000 <- 수량, 단가 수정
4 HDTV 2 1500000 <- 수량 수정
전체 레코드 수 : 4
[ 상품별 총금액 ]
냉장고 상품의 총금액은 1,700,000
세탁기 상품의 총금액은 1,650,000
전자레인지 상품의 총금액은 2,000,000
HDTV 상품의 총금액은 3,000,000
'''
import pymysql
config = {
'host' : '127.0.0.1',
'user' : 'scott',
'password' : 'tiger',
'database' : 'work',
'port' : 3306,
'charset':'utf8',
'use_unicode' : True}
try :
# db 연동 객체 생성
conn = pymysql.connect(**config)
# sql 문 실행 객체 생성
cursor = conn.cursor()
#3. Updat문:Update: code를 찾아 -> name,dan 수정한다
code = int(input('update code input:'))
su = int(input('su code input:'))
dan=int(input('update dan input:'))
sql=f"""update goods set su = '{su}', dan={dan} where
code = {code}"""
cursor.execute(sql) # 레코드 수정
conn.commit() #db반영
#1. select문 :전체 레코드 조회
sql="select *from goods"
cursor.execute(sql) # 실제 sql문 실행
# 레코드 조회 결과
print('\n\t[ 상품별 총급액]')
dataset=cursor.fetchall() # 레코드 가져오기
for row in dataset:
#print(row) # tuple (1, '냉장고', 2, 850000)
print(row[0],row[1],row[2],row[3]) # 1 냉장고 2 850000
# 인덱스 없이는 tuple 로 나온고 인데스 있으면 tuple 이 벗겨짐.
sql="select *from goods"
cursor.execute(sql)
dataset1=cursor.fetchall()
for row1 in dataset1:
print('{0} 상품의 총금액은 {1:3,d}'.format(row1[1],row1[2]*row1[3]))
except Exception as e :
print('db connection err:', e)
conn.rollback() # 이전 상태 리턴
finally:
cursor.close(); conn.close() # 객체 닫기 (역순)
| true |
a036e35e4679a8f561435daed4a29b7eb97827e0 | Python | sarvenderdahiya/leetcode_solutions | /My solutions/1122_Relative_sort_array.py | UTF-8 | 1,806 | 3.421875 | 3 | [
"MIT"
] | permissive | from typing import List
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
out = []
arr1.sort()
for i in range(len(arr2)):
pos1 = -1
pos2 = -1
lo = 0
hi = len(arr1) - 1
# To find first occurrence of arr2[i] in arr1
while lo <= hi:
mid = (hi+lo)//2
if arr1[mid] < arr2[i]:
lo = mid + 1
elif arr1[mid] == arr2[i]:
pos1 = mid
print("pos1 of ",arr2[i]," ",pos1 )
hi = mid - 1
else:
hi = mid - 1
# To find last occurrence of arr2[i] in arr1
lo = 0
hi = len(arr1) - 1
while lo <= hi:
mid = (hi+lo)//2
if arr1[mid] < arr2[i]:
lo = mid + 1
elif arr1[mid] == arr2[i]:
pos2 = mid
print("pos2 of ",arr2[i]," ",pos2 )
lo = mid + 1
else:
hi = mid - 1
# now add all those elements between pos1 and pos2 to output
for i in range (pos1, pos2+1):
out.append(arr1[i])
diff = []
for i in range(len(arr1)):
if arr1[i] not in arr2:
diff.append(arr1[i])
print(sorted(diff))
return out + (sorted(diff))
# Just to test the output with a test case
o = Solution()
print(o.relativeSortArray([2,21,43,38,0,42,33,7,24,13,12,27,12,24,5,23,29,48,30,31],[2,42,38,0,43,21]))
# Runtime: 48 ms, faster than 47.38% of Python3 online submissions
# Memory Usage: 13.9 MB, less than 67.01% of Python3 online submissions
| true |
200b72f7be22a879a36dbcdf19fafe1de97439f7 | Python | prihoda/bgc-pipeline | /bgc_detection/evaluation/prediction_plot.py | UTF-8 | 2,704 | 3.1875 | 3 | [
"MIT",
"BSD-3-Clause",
"Python-2.0",
"GPL-2.0-only",
"Apache-2.0",
"GPL-3.0-only",
"LicenseRef-scancode-biopython"
] | permissive | #!/usr/bin/env python
# David Prihoda
# Plot prediction probability output, producing a line plot with protein domains on x-axis and prediction value on y-axis
import argparse
import matplotlib.pyplot as plt
import pandas as pd
def count_y_clusters(y):
prev = 0
clusters = 0
for val in y:
if val == 1 and prev == 0:
clusters += 1
prev = val
return clusters
def prediction_plot(predictions_per_model, names, colors):
"""
Plot prediction probability output, producing a line plot with protein domains on x-axis and prediction and in_cluster value on y-axis
:param predictions_per_model: list of model predictions (each model prediction is a Domain DataFrame with prediction and in_cluster column)
:param names: list of model names
:param colors: list of model colors
:return: Plot figure
"""
contig_ids = predictions_per_model[0]['contig_id'].unique()
rows = len(contig_ids) * len(names)
samples_fig, samples_ax = plt.subplots(rows, 1, figsize=(20, rows*2))
i = 0
for contig_id in contig_ids:
for predictions, name, color in zip(predictions_per_model, names, colors):
contig_predictions = predictions[predictions['contig_id'] == contig_id].reset_index(drop=True)
print('Plotting', contig_id, name, len(contig_predictions))
contig_predictions['in_cluster'].plot.area(color='black', alpha=0.1, ax=samples_ax[i])
contig_predictions['in_cluster'].plot(color='black', lw=2, alpha=0.7, ax=samples_ax[i])
contig_predictions['prediction'].plot(color=color, title=contig_id, label=name, ax=samples_ax[i])
i += 1
samples_fig.tight_layout()
return samples_fig
if __name__ == "__main__":
# Parse command line
parser = argparse.ArgumentParser()
parser.add_argument("--prediction", dest="predictions", required=True, action='append',
help="Prediction CSV file path.", metavar="FILE")
parser.add_argument("--name", dest="names", required=True, action='append',
help="Name for given prediction.", metavar="FILE")
parser.add_argument("--color", dest="colors", required=True, action='append',
help="Color for given prediction.", metavar="FILE")
parser.add_argument("-o", "--output", dest="output", required=True,
help="Output file path.", metavar="FILE")
options = parser.parse_args()
predictions = [pd.read_csv(path) for path in options.predictions]
fig = prediction_plot(predictions, options.names, options.colors)
fig.savefig(options.output, dpi=150)
print('Saved prediction plot to: ', options.output)
| true |
2102a631351e26e87277452516b0a90c96136ffc | Python | KarenWest/pythonClassProjects | /insertNewLinesTypeWriter.py | UTF-8 | 5,593 | 3.859375 | 4 | [] | no_license | '''
Imagine a typewriter: whenever it's in the middle of a word, and reaches its
desired line length, the internal bell rings. This signifies to the typist
that after finishing the current word, a newline must be manually inserted.
We ask you to emulate this process such that a newline is inserted as required
after each word that exceeds the desired line length. Note that if the
typewriter's bell rings on a space, a newline should be inserted before the
start of the next word.
This function has to be recursive! You may not use loops (for or while) to solve this problem.
Note: In programming there are many ways to solve a problem. For your code to
check correctly here, though, you must write your recursive function such that
you make a recursive call directly to either the function insertNewlines or -
if you wish to use a helper function - insertNewlinesRec. Thank you for
understanding.
'''
def insertNewlines(text, lineLength):
"""
Given text and a desired line length, wrap the text as a typewriter would.
Insert a newline character ("\n") after each word that reaches or exceeds
the desired line length.
text: a string containing the text to wrap.
line_length: the number of characters to include on a line before wrapping
the next word.
returns: a string, with newline characters inserted appropriately.
"""
#with recursive function insertNewLines and NO recursive helper function
if (lineLength >= len(text)):
return text
else: #lineLength where to insert is less than length of rest of text
if (len(text) == (lineLength + 1)) or (len(text) == (lineLength + 2)) or (len(text) == (lineLength + 3)):
return text
elif (len(text) < (2*lineLength)):
textLineLengthIndex = text.find(" ", lineLength)
if (textLineLengthIndex != -1):
textLineLength = text[0:textLineLengthIndex]
textRestOfLine = text[(textLineLengthIndex + 1):]
textLineLength += "\n"
return textLineLength + textRestOfLine
else:
return text
textLineLength = text[0:lineLength]
textRestOfLine = text[lineLength:]
#print textLineLength
#print textRestOfLine
if (textLineLength[-1] == " "): #last char is a space in line
textLineLength += "\n"
else: #in the middle of a word -- finish this word first before \n
textLineLengthIndex = text.find(" ", lineLength)
textLineLength = text[0:textLineLengthIndex]
textRestOfLine = text[(textLineLengthIndex + 1):]
textLineLength += "\n"
return textLineLength + insertNewlines(textRestOfLine, lineLength)
#Test Case 1:
#print insertNewlines('While I expect new intellectual adventures ahead, nothing will compare to the exhilaration of the world-changing accomplishments that we produced together.', 15)
'''
Output:
While I expect
new intellectual
adventures ahead,
nothing will compare
to the exhilaration
of the world-changing
accomplishments
that we produced
together.
'''
#Test Case 2:
#print insertNewlines('Nuh-uh! We let users vote on comments and display them by number of votes. Everyone knows that makes it impossible for a few persistent voices to dominate the discussion.', 20)
'''
Output:
Nuh-uh! We let users
vote on comments and
display them by number
of votes. Everyone knows
that makes it impossible
for a few persistent
voices to dominate the
discussion.
'''
#Test Case 3:
#print insertNewlines('Random text to wrap again.', 5)
'''
Random
text
to wrap
again.
'''
#Test Case 4:
#print insertNewlines('igh qujbg hotjr icogdx ksp cxtlgr phkf rinshq bugpc xdgbkae puky hwdb rcmu kbluiqr hybx ump hwkeqsy ubjf qheag sxebdgz kzex zlem wpzf rjmgow yqv kdztbia ihvrqf rjpeo ctijkarz', 26)
'''
igh qujbg hotjr icogdx ksp
cxtlgr phkf rinshq bugpc xdgbkae
puky hwdb rcmu kbluiqr hybx
ump hwkeqsy ubjf qheag sxebdgz
kzex zlem wpzf rjmgow yqv
kdztbia ihvrqf rjpeo ctijkarz
'''
#Test case 5:
print insertNewlines('pclhodqg xwur lsvg bwkmv dfxm xhug jmcbs spmiau gamr sdcwng msyr ogskn zmxqaysf rhijfks gdl mlhkerio xiz rdnzaku bfwzudlx eju hxlbo eybvgqw jmfn kwdbaq sgjmewk pysqtcgl apocmzkd oyed zflcn', 44)
'''
pclhodqg xwur lsvg bwkmv dfxm xhug jmcbs spmiau
gamr sdcwng msyr ogskn zmxqaysf rhijfks gdl
mlhkerio xiz rdnzaku bfwzudlx eju hxlbo eybvgqw
jmfn kwdbaq sgjmewk pysqtcgl apocmzkd oyed zflcn
'''
'''
with recursive helper function that their auto-grader rejected (said it was recursive!)
def insertNewlinesRec(text, lineLength, out):
#print " text this time is " + text
#print " lineLength " + str(lineLength)
#print " out this time is " + out
if lineLength > len(text):
return out + text
else:
textLineLength = text[0:lineLength]
textRestOfLine = text[lineLength:]
#print textLineLength
#print textRestOfLine
if (textLineLength[-1] == " "): #last char is a space in line
textLineLength += "\n"
else: #in the middle of a word -- finish this word first before \n
i = 0
while (textLineLength[-1] != " "):
textLineLength = text[0:(lineLength + i)]
textRestOfLine = text[(lineLength + i):]
i += 1
textLineLength += "\n"
out += textLineLength
return insertNewlinesRec(textRestOfLine, lineLength, out)
return insertNewlinesRec( text, lineLength, "")
'''
| true |
56b0201e448df1ba10fb88fe7bacebf23507a98f | Python | AlfredKai/KaiCodingNotes | /LeetCode/Hard/124. Binary Tree Maximum Path Sum.py | UTF-8 | 1,403 | 3.546875 | 4 | [] | no_license | 1044. Longest Duplicate Substring
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
import math
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
def helper(root):
if root == None:
return (-math.inf, -math.inf)
if root.left == None and root.right == None:
return (root.val, -math.inf)
left = helper(root.left)
right = helper(root.right)
noRootMaxSum = max(left[0], left[1], right[0], right[1], root.val+left[0]+right[0])
rootMax = max(root.val, root.val+left[0], root.val+right[0])
return (rootMax, noRootMaxSum)
return max(helper(root))
a = Solution()
b = TreeNode(1)
b.left = TreeNode(2)
b.right = TreeNode(3)
print(a.maxPathSum(b))
b = TreeNode(-10)
b.left = TreeNode(9)
b.right = TreeNode(20)
b.right.left = TreeNode(15)
b.right.right = TreeNode(7)
print(a.maxPathSum(b))
b = TreeNode(-3)
print(a.maxPathSum(b))
b = TreeNode(5)
b.left = TreeNode(4)
b.right = TreeNode(8)
b.left.left = TreeNode(11)
b.right.left = TreeNode(13)
b.right.right = TreeNode(4)
b.left.left.left = TreeNode(7)
b.left.left.right = TreeNode(2)
b.right.right.right = TreeNode(1)
print(a.maxPathSum(b)) | true |
11b21bbf9d24ac3867bd709091f7019f6e722602 | Python | fabriciocravo/Animals10 | /DataAnalysis/PercentageOfSucessfullAttacks.py | UTF-8 | 2,269 | 2.59375 | 3 | [
"MIT"
] | permissive | import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import pickle as pkl
import cv2 as cv
# Needed for pickle loading!!!
from ResNet import ResNet
from VGG import VGG
from GoogLeNet import GoogLeNet
from AlexNet import AlexNet
# Parameters ######################################################
filter = False
model = "GoogleNet"
image_folder = "D:/Captcha_Data/ResNet_1000_3ModelClean/"
ResNet_path = "C:/Users/33782/Desktop/Animals10Captcha/Models/ResNet_animals10.pkl"
VGG_path = "C:/Users/33782/Desktop/Animals10Captcha/Models/VGG_animals10.pkl"
GoogleNet_Path = "C:/Users/33782/Desktop/Animals10Captcha/Models/GoogLeNet_animals10.pkl"
AlexNet_Path = "C:/Users/33782/Desktop/Animals10Captcha/Models/AlexNet_animals10.pkl"
###################################################################
class_dictionary = {'butterfly': 0, 'cat': 1, 'chicken':2 , 'cow': 3,
'dog': 4, 'elephant': 5, 'horse': 6, 'sheep': 7,
'spider': 8, 'squirrel': 9}
index_dictionary = { 0:'butterfly' , 1:'cat', 2:'chicken' , 3: 'cow',
4:'dog', 5:'elephant', 6:'horse', 7:'sheep',
8:'spider', 9:'squirrel'}
if model == "ResNet":
model = pkl.load(open(ResNet_path, "rb"))
elif model == "VGG":
model = pkl.load(open(VGG_path, "rb"))
elif model == "GoogleNet":
model = pkl.load(open(GoogleNet_Path, "rb"))
elif model == "AlexNet":
model = pkl.load(open(AlexNet_Path, "rb"))
else:
raise Exception("No model selected")
acc = 0
for image in os.listdir(image_folder):
img = Image.open(image_folder + image)
img = np.asarray(img)
img = img[:, :, :3]
real_class_name = image.split("_")[0]
real_class = class_dictionary[real_class_name]
if filter:
img = cv.medianBlur(img, 3)
probabilities = model.predict_numpy_images([img])
print("Image: ", image)
print(probabilities)
predicted_class = int(np.argmax(probabilities))
predicted_class_name = index_dictionary[predicted_class]
print(real_class, predicted_class)
if real_class == predicted_class:
acc = acc + 1
print(acc/len(os.listdir(image_folder)))
| true |
8cd5db8caaae6d93ab7bbcec9b982032c488ca2c | Python | RobertNeuzil/sandbox | /mulchoice.py | UTF-8 | 1,403 | 3.734375 | 4 | [] | no_license | class Multiple_Choice:
def __init__(self, question, correctanswer, answer2, answer3, answer4):
self.question = question
self.correctanswer = correctanswer
self.answer2 = answer2
self.answer3 = answer3
self.answer4 = answer4
one = Multiple_Choice("What color is the sky? ", "blue", "red", "green", "yellow")
two = Multiple_Choice("What color is the sun? ", "yellow", "red", "green", "blue")
three = Multiple_Choice("What color is the grass? ", "green", "yellow", "red", "blue")
def run_test(one, two, three):
score = 0
print (one.question + "\n" + "\n" + one.correctanswer + "\n" + one.answer2 + "\n" + one.answer3 + "\n" + one.answer4 + "\n")
user_answer = input("type answer here: ")
print (two.question + "\n" + "\n" + two.correctanswer + "\n" + two.answer2 + "\n" + two.answer3 + "\n" + two.answer4 + "\n")
user_answer_two = input("type answer here: ")
print (three.question + "\n" + "\n" + three.correctanswer + "\n" + three.answer2 + "\n" + three.answer3 + "\n" + three.answer4 + "\n")
user_answer_three = input("type answer here: ")
if user_answer.lower() == one.correctanswer.lower():
score += 1
else:
pass
if user_answer_two.lower() == two.correctanswer.lower():
score += 1
else:
pass
if user_answer_three.lower() == three.correctanswer.lower():
score += 1
else:
pass
print ("You got " + str(score) + " answers correct!")
run_test(one, two, three)
| true |
3ddd65df5f592e6728f44ec6911ce0c4676ff340 | Python | Matmonsen/py-yr | /py_yr/weatherdata/links/links.py | UTF-8 | 907 | 2.796875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
from .link import Link
class Links(object):
def __init__(self, links):
self.xmlSource = Link(links['link'][0])
self.xmlSourceHourByHour = Link(links['link'][1])
self.overview = Link(links['link'][2])
self.hourbyhour = Link(links['link'][3])
self.longTermForecast = Link(links['link'][4])
try:
self.radar = Link(links['link'][5])
except IndexError:
self.radar = None
def __str__(self):
return '\txmlSource: \n{0} ' \
'\n\txmlSourceHourByHour: \n{1} ' \
'\n\tOverview: \n{2} ' \
'\n\tHourByHour: \n{3} ' \
'\n\tLongTermForecast: \n{4} ' \
'\n\tRadar: \n{5}'.format(self.xmlSource, self.xmlSourceHourByHour, self.overview, self.hourbyhour,
self.longTermForecast, self.radar) | true |
295e5db1cd439fb334e1449fde5b1e60b10bac24 | Python | HBinhCT/Q-project | /hackerearth/Math/Number Theory/Basic Number Theory-1/Connected Components/solution.py | UTF-8 | 838 | 2.78125 | 3 | [
"MIT"
] | permissive | from sys import stdin
mod = 1000000007
def combine(comb, inv_comb, x, y):
return comb[x] * (inv_comb[x - y] * inv_comb[y] % mod) % mod
t = int(stdin.readline())
cases = []
size = 0
for _ in range(t):
n, m, c = map(int, stdin.readline().strip().split())
cases.append((n, m, c))
size = max(size, n, m, c)
fac = [1, 1]
size += 2
for i in range(2, size):
fac.append(fac[i - 1] * i % mod)
inverse_fac = [0] * (size + 1)
inverse_fac[size] = pow(fac[size - 1] * size % mod, mod - 2, mod)
for i in range(size, 0, -1):
inverse_fac[i - 1] = inverse_fac[i] * i % mod
for n, m, c in cases:
if n == m and not c:
print(1)
elif not c or c + c - 1 > n or c > m + 1 or c > n - m:
print(0)
else:
print(combine(fac, inverse_fac, m + 1, c) * combine(fac, inverse_fac, n - m - 1, c - 1) % mod)
| true |
61ec729aaf9e88913870aad76cd12d9f2db8d2d2 | Python | digital101ninja/pythonAutomateTasks | /pythonAutomate/ch7Regex.py | UTF-8 | 2,262 | 3.265625 | 3 | [] | no_license | #!/usr/bin/python
import re
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('My number is 415-555-4242')
print "Phone number found:" + mo.group()
print "Area code is:" + mo.group(1)
batRegex = re.compile(r'Bat(man|mobile|copter|bat)')
mo = batRegex.search('Batcopter does not exist')
print mo.group()
print mo.group(1)
batRegex = re.compile(r'Bat(wo)?man')
moMen = batRegex.search('The adventures of Batman')
moWomen = batRegex.search('The adventures of Batwoman')
print moMen.group()
print moWomen.group()
haRegex = re.compile(r'(ha){3}')
haRangeRegex = re.compile(r'(ha){3,5}')
ha1 = haRegex.search('ha')
ha2 = haRegex.search('haha')
ha3 = haRegex.search('hahaha')
ha10 = haRangeRegex.search('ha'*10)
if ha1: print ha1.group()
if ha2: print ha2.group()
if ha3: print ha3.group()
print 'ha'*10
vowelRegex = re.compile(r'[aeiouAEIOU1-9]')
consonantRegex = re.compile(r'[^aeiouAEIOU]')
vowelList = vowelRegex.findall('2 RoboCop eats 19 jars of baby food and 4 bottles of milk. BABY FOOD.')
consonantList = consonantRegex.findall('2 RoboCop eats 19 jars of baby food and 4 bottles of milk. BABY FOOD.')
print vowelList
print consonantList
#case insensitivity
robocop = re.compile(r'robocop',re.I)
result = robocop.search('RoboCop is part man, part machine, all cop.').group()
print result
result = robocop.search('ROBOCOP protects the innocent').group()
print result
result = robocop.search('Al,why does your programmign book talk about robocop so much?').group()
print result
namesRegex = re.compile(r'Agent \w+')
result = namesRegex.sub('CENSORED','Agent Alice gave the secret documents to Agent Bob.')
print result
agentNamesRegex = re.compile(r'Agent (\w)\w*')
result = agentNamesRegex.sub(r'\1***','Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.')
print result
ultimatePhoneRegex = re.compile(r'''(
(\d{3}|\(\d{3}\))? #area code 415 or (415)
(\s|-|\.)? #separator ' ' or '-' or '.'
\d{3} #first 3 digits
(\s|-|\.) #separator ' ' or '-' or '.'
\d{4} #last 4 digits
(\s*(ext|x|ext.)\s*\d{2,5})? #possible extension. 'ext' or 'x' or 'ext.'
)''',re.VERBOSE)
| true |
8ee20553e61883dc17835e8a6d69f5ccdea8d3dd | Python | dythebs/happygoat | /backend/src/main/java/csu/edu/happygoat/spider/hunyanjiudiansousuo.py | UTF-8 | 1,910 | 2.578125 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import json
import re
import sys
url = sys.argv[1]
base_url = re.findall('(https://.*?/HunYan)', url)[0]
html = requests.get(url).text
soup = BeautifulSoup(html, "html.parser")
def trim(str):
return str.replace(' ', '').replace('\n', '').replace('\r', '')
lis = soup.find_all('li', class_='clearfix listStyle')
datas = []
for li in lis:
data_dict = {}
data_dict['title'] = li.find('a', class_='name')['title']
data_dict['img'] = li.article.a.img['src']
data_dict['cast'] = '¥ '+li.find('strong').text.replace(' ','').strip()
data_dict['href'] = base_url + li.find('a', class_='pic')['href']
opinions = li.find('div', class_='opinion clearfix').find_all('i')
opinions_list = []
for opinion in opinions:
if opinion.get('class') != None and 'line' in opinion['class']:
continue
opinions_list.append(trim(opinion.text))
data_dict['opinions'] = opinions_list
rooms = li.find('ul', class_='rooms').find_all('li')
rooms_list = []
for room in rooms:
room_dict = {}
room_dict['name'] = trim(room.a.em.text)
room_dict['img'] = room.a.img['src']
rooms_list.append(room_dict)
data_dict['rooms'] = rooms_list
datas.append(data_dict)
pages = {}
p = soup.find('div', id='pages')
total = trim(p.find('span', class_='totalPage').text)
pages['total'] = total
pagelist = p.find('span', id='pageNum').find_all('a')
page_list = []
for page in pagelist:
dict = {}
dict['num'] = trim(page.text)
dict['href'] = base_url + '/' + page['href']
page_list.append(dict)
pages['list'] = page_list
pre = p.find('span', id='pagePrev')
if pre.a == None:
pages['pre'] = ''
else:
pages['pre'] = base_url + '/' + pre.a['href']
next = p.find('span', id='pageNext')
if next.a == None:
pages['next'] = ''
else:
pages['next'] = base_url + '/' + next.a['href']
res = {}
res['code'] = 200
res['datas'] = datas
res['pages'] = pages
print(json.dumps(res))
| true |
3561d2eed8f7386fe2ed227fd25183577773a9e8 | Python | YanzheL/CatchU | /multiproc_model/consumer.py | UTF-8 | 1,956 | 2.609375 | 3 | [] | no_license | import six
import abc
from utils.logger_router import LoggerRouter
from utils.counter import Counter
@six.add_metaclass(abc.ABCMeta)
class Consumer:
global_running = True
all_stopped = Counter('Consumer')
@classmethod
def from_name(cls, name, **kwargs):
for sub_cls in cls.__subclasses__():
if name.lower() + "consumer" == sub_cls.__name__.lower():
return sub_cls(**kwargs)
def __init__(self, input_queue):
self.input_queue = input_queue
self.logger = LoggerRouter().getLogger(__name__)
self.running = True
def run(self):
if not self.all_stopped.finished.is_set():
self.all_stopped.increase()
try:
while Consumer.global_running and self.running:
# print("WK")
in_data = self.input_queue.get()
ret = self.process(in_data)
if ret[1] is not None:
self.output_queue.put(ret)
except Exception as e:
self.exception_handler(e)
finally:
# pass
self.stop()
def stop(self, all_instance=False):
if not self.all_stopped.finished.is_set():
if all_instance:
Consumer.global_running = False
self.running = False
self._clean_up()
self.logger.info('Worker %s stopped' % (self.__class__.__name__))
self.all_stopped.decrease()
@abc.abstractmethod
def process(self, data):
return data
def exception_handler(self, exc):
self.logger.error("Unexpected exception %s, now stopping..." % exc)
def _clean_up(self):
pass
class GUIConsumer(Consumer):
def __init__(self, input_queue, gui):
super(GUIConsumer, self).__init__(input_queue)
self.gui = gui
def process(self, data):
self.gui.set_image(data[1])
| true |
3ce996947dd302c55552ff068ef78c670955e0f5 | Python | Penguin2600/mtp_breaker | /mtp.py | UTF-8 | 5,849 | 2.953125 | 3 | [] | no_license | import sys
import os
def rawxor(a, b):
"""xor two strings of different length"""
if len(a) > len(b):
return [x ^ y for (x, y) in zip(a[:len(b)], b)]
else:
return [x ^ y for (x, y) in zip(a, b[:len(a)])]
def decify(hexstring):
intarray = [int(hexstring[i:i+2], 16)
for i in range(0, len(hexstring), 2)]
return intarray
def decixor(a, b):
return rawxor(decify(a), decify(b))
def hexdecixor(a, b):
return rawxor(decify(a), b)
def singlexor(a, b):
return [x ^ b for x in decify(a)]
class MtpBreaker(object):
"""Breaks ascii encoded mtp strings which happen to have spaces"""
def __init__(self):
super(MtpBreaker, self).__init__()
self.cypherfile = self.locate_cypherfile()
self.cyphertexts = self.parse_cypherfile()
self.keylength = len(max(self.cyphertexts, key=len))
self.key = [0]*self.keylength
def locate_cypherfile(self):
static_default = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'crypted.txt')
if os.path.exists(static_default):
return static_default
else:
print "Couldnt find cyphertext, exiting."
sys.exit(0)
def parse_cypherfile(self):
result = []
for line in open(self.cypherfile, 'r'):
result.append(line.rstrip())
return result
def add_keyguess(self, cyphertext, bytepos, value):
"""guess a letter and get the resulting key byte"""
self.key[bytepos] = singlexor(
self.cyphertexts[cyphertext],
value)[bytepos]
return self.key[bytepos]
def keystats(self, printkey=False):
reco = float(len([x for x in self.key if x > 0]))
print "Key {0:3.2f}% recovered :)".format(reco / self.keylength*100.0)
if printkey:
print self.key
def decode(self):
for texts in xrange(len(self.cyphertexts)):
result = []
raw = rawxor(self.key, decify(self.cyphertexts[texts]))
for index in xrange(len(raw)):
rawchr = raw[index]
if (self.key[index] != 0):
if ((rawchr >= 32 and rawchr <= 90) or
(rawchr >= 97 and rawchr <= 122)):
result.append(chr(rawchr))
else:
result.append("_")
else:
result.append("-")
print ''.join(result)
def get_key_from_spaces(self, confidence=0.7):
for base_text in xrange(len(self.cyphertexts)):
spacecounts = {}
# print "\n=== Base Message {} ===".format(base_text)
for challenge_text in xrange(len(self.cyphertexts)):
result = []
# Skip xoring base against itself
if (challenge_text != base_text):
# XOR base text with challenge text
basexor = decixor(self.cyphertexts[base_text],
self.cyphertexts[challenge_text])
for index in xrange(len(basexor)):
raw_char = basexor[index]
# Look for [a-zA-Z] characters which may indicate space
if ((raw_char >= 65 and raw_char <= 90) or
(raw_char >= 97 and raw_char <= 122)):
result.append(chr(raw_char))
# Add possible space to counter
spacecounts.setdefault(index, 0)
spacecounts[index] += 1
else:
# if its not alpha, draw a hyphen.
result.append("-")
# print ''.join(result)
# look at space counts per base cypher.
for col, count in spacecounts.iteritems():
# if over X% of the texts had a possible space, derive key.
if (count >= len(self.cyphertexts) * confidence):
# print "high chance of space at {}".format(col)
if not self.key[col]:
self.key[col] = singlexor(
self.cyphertexts[base_text],
ord(' '))[col]
else:
alt = singlexor(
self.cyphertexts[base_text],
ord(' '))[col]
# print "key colision at {} {},{}".format(
# col, self.key[col], alt)
def main():
breaker = MtpBreaker()
# get most confident guesses first
for i in xrange(10, 1, -1):
breaker.get_key_from_spaces(i/10.0)
# add manual guesses in form cyphertext, bytepos, value
# breaker.add_keyguess(0, 27, ord('o'))
# breaker.add_keyguess(0, 54, ord('e'))
# breaker.add_keyguess(0, 63, ord('e'))
# breaker.add_keyguess(0, 64, ord('n'))
# breaker.add_keyguess(0, 3, ord('r'))
breaker.add_keyguess(0, 7, ord('r'))
# breaker.add_keyguess(0, 14, ord('t'))
breaker.add_keyguess(0, 25, ord('p'))
# breaker.add_keyguess(0, 26, ord('t'))
# breaker.add_keyguess(1, 34, ord('y'))
breaker.add_keyguess(6, 35, ord('n'))
# breaker.add_keyguess(3, 39, ord('m'))
# breaker.add_keyguess(3, 55, ord('c'))
# breaker.add_keyguess(10, 36, ord('s'))
# breaker.add_keyguess(10, 66, ord('e'))
# breaker.add_keyguess(10, 69, ord('m'))
# breaker.add_keyguess(10, 73, ord(' '))
# breaker.add_keyguess(10, 78, ord(' '))
# breaker.add_keyguess(10, 82, ord('e'))
breaker.keystats()
breaker.decode()
if __name__ == '__main__':
main()
| true |
aa0cba014a34b5c9bff9415c353e5b23c060b444 | Python | 02stevenyang850527/ML2017 | /hw3/grad_ascent.py | UTF-8 | 2,240 | 2.625 | 3 | [] | no_license | import matplotlib.pyplot as plt
from keras.models import load_model
from keras import backend as K
import numpy as np
NUM_STEPS = 20
RECORD_FREQ = 5
def normalize(x):
# utility function to normalize a tensor by its L2 norm
return x / (K.sqrt(K.mean(K.square(x))) + 1e-7)
def grad_ascent(num_step,input_image_data,iter_func,filter_images):
"""
Implement this function!
"""
lr = 1
for i in range(num_step):
loss, grad = iter_func([input_image_data,0])
input_image_data += grad*lr
if (i%RECORD_FREQ == 0):
filter_images[int(i/RECORD_FREQ)].append([np.copy(np.reshape(input_image_data,(48,48))), loss])
return filter_images
def main():
emotion_classifier = load_model('my_model.h5')
layer_dict = dict([layer.name, layer] for layer in emotion_classifier.layers[1:])
input_img = emotion_classifier.input
num_steps = NUM_STEPS
nb_filter = 112
name_ls = ['activation_2']
collect_layers = [ layer_dict[name].output for name in name_ls ]
for cnt, c in enumerate(collect_layers):
filter_imgs = [[] for i in range(NUM_STEPS//RECORD_FREQ)]
for filter_idx in range(nb_filter):
input_img_data = np.random.random((1, 48, 48, 1)) # random noise
target = K.mean(c[:, :, :, filter_idx])
grads = normalize(K.gradients(target, input_img)[0])
iterate = K.function([input_img,K.learning_phase()], [target, grads])
###
"You need to implement it."
grad_ascent(num_steps, input_img_data, iterate, filter_imgs)
###
for it in range(NUM_STEPS//RECORD_FREQ):
fig = plt.figure(figsize=(14, 8))
for i in range(nb_filter):
ax = fig.add_subplot(nb_filter/16, 16, i+1)
ax.imshow(filter_imgs[it][i][0], cmap='BuGn')
plt.xticks(np.array([]))
plt.yticks(np.array([]))
plt.xlabel('{:.3f}'.format(filter_imgs[it][i][1]))
plt.tight_layout()
fig.suptitle('Filters of layer {} (# Ascent Epoch {} )'.format(name_ls[cnt], it*RECORD_FREQ))
fig.savefig('e'+ str(it) + '_act2')
if __name__ == "__main__":
main()
| true |
a32561a522b6324eb471f93b2a7f7855d6b810cc | Python | jayrshah98/ASE-HW1 | /src/hw3/LIB.py | UTF-8 | 3,149 | 2.8125 | 3 | [
"MIT"
] | permissive | import math
import random
import re
import sys
from pathlib import Path
import config
lo = float('inf')
hi = float('-inf')
seed = 937162211
class LIB:
def __init__(self):
pass
def rint(self, lo, hi):
return math.floor(0.5 + self.rand(lo,hi))
def rand(self,lo, hi):
global seed
lo, hi = lo or 0, hi or 1
seed = (16807 * seed) % 2147483647
return lo + (hi-lo) * seed / 2147483647
def rnd(self, n, nPlaces = 3):
mult = 10**(nPlaces)
return math.floor(n * mult + 0.5) / mult
def coerce(self,s):
def fun(s1):
if s1 == "true" or s1 == "True":
return True
elif s1 == "false" or s1 == "False":
return False
else:
return s1
if type(s) == bool:
return s
try:
result = int(s)
except:
try:
result = float(s)
except:
result = fun(re.match("^\s*(.+)\s*$", s).string)
return result
def csv(self,sFilename,fun):
filePath = Path(sFilename)
filePath = filePath.absolute()
filePath = filePath.resolve()
f = open(filePath,"r")
readLines = f.readlines()
f.close()
for line in readLines:
t = []
for s1 in re.findall("([^,]+)", line):
t.append(self.coerce(s1))
fun(t)
def kap(self, t, fun):
u = {}
for k,v in enumerate(t):
v, k = fun(k,v)
u[k or len(u)+1] = v
return u
def o(self):
return
def cosine(self, a,b,c):
x1 = (a**2 + c**2 - b**2) / (2**c)
x2 = max(0,min(1,x1))
y = (abs(a**2 - x2**2))**(0.5)
return (x2, y)
def any(self, t):
rintVal = self.rint(None, len(t) - 1)
return t[rintVal]
def many(self,t,n):
u = []
for i in range(1, n + 1):
u.append(self.any(t))
return u
def settings(self,s):
t={}
res = re.findall("\n[\s]+[-][\S]+[\s]+[-][-]([\S]+)[^\n]+= ([\S]+)", s)
for k,v in res:
t[k] = self.coerce(v)
return t
def cli(self,options):
for k,v in options.items():
v = str(v)
for n, x in enumerate(sys.argv):
if x== "-" + k[0] or x == "--" + k:
v = (sys.argv[n + 1] if n + 1 < len(
sys.argv) else False) or v == "False" and "true" or v == "True" and "false"
options[k] = self.coerce(v)
return options
def show(self,node,what,cols,nPlaces,lvl=None):
if node:
lvl = lvl or 0
print("| " * lvl + str(len(node["data"].rows)) + " ", end="")
if ("left" not in node) or lvl == 0:
print(node["data"].stats("mid", node["data"].cols.y, nPlaces))
else:
print("")
self.show(node.get("left", None), what, cols, nPlaces, lvl+1)
self.show(node.get("right", None), what, cols, nPlaces, lvl+1)
| true |
cd5f23b7b7d336be09837689e487a2fe181bf5c3 | Python | Andrewlearning/Leetcoding | /leetcode/Math/264. 丑数II(第n个丑数,DP).py | UTF-8 | 1,317 | 4.09375 | 4 | [] | no_license | """
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
一个数仅由 2,3,5的乘积构成
"""
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
if n < 1:
return n
res = [1 for i in range(n)]
p2 = 0
p3 = 0
p5 = 0
for i in range(1, n):
cur_min = min(res[p2] * 2, res[p3] * 3, res[p5] * 5)
res[i] = cur_min
# 为什么要三个if, 而不是elif
# 因为有可能产生的cur_min, 可以由不同的乘积得到,我们要更新全部指针
if cur_min == res[p2] * 2:
p2 += 1
if cur_min == res[p3] * 3:
p3 += 1
if cur_min == res[p5] * 5:
p5 += 1
return res[n - 1]
"""
Time: O(n), Space: O(n)
答案:
这题是使用dp来做的
1.由于我们想让res里的元素,是丑数从小到大的排序
2.每个丑数都有 *2,3,5的机会,但是要看res[i]的下一位最小是多少
3.由于p2,p3,p5都是代表着res里的index,等于是这几个index*(2,3,5)在竞赛,看哪个的
更小,就放到下一位。
3.由此可以推出第n个丑数的大小
"""
| true |
766f1cdae4ca8ca4dea7374423d6d5bff6f58b8c | Python | JannaKim/PS | /DFS&BFS/음료수얼려먹기.py | UTF-8 | 499 | 2.8125 | 3 | [] | no_license | N, M = map(int, input().split())
mp=[]
mp.append([1]*(M+2))
for _ in range(N):
mp.append([1]+[int(i) for i in input()]+[1])
mp.append([1]*(M+2))
# [print(i) for i in mp]
dx=[0,0,1,-1]
dy=[1,-1,0,0]
def dfs(i,j):
mp[i][j]=1
for x, y in zip(dx,dy):
if mp[i+x][j+y]==0:
dfs(i+x,j+y)
cnt=0
for i in range(1,N+1):
for j in range(1,M+1):
if mp[i][j]==0:
dfs(i,j)
cnt+=1
print(cnt)
'''
4 5
00110
00011
11111
00000
'''
| true |
30ae304892ff4510e6169c2d708b932ece5cd5cf | Python | yuanhuiru/xnr2 | /xnr_0429/xnr/cron/fb_xnr_operate/social_sensing/get_keywords.py | UTF-8 | 1,476 | 3.5 | 4 | [] | no_license | # -*-coding:utf-8-*-
from textrank4zh import TextRank4Keyword,TextRank4Sentence
def extract_keyword(text):
word = TextRank4Keyword()
word.analyze(text,window = 2,lower = True)
w_list = word.get_keywords(num = 20,word_min_len = 1)
print w_list
for w in w_list:
print w.word,w.weight
print sorted(w_list, key=lambda x:x["weight"], reverse=True)[:5]
phrase = word.get_keyphrases(keywords_num = 5,min_occur_num=2)
if __name__ == "__main__":
text = "【江西一老人遇车祸拒绝赔偿,现场安慰司机“我不讹你们的钱”】3月3日,一篇《#不讹人#为刘振仕老人点赞》的微博引发网友关注。据博主介绍,刘振仕今年77岁,是吉安市泰和县人。2日上午,刘振仕乘坐的三轮车拐道时,和相向的一辆小车相撞。当即,三轮车侧翻,他从车上摔下来,所幸仅手掌被擦伤了一点。正当小车司机肖杨杰手足无策时,老人安慰他们别慌:“我不讹司机,我家四个儿子都有车,知道开车的难处,我不讹你们的冤枉钱。”救护车来后,老人还是不肯去,“去一下医院至少一千多,你们现在赚钱也不容易,我到时候回家敷点草药就没事了,你们放心。就算等会真的有什么事,我也不会找你们麻烦。”老人还拒绝了肖杨杰的赔偿,说给了钱也会花掉。肖杨杰说,自己当时非常感动,无以言"
extract_keyword(text)
| true |
200714b49d9cb4ffffdb165620a534658da2dd64 | Python | ahuangya/Practice | /lib_practice/pra_json.py | UTF-8 | 918 | 2.609375 | 3 | [] | no_license | # !/usr/bin/env python
# -*-coding:utf-8-*-
# **************************************
# Filename:pra_json.py
# Author:huangya
# Description:
# time:2017-01-21
# ***************************************
import json
global type_list
type_list = []
def dict2json(dict):
"""
dict convert json
"""
json_str = json.dumps(dict)
return json_str
def ergodic_json(json_str):
"""
input json
output value list
"""
global type_list
data = json.loads(json_str)
keylist = data.keys()
for i in range(len(keylist)):
if type(data[keylist[i]]) == type({}):
json_str = dict2json(data[keylist[i]])
type_list.append(type(data[keylist[i]]))
return ergodic_json(json_str)
else:
type_list.append(type(data[keylist[i]]))
print type_list
return type_list
dict = {"key1": 12}
ergodic_json(dict2json(dict))
| true |
08f5f5546a474cf1279eeca36f698001277dbefe | Python | nyucusp/gx5003-fall2013 | /yz1897/Assigment2/problem1.py | UTF-8 | 1,077 | 2.578125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 17:32:28 2013
@author: yilong
"""
import time
import sys
def find_late_student():
try:
deadline=sys.argv()[1]
#get the deadline as parameter
except:
deadline='09/19/2013 09:12:15'#
find=0
for line in file("c:/works/dropbox/Git/data/logsofar.txt"):
#record the author information, update every time reading a new log
if line.find("Author:")!=-1:
Author=line[:-1].split(": ")[1]
if line.find("Author:")!=-1:
Author=line[:-1].split(": ")[1]
#record the data information
find=line.find("Date:")
if find!=-1:
committime=line[:-1].split(": ")[1]
time1=time.strptime(committime[:-6],"%a %b %d %H:%M:%S %Y")
time2=time.strptime(deadline,"%m/%d/%Y %H:%M:%S")
if time2<time1:
print Author
print time1
if __name__=="__main__":
find_late_student() | true |
8bd75065b335df58581f3e158453ce0b483aeba2 | Python | ksh1ng/ML | /hw1/ML_hw1.py | UTF-8 | 3,843 | 3.09375 | 3 | [] | no_license | #ML HW1
import csv
import numpy as np
data = []
# 每一個維度儲存一種污染物的資訊
for i in range(18):
data.append([])
n_row = 0
train_f = open('train.csv', 'r', encoding='big5')
row = csv.reader(train_f, delimiter = ',')
for r in row:
if n_row != 0:
for i in range(3, 27):
if r[i] != 'NR':
data[(n_row - 1)%18].append(float(r[i]))
else:
data[(n_row-1)%18].append(float(0))
n_row += 1
train_f.close()
print(data)
#parse data to (x,y)
x = []
y = []
for i in range(12):
for j in range(471):
x.append([])
for t in range(18):
for s in range(9):
x[471*i + j].append(data[t][480 * i + j +s])
y.append(data[9][480 * i + j + 9])
x = np.array(x)
y = np.array(y)
#add bias (前九小時所有data加一個constant,12個月共可以組成有12*47個連續的九小時)
x = np.concatenate((np.ones((x.shape[0], 1)), x), axis=1)
#init weight and some hyperparameters
#前9九小時包含bias共有18*9 + 1個參數
w = np.zeros(len(x[0])) #column vector (default)
w = np.array(w)
print(w)
l_rate = 0.01
repeat = 100
hypo = np.dot(x,w)
#start training
#by least square error
#可以用least square error的結果當作初始去train
inverse = np.linalg.inv(np.dot(x.transpose(), x)) #(x'x)**(-1)
w = np.dot(x.transpose() , y)
w = np.dot(inverse, w)
#start training
l_rate = 0.00001
repeat = 100
x_t = x.transpose()
sum_grad = np.zeros(len(x[0]))
for i in range(repeat):
hypothesis = np.dot(x, w)
loss = hypothesis - y
cost = np.sum(loss **2) #cost function
a_cost = np.sqrt(cost / len(loss) )
grad = np.dot(x_t, loss)
sum_grad += grad ** 2
ada = np.sqrt(sum_grad)
w = w - l_rate * grad / ada
print('iteration: %d | Cost: %f' %(i, a_cost))
#save/read model
np.save('model.npy',w)
w = np.load('model.npy')
#read testing data
test_x = []
n_row = 0
t_data = open('test.csv', 'r')
row = csv.reader(t_data, delimiter = ',')
for r in row:
#把每九小時內所有data存成test_x裡的一個row
if n_row %18 == 0:
test_x.append([1]) #[1]: 先加bias
for i in range(2, 11):
test_x[n_row // 18].append(float(r[i]))
else:
for i in range(2,11):
if r[i] != 'NR':
test_x[n_row // 18].append(float(r[i]))
else:
test_x[n_row // 18].append(0)
n_row += 1
t_data.close()
test_x = np.array(test_x)
#get ans.csv(prediction result) with your model
ans = []
for i in range(len(test_x)):
ans.append(['id_' + str(i)])
a = np.dot(test_x[i], w)
print(i, a)
ans[i].append(a)
filename = 'predict.csv'
result = open(filename, 'w+') #w+: 開新檔並可讀寫
s = csv.writer(result, delimiter = ',', lineterminator = '\n')
s.writerow(['id', 'value']) #表格的title
for i in range(len(ans)):
print(ans[i])
s.writerow(ans[i]) #writerow: 可以直接把一行row array寫成一行
result.close()
'''
#by least square error
inverse = np.linalg.inv(np.dot(x.transpose(), x)) #(x'x)**(-1)
w = np.dot(x.transpose() , y)
w = np.dot(inverse, w)
hypothesis = np.dot(x, w)
loss = hypothesis - y
cost = np.sum(loss **2)
a_cost = np.sqrt(cost / len(loss) )
print(a_cost)
#可以用least square error的結果當作初始去train
#start training
l_rate = 0.00001
repeat = 1000000
x_t = x.transpose()
sum_grad = np.zeros(len(x[0]))
for i in range(repeat):
hypothesis = np.dot(x, w)
loss = hypothesis - y
cost = np.sum(loss **2) #cost function
a_cost = np.sqrt(cost / len(loss) )
grad = np.dot(x_t, loss)
sum_grad += grad ** 2
ada = np.sqrt(sum_grad)
w = w - l_rate * grad / ada
print('iteration: %d | Cost: %f' %(i, a_cost))
#save/read model
np.save('model.npy',w)
w = np.load('model.npy')
''' | true |
e250d9f9632f3cafe9a1870500fcb5036cf61b79 | Python | jovaandres/daspro | /riwayatpinjam.py | UTF-8 | 4,650 | 3.296875 | 3 | [] | no_license | #riwayatpinjam.py
#F11 - Melihat Riwayat Peminjaman Gadget
#tanggal pembuatan: 17 April 2021
import time as datetime
from load import gadgetBorrowHistoryDatas, gadgetDatas, userDatas
#FUNGSI/PROSEDURAL
def tampil_lagi(sorted_datas,idx):
p = True #kondisi untuk loop while
while p:
#Menampilkan riwayat jika sisa jumlah data <= 5
if len(sorted_datas)-idx<=5:
for i in range (len(sorted_datas)-idx):
print("ID Peminjaman :",sorted_datas[idx+i][0])
print("Nama Pengambil :",cek_nama_user(sorted_datas[idx+i][1]))
print("Nama Gadget :",cek_nama(sorted_datas[idx+i][2]))
print("Tanggal peminjaman :",sorted_datas[idx+i][3])
print("Jumlah :",sorted_datas[idx+i][4])
print()
print("Ini adalah akhir dari riwayat peminjaman gadget")
p = False
#Menampilkan riwayat jika sisa jumlah data > 5
else: #len(sorted_datas)>5
for i in range (5):
print("ID Peminjaman :",sorted_datas[idx+i][0])
print("Nama Pengambil :",cek_nama_user(sorted_datas[idx+i][1]))
print("Nama Gadget :",cek_nama(sorted_datas[idx+i][2]))
print("Tanggal peminjaman :",sorted_datas[idx+i][3])
print("Jumlah :",sorted_datas[idx+i][4])
print()
print("Apakah Anda ingin melihat riwayat peminjaman gadget lainnya? (Y/N)")
parameter = input(">>> ")
if parameter == 'Y':
idx += 5
tampil_lagi(sorted_datas,idx)
elif parameter == 'N':
print("Pengaksesan riwayat peminjaman gadget selesai")
else:
print("Terjadi kesalahan saat input")
return idx
#ALGORITMA UTAMA
def riwayat_pinjam():
global gadgetBorrowHistoryDatas
#Pengaksesan file dan konversi
datas = gadgetBorrowHistoryDatas["datas"]
#Mengurutkan tanggal dan id berdasarkan tanggal
#Pengembalian secara descending
list_tanggal=[]
for i in range (len(datas)):
tmp = [] #template buat nyimpen nilai id dan tanggal
tmp.append(str(datas[i][0]))
tmp.append(datas[i][3])
list_tanggal.append(tmp) #list_tanggal = [[id,tanggal_peminjaman],[..]..]
sorted_list_tanggal = sorted(list_tanggal, key=lambda t: datetime.strptime(t[1], '%d/%m/%Y' ), reverse= True) #t[1] karena posisi tanggal di arraynya
#Mengurutkan data berdasarkan tanggal secara descending
sorted_datas = []
for i in range (len(datas)):
for j in range (len(datas)):
if sorted_list_tanggal[i][0] == datas[j][0]:
sorted_datas.append(datas[j])
#Menampilkan riwayat jika jumlah data <= 5
if len(sorted_datas)<=5:
for i in range (len(sorted_datas)):
print("ID Peminjaman :",sorted_datas[i][0])
print("Nama Pengambil :",cek_nama_user(sorted_datas[i][1]))
print("Nama Gadget :",cek_nama(sorted_datas[i][2]))
print("Tanggal peminjaman :",sorted_datas[i][3])
print("Jumlah :",sorted_datas[i][4])
print()
print("Ini adalah akhir dari riwayat peminjaman gadget")
#Menampilkan riwayat jika jumlah data > 5
else: #len(sorted_datas)>5
for i in range (5):
print("ID Peminjaman :",sorted_datas[i][0])
print("Nama Pengambil :",cek_nama_user(sorted_datas[i][1]))
print("Nama Gadget :",cek_nama(sorted_datas[i][2]))
print("Tanggal peminjaman :",sorted_datas[i][3])
print("Jumlah :",sorted_datas[i][4])
print()
print("Apakah Anda ingin melihat riwayat peminjaman gadget lainnya? (Y/N)")
parameter = input(">>> ")
if parameter == 'Y':
idx = 5 #indeks inisiai untuk menampilkan data selanjutnya
tampil_lagi(sorted_datas,idx)
elif parameter == 'N':
print("Pengaksesan riwayat peminjaman gadget selesai")
else:
print("Terjadi kesalahan saat input")
def cek_nama_user(_id):
global userDatas
i = 0
while i < len(userDatas["datas"]):
if userDatas["datas"][i][0] == _id:
return userDatas["datas"][i][2]
i += 1
return ("Not Found")
def cek_nama(_id):
global gadgetDatas
i = 0
while i < len(gadgetDatas["datas"]):
if gadgetDatas["datas"][i][0] == _id:
return gadgetDatas["datas"][i][1]
i += 1
return ("Not Found") | true |
1981ef90455be8faede3ad565ce148a611eaeffc | Python | huangzhuo492008824/websocket | /redisDB.py | UTF-8 | 574 | 2.875 | 3 | [] | no_license | import redis
class RedisDB(object):
"""Simple Queue with Redis Backend"""
def __init__(self, namespace='websocket', **redis_kwargs):
"""The default connection parameters are: host='localhost', port=6379, db=0"""
self.__db = redis.StrictRedis.from_url(url='redis://localhost:6379/0')
self.key = '%s:' % namespace
def set(self, key, val, ex=None):
self.__db.set(self.key+key, val, ex=ex)
def get(self, key):
return self.__db.get(self.key+key)
def delete(self, key):
return self.__db.delete(self.key+key) | true |
a521bb57155107c558280e2a09b6917cb86456ee | Python | nkmk/python-snippets | /notebook/dict_value_max_min_series.py | UTF-8 | 1,007 | 3.6875 | 4 | [
"MIT"
] | permissive | import pandas as pd
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
s = pd.Series(d)
print(s)
# a 100
# b 20
# c 50
# d 100
# e 80
# dtype: int64
print(s.index)
# Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
print(s.values)
# [100 20 50 100 80]
print(s.max())
# 100
print(s.min())
# 20
print(max(s.index))
# e
print(min(s.index))
# a
print(s.idxmax())
# a
print(s.idxmin())
# b
print(s[s == s.max()])
# a 100
# d 100
# dtype: int64
print(s[s == s.max()].index)
# Index(['a', 'd'], dtype='object')
print(s[s == s.max()].index.tolist())
# ['a', 'd']
print(list(s[s == s.max()].index))
# ['a', 'd']
print(s[s == s.min()])
# b 20
# dtype: int64
print(s[s == s.min()].index)
# Index(['b'], dtype='object')
print(s[s == s.min()].index.tolist())
# ['b']
print(list(s[s == s.min()].index))
# ['b']
print(s.sort_values())
# b 20
# c 50
# e 80
# a 100
# d 100
# dtype: int64
print(s[s > 60])
# a 100
# d 100
# e 80
# dtype: int64
| true |