Resolving conflict

This commit is contained in:
Akshath 2023-10-24 18:34:49 +05:30
parent 790529ee12
commit a0d4e04a3c
56 changed files with 95733 additions and 95733 deletions

View File

@ -1,256 +1,256 @@
import tkinter as tk
import random
import colors as c
class Game(tk.Frame):
def __init__(self):
tk.Frame.__init__(self)
self.grid()
self.master.title('2048')
self.main_grid = tk.Frame(
self, bg=c.GRID_COLOR, bd=3, width=400, height=400)
self.main_grid.grid(pady=(100, 0))
self.make_GUI()
self.start_game()
self.master.bind("<Left>", self.left)
self.master.bind("<Right>", self.right)
self.master.bind("<Up>", self.up)
self.master.bind("<Down>", self.down)
self.mainloop()
def make_GUI(self):
# make grid
self.cells = []
for i in range(4):
row = []
for j in range(4):
cell_frame = tk.Frame(
self.main_grid,
bg=c.EMPTY_CELL_COLOR,
width=100,
height=100)
cell_frame.grid(row=i, column=j, padx=5, pady=5)
cell_number = tk.Label(self.main_grid, bg=c.EMPTY_CELL_COLOR)
cell_number.grid(row=i, column=j)
cell_data = {"frame": cell_frame, "number": cell_number}
row.append(cell_data)
self.cells.append(row)
# make score header
score_frame = tk.Frame(self)
score_frame.place(relx=0.5, y=40, anchor="center")
tk.Label(
score_frame,
text="Score",
font=c.SCORE_LABEL_FONT).grid(row=0)
self.score_label = tk.Label(score_frame, text="0", font=c.SCORE_FONT)
self.score_label.grid(row=1)
def start_game(self):
# create matrix of zeroes
self.matrix = [[0] * 4 for _ in range(4)]
# fill 2 random cells with 2s
row = random.randint(0, 3)
col = random.randint(0, 3)
self.matrix[row][col] = 2
self.cells[row][col]["frame"].configure(bg=c.CELL_COLORS[2])
self.cells[row][col]["number"].configure(
bg=c.CELL_COLORS[2],
fg=c.CELL_NUMBER_COLORS[2],
font=c.CELL_NUMBER_FONTS[2],
text="2"
)
while(self.matrix[row][col] != 0):
row = random.randint(0, 3)
col = random.randint(0, 3)
self.matrix[row][col] = 2
self.cells[row][col]["frame"].configure(bg=c.CELL_COLORS[2])
self.cells[row][col]["number"].configure(
bg=c.CELL_COLORS[2],
fg=c.CELL_NUMBER_COLORS[2],
font=c.CELL_NUMBER_FONTS[2],
text="2"
)
self.score = 0
# Matrix Manipulation Functions
def stack(self):
new_matrix = [[0] * 4 for _ in range(4)]
for i in range(4):
fill_position = 0
for j in range(4):
if self.matrix[i][j] != 0:
new_matrix[i][fill_position] = self.matrix[i][j]
fill_position += 1
self.matrix = new_matrix
def combine(self):
for i in range(4):
for j in range(3):
if self.matrix[i][j] != 0 and self.matrix[i][j] == self.matrix[i][j + 1]:
self.matrix[i][j] *= 2
self.matrix[i][j + 1] = 0
self.score += self.matrix[i][j]
def reverse(self):
new_matrix = []
for i in range(4):
new_matrix.append([])
for j in range(4):
new_matrix[i].append(self.matrix[i][3 - j])
self.matrix = new_matrix
def transpose(self):
new_matrix = [[0] * 4 for _ in range(4)]
for i in range(4):
for j in range(4):
new_matrix[i][j] = self.matrix[j][i]
self.matrix = new_matrix
# Add a new 2 or 4 tile randomly to an empty cell
def add_new_tile(self):
row = random.randint(0, 3)
col = random.randint(0, 3)
while(self.matrix[row][col] != 0):
row = random.randint(0, 3)
col = random.randint(0, 3)
self.matrix[row][col] = random.choice([2, 4]) # create new tile of 2 or 4 at any random row & col
# Update the GUI to match the matrix
def update_GUI(self):
for i in range(4):
for j in range(4):
cell_value = self.matrix[i][j]
if cell_value == 0:
self.cells[i][j]["frame"].configure(bg=c.EMPTY_CELL_COLOR) # give bgcolor to empty cell's frame
self.cells[i][j]["number"].configure( # give bgcolor to empty cell's number
bg=c.EMPTY_CELL_COLOR, text="")
else:
self.cells[i][j]["frame"].configure( # give cell colour's value to filled cell's frame
bg=c.CELL_COLORS[cell_value])
self.cells[i][j]["number"].configure(
bg=c.CELL_COLORS[cell_value],
fg=c.CELL_NUMBER_COLORS[cell_value],
font=c.CELL_NUMBER_FONTS[cell_value],
text=str(cell_value))
self.score_label.configure(text=self.score)
self.update_idletasks()
# Arrow-Press Functions
def left(self, event):
self.stack()
self.combine()
self.stack()
self.add_new_tile()
self.update_GUI()
self.game_over()
def right(self, event):
self.reverse()
self.stack()
self.combine()
self.stack()
self.reverse()
self.add_new_tile()
self.update_GUI()
self.game_over()
def up(self, event):
self.transpose()
self.stack()
self.combine()
self.stack()
self.transpose()
self.add_new_tile()
self.update_GUI()
self.game_over()
def down(self, event):
self.transpose()
self.reverse()
self.stack()
self.combine()
self.stack()
self.reverse()
self.transpose()
self.add_new_tile()
self.update_GUI()
self.game_over()
# Check if any moves are possible
def horizontal_move_exists(self):
for i in range(4):
for j in range(3):
if self.matrix[i][j] == self.matrix[i][j + 1]:
return True
return False
def vertical_move_exists(self):
for i in range(3):
for j in range(4):
if self.matrix[i][j] == self.matrix[i + 1][j]:
return True
return False
# Check if Game is Over (Win/Lose)
def game_over(self):
if any(2048 in row for row in self.matrix):
game_over_frame = tk.Frame(self.main_grid, borderwidth=2)
game_over_frame.place(relx=0.5, rely=0.5, anchor="center")
tk.Label(
game_over_frame,
text="You win!",
bg=c.WINNER_BG,
fg=c.GAME_OVER_FONT_COLOR,
font=c.GAME_OVER_FONT).pack()
elif not any(0 in row for row in self.matrix) and not self.horizontal_move_exists()\
and not self.vertical_move_exists():
game_over_frame = tk.Frame(self.main_grid, borderwidth=2)
game_over_frame.place(relx=0.5, rely=0.5, anchor="center")
tk.Label(
game_over_frame,
text="Game over!",
bg=c.LOSER_BG,
fg=c.GAME_OVER_FONT_COLOR,
font=c.GAME_OVER_FONT).pack()
def main():
Game()
if __name__ == "__main__":
import tkinter as tk
import random
import colors as c
class Game(tk.Frame):
def __init__(self):
tk.Frame.__init__(self)
self.grid()
self.master.title('2048')
self.main_grid = tk.Frame(
self, bg=c.GRID_COLOR, bd=3, width=400, height=400)
self.main_grid.grid(pady=(100, 0))
self.make_GUI()
self.start_game()
self.master.bind("<Left>", self.left)
self.master.bind("<Right>", self.right)
self.master.bind("<Up>", self.up)
self.master.bind("<Down>", self.down)
self.mainloop()
def make_GUI(self):
# make grid
self.cells = []
for i in range(4):
row = []
for j in range(4):
cell_frame = tk.Frame(
self.main_grid,
bg=c.EMPTY_CELL_COLOR,
width=100,
height=100)
cell_frame.grid(row=i, column=j, padx=5, pady=5)
cell_number = tk.Label(self.main_grid, bg=c.EMPTY_CELL_COLOR)
cell_number.grid(row=i, column=j)
cell_data = {"frame": cell_frame, "number": cell_number}
row.append(cell_data)
self.cells.append(row)
# make score header
score_frame = tk.Frame(self)
score_frame.place(relx=0.5, y=40, anchor="center")
tk.Label(
score_frame,
text="Score",
font=c.SCORE_LABEL_FONT).grid(row=0)
self.score_label = tk.Label(score_frame, text="0", font=c.SCORE_FONT)
self.score_label.grid(row=1)
def start_game(self):
# create matrix of zeroes
self.matrix = [[0] * 4 for _ in range(4)]
# fill 2 random cells with 2s
row = random.randint(0, 3)
col = random.randint(0, 3)
self.matrix[row][col] = 2
self.cells[row][col]["frame"].configure(bg=c.CELL_COLORS[2])
self.cells[row][col]["number"].configure(
bg=c.CELL_COLORS[2],
fg=c.CELL_NUMBER_COLORS[2],
font=c.CELL_NUMBER_FONTS[2],
text="2"
)
while(self.matrix[row][col] != 0):
row = random.randint(0, 3)
col = random.randint(0, 3)
self.matrix[row][col] = 2
self.cells[row][col]["frame"].configure(bg=c.CELL_COLORS[2])
self.cells[row][col]["number"].configure(
bg=c.CELL_COLORS[2],
fg=c.CELL_NUMBER_COLORS[2],
font=c.CELL_NUMBER_FONTS[2],
text="2"
)
self.score = 0
# Matrix Manipulation Functions
def stack(self):
new_matrix = [[0] * 4 for _ in range(4)]
for i in range(4):
fill_position = 0
for j in range(4):
if self.matrix[i][j] != 0:
new_matrix[i][fill_position] = self.matrix[i][j]
fill_position += 1
self.matrix = new_matrix
def combine(self):
for i in range(4):
for j in range(3):
if self.matrix[i][j] != 0 and self.matrix[i][j] == self.matrix[i][j + 1]:
self.matrix[i][j] *= 2
self.matrix[i][j + 1] = 0
self.score += self.matrix[i][j]
def reverse(self):
new_matrix = []
for i in range(4):
new_matrix.append([])
for j in range(4):
new_matrix[i].append(self.matrix[i][3 - j])
self.matrix = new_matrix
def transpose(self):
new_matrix = [[0] * 4 for _ in range(4)]
for i in range(4):
for j in range(4):
new_matrix[i][j] = self.matrix[j][i]
self.matrix = new_matrix
# Add a new 2 or 4 tile randomly to an empty cell
def add_new_tile(self):
row = random.randint(0, 3)
col = random.randint(0, 3)
while(self.matrix[row][col] != 0):
row = random.randint(0, 3)
col = random.randint(0, 3)
self.matrix[row][col] = random.choice([2, 4]) # create new tile of 2 or 4 at any random row & col
# Update the GUI to match the matrix
def update_GUI(self):
for i in range(4):
for j in range(4):
cell_value = self.matrix[i][j]
if cell_value == 0:
self.cells[i][j]["frame"].configure(bg=c.EMPTY_CELL_COLOR) # give bgcolor to empty cell's frame
self.cells[i][j]["number"].configure( # give bgcolor to empty cell's number
bg=c.EMPTY_CELL_COLOR, text="")
else:
self.cells[i][j]["frame"].configure( # give cell colour's value to filled cell's frame
bg=c.CELL_COLORS[cell_value])
self.cells[i][j]["number"].configure(
bg=c.CELL_COLORS[cell_value],
fg=c.CELL_NUMBER_COLORS[cell_value],
font=c.CELL_NUMBER_FONTS[cell_value],
text=str(cell_value))
self.score_label.configure(text=self.score)
self.update_idletasks()
# Arrow-Press Functions
def left(self, event):
self.stack()
self.combine()
self.stack()
self.add_new_tile()
self.update_GUI()
self.game_over()
def right(self, event):
self.reverse()
self.stack()
self.combine()
self.stack()
self.reverse()
self.add_new_tile()
self.update_GUI()
self.game_over()
def up(self, event):
self.transpose()
self.stack()
self.combine()
self.stack()
self.transpose()
self.add_new_tile()
self.update_GUI()
self.game_over()
def down(self, event):
self.transpose()
self.reverse()
self.stack()
self.combine()
self.stack()
self.reverse()
self.transpose()
self.add_new_tile()
self.update_GUI()
self.game_over()
# Check if any moves are possible
def horizontal_move_exists(self):
for i in range(4):
for j in range(3):
if self.matrix[i][j] == self.matrix[i][j + 1]:
return True
return False
def vertical_move_exists(self):
for i in range(3):
for j in range(4):
if self.matrix[i][j] == self.matrix[i + 1][j]:
return True
return False
# Check if Game is Over (Win/Lose)
def game_over(self):
if any(2048 in row for row in self.matrix):
game_over_frame = tk.Frame(self.main_grid, borderwidth=2)
game_over_frame.place(relx=0.5, rely=0.5, anchor="center")
tk.Label(
game_over_frame,
text="You win!",
bg=c.WINNER_BG,
fg=c.GAME_OVER_FONT_COLOR,
font=c.GAME_OVER_FONT).pack()
elif not any(0 in row for row in self.matrix) and not self.horizontal_move_exists()\
and not self.vertical_move_exists():
game_over_frame = tk.Frame(self.main_grid, borderwidth=2)
game_over_frame.place(relx=0.5, rely=0.5, anchor="center")
tk.Label(
game_over_frame,
text="Game over!",
bg=c.LOSER_BG,
fg=c.GAME_OVER_FONT_COLOR,
font=c.GAME_OVER_FONT).pack()
def main():
Game()
if __name__ == "__main__":
main()

View File

@ -1,50 +1,50 @@
GRID_COLOR = "#a39489"
EMPTY_CELL_COLOR = "#c2b3a9"
SCORE_LABEL_FONT = ("Verdana", 20)
SCORE_FONT = ("Helvetica", 32, "bold")
GAME_OVER_FONT = ("Helvetica", 48, "bold")
GAME_OVER_FONT_COLOR = "#ffffff"
WINNER_BG = "#ffcc00"
LOSER_BG = "#a39489"
CELL_COLORS = {
2: "#fcefe6",
4: "#f2e8cb",
8: "#f5b682",
16: "#f29446",
32: "#ff775c",
64: "#e64c2e",
128: "#ede291",
256: "#fce130",
512: "#ffdb4a",
1024: "#f0b922",
2048: "#fad74d"
}
CELL_NUMBER_COLORS = {
2: "#695c57",
4: "#695c57",
8: "#ffffff",
16: "#ffffff",
32: "#ffffff",
64: "#ffffff",
128: "#ffffff",
256: "#ffffff",
512: "#ffffff",
1024: "#ffffff",
2048: "#ffffff"
}
CELL_NUMBER_FONTS = {
2: ("Helvetica", 55, "bold"),
4: ("Helvetica", 55, "bold"),
8: ("Helvetica", 55, "bold"),
16: ("Helvetica", 50, "bold"),
32: ("Helvetica", 50, "bold"),
64: ("Helvetica", 50, "bold"),
128: ("Helvetica", 45, "bold"),
256: ("Helvetica", 45, "bold"),
512: ("Helvetica", 45, "bold"),
1024: ("Helvetica", 40, "bold"),
2048: ("Helvetica", 40, "bold")
GRID_COLOR = "#a39489"
EMPTY_CELL_COLOR = "#c2b3a9"
SCORE_LABEL_FONT = ("Verdana", 20)
SCORE_FONT = ("Helvetica", 32, "bold")
GAME_OVER_FONT = ("Helvetica", 48, "bold")
GAME_OVER_FONT_COLOR = "#ffffff"
WINNER_BG = "#ffcc00"
LOSER_BG = "#a39489"
CELL_COLORS = {
2: "#fcefe6",
4: "#f2e8cb",
8: "#f5b682",
16: "#f29446",
32: "#ff775c",
64: "#e64c2e",
128: "#ede291",
256: "#fce130",
512: "#ffdb4a",
1024: "#f0b922",
2048: "#fad74d"
}
CELL_NUMBER_COLORS = {
2: "#695c57",
4: "#695c57",
8: "#ffffff",
16: "#ffffff",
32: "#ffffff",
64: "#ffffff",
128: "#ffffff",
256: "#ffffff",
512: "#ffffff",
1024: "#ffffff",
2048: "#ffffff"
}
CELL_NUMBER_FONTS = {
2: ("Helvetica", 55, "bold"),
4: ("Helvetica", 55, "bold"),
8: ("Helvetica", 55, "bold"),
16: ("Helvetica", 50, "bold"),
32: ("Helvetica", 50, "bold"),
64: ("Helvetica", 50, "bold"),
128: ("Helvetica", 45, "bold"),
256: ("Helvetica", 45, "bold"),
512: ("Helvetica", 45, "bold"),
1024: ("Helvetica", 40, "bold"),
2048: ("Helvetica", 40, "bold")
}

View File

@ -1,127 +1,127 @@
import random
print("wassup hommie, care to play a game?")
print("i'll try to guess the number YOU choose.")
print("please tell me the borders: ")
a = int(input("Min: "))
b = int(input("Max: "))
while True:
if(a > b):
(print("error, min can't be more than max. "))
a = int(input("Min: "))
b = int(input("Max: "))
else:
break;
breaking = "------------"
print("now type in the number: ")
c = int(input(" "))
tries = 1;
d = random.randint(a, b)
while True:
if(d == c and tries == 1):
print("guess 1: " + str(d))
print("HA, gotcha. I got it in 1 time!")
print("Wanna go again? y for yes and anykey for no. ")
i = input("");
if(i == "y"):
print(breaking * 10);
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
tries = 1;
if(a > b):
print("error, min can't be more than max. ")
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
else:
d = random.randint(a, b)
else:
break;
elif(d == c):
print("HA, gotcha. I got it in " + str(tries - 1) + " times!")
print("Wanna go again? y for yes and anykey for no. ")
i = input("");
if(i == "y"):
print(breaking * 10);
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
tries = 1;
if(a > b):
print("error, min can't be more than max. ")
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
else:
d = random.randint(a, b)
else:
break;
elif(c > b):
print("error, number can't be bigger than max.");
print("Wanna go again? y for yes and anykey for no. ")
i = input("");
if(i == "y"):
print(breaking * 10);
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
tries = 1;
if(a > b):
(print("error, min can't be more than max. "))
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
else:
d = random.randint(a, b)
else:
break;
elif(c < a):
print("error, number can't be smaller than min.");
print("Wanna go again? y for yes and anykey for no. ")
i = input("");
if(i == "y"):
print(breaking * 10);
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
tries = 1;
if(a > b):
print("error, min can't be more than max. ")
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
else:
d = random.randint(a, b)
else:
break;
elif(d < c):
a = d + 1;
d = random.randint(a, b)
print( "guess " + str(tries) + " :" + str(d));
tries += 1;
elif(d > c):
b = d - 1;
d = random.randint(a, b)
print( "guess " + str(tries) + " :" + str(d))
tries += 1
input=""
import random
print("wassup hommie, care to play a game?")
print("i'll try to guess the number YOU choose.")
print("please tell me the borders: ")
a = int(input("Min: "))
b = int(input("Max: "))
while True:
if(a > b):
(print("error, min can't be more than max. "))
a = int(input("Min: "))
b = int(input("Max: "))
else:
break;
breaking = "------------"
print("now type in the number: ")
c = int(input(" "))
tries = 1;
d = random.randint(a, b)
while True:
if(d == c and tries == 1):
print("guess 1: " + str(d))
print("HA, gotcha. I got it in 1 time!")
print("Wanna go again? y for yes and anykey for no. ")
i = input("");
if(i == "y"):
print(breaking * 10);
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
tries = 1;
if(a > b):
print("error, min can't be more than max. ")
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
else:
d = random.randint(a, b)
else:
break;
elif(d == c):
print("HA, gotcha. I got it in " + str(tries - 1) + " times!")
print("Wanna go again? y for yes and anykey for no. ")
i = input("");
if(i == "y"):
print(breaking * 10);
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
tries = 1;
if(a > b):
print("error, min can't be more than max. ")
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
else:
d = random.randint(a, b)
else:
break;
elif(c > b):
print("error, number can't be bigger than max.");
print("Wanna go again? y for yes and anykey for no. ")
i = input("");
if(i == "y"):
print(breaking * 10);
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
tries = 1;
if(a > b):
(print("error, min can't be more than max. "))
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
else:
d = random.randint(a, b)
else:
break;
elif(c < a):
print("error, number can't be smaller than min.");
print("Wanna go again? y for yes and anykey for no. ")
i = input("");
if(i == "y"):
print(breaking * 10);
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
tries = 1;
if(a > b):
print("error, min can't be more than max. ")
a = int(input("Min: "))
b = int(input("Max: "))
print("now type in the number")
c = int(input(" "))
else:
d = random.randint(a, b)
else:
break;
elif(d < c):
a = d + 1;
d = random.randint(a, b)
print( "guess " + str(tries) + " :" + str(d));
tries += 1;
elif(d > c):
b = d - 1;
d = random.randint(a, b)
print( "guess " + str(tries) + " :" + str(d))
tries += 1
input=""

View File

@ -1,7 +1,7 @@
id,file_name,file_url,download_date,download_status
1430,sample_video1.mp4,https://example.com/download/sample_video1.mp4,05/10/22,
239,sample_video2.mp4,https://example.com/download/sample_video2.mp4,05/10/22,
3421,sample_video3.mp4,https://example.com/download/sample_video3.mp4,05/10/22,
1305,sample_video4.mp4,https://example.com/download/sample_video4.mp4,05/10/22,
6375,sample_video5.mp4,https://example.com/download/sample_video5.mp4,06/10/22,done
1203,sample_video6.mp4,https://example.com/download/sample_video6.mp4,06/10/22,done
id,file_name,file_url,download_date,download_status
1430,sample_video1.mp4,https://example.com/download/sample_video1.mp4,05/10/22,
239,sample_video2.mp4,https://example.com/download/sample_video2.mp4,05/10/22,
3421,sample_video3.mp4,https://example.com/download/sample_video3.mp4,05/10/22,
1305,sample_video4.mp4,https://example.com/download/sample_video4.mp4,05/10/22,
6375,sample_video5.mp4,https://example.com/download/sample_video5.mp4,06/10/22,done
1203,sample_video6.mp4,https://example.com/download/sample_video6.mp4,06/10/22,done

1 id file_name file_url download_date download_status
2 1430 sample_video1.mp4 https://example.com/download/sample_video1.mp4 05/10/22
3 239 sample_video2.mp4 https://example.com/download/sample_video2.mp4 05/10/22
4 3421 sample_video3.mp4 https://example.com/download/sample_video3.mp4 05/10/22
5 1305 sample_video4.mp4 https://example.com/download/sample_video4.mp4 05/10/22
6 6375 sample_video5.mp4 https://example.com/download/sample_video5.mp4 06/10/22 done
7 1203 sample_video6.mp4 https://example.com/download/sample_video6.mp4 06/10/22 done

View File

@ -1,92 +1,92 @@
#!/usr/bin/python
import sys
import copy
import argparse
import itertools
def parse_arguments():
parser = argparse.ArgumentParser(description = 'Countdown - Numbers Game',
add_help = False)
parser._optionals.title = 'Target and List Numbers'
parser.add_argument('-h', '--help', action = 'help',
default = argparse.SUPPRESS,
help = 'Countdown Numbers Game. Inform a list of six numbers (-l) and a target (-t).')
parser.add_argument('-t', '--target', type = int, action = 'store',
dest = 'target', default = 100, help = 'The target of the game.')
parser.add_argument('-l', '--list', type = int, nargs = '+',
default = [1, 2, 4, 8, 10, 25], help = 'List with six integers.')
arguments = parser.parse_args()
return arguments
pd = {}
def nubmers_game(L, t, s, ol):
global pd
ops = ['+', '-', '*', '/']
ss = copy.deepcopy(s)
key = str((ss, L))
if key in pd:
return pd[key]
if len(L) == 1:
if L[0] == t:
print(f'Target: {t}\nNumbers: {ol}\nSolution: {ss}')
return True
else:
pd[key] = False
return False
else:
for c in itertools.combinations(L, 2):
if not c[0] or not c[1]:
continue
tmp = L[:]
tmp.remove(c[0])
tmp.remove(c[1])
exp1 = f'{c[0]} %s {c[1]}'
exp2 = f'{c[1]} %s {c[0]}'
if nubmers_game(tmp + [c[0] + c[1]], t, ss + [exp1 % ('+')], ol):
return True
elif nubmers_game(tmp + [c[0] - c[1]], t, ss + [exp1 % ('-')], ol):
return True
elif nubmers_game(tmp + [c[1] - c[0]], t, ss + [exp2 % ('-')], ol):
return True
elif nubmers_game(tmp + [c[0] * c[1]], t, ss + [exp1 % ('*')], ol):
return True
elif c[0] % c[1] == 0 and nubmers_game(tmp + [c[0] // c[1]], t, ss + [exp1 % ('/')], ol):
return True
elif c[1] % c[0] == 0 and nubmers_game(tmp + [c[1] // c[0]], t, ss + [exp2 % ('/')], ol):
return True
elif nubmers_game(tmp + [c[0]], t, ss, ol):
return True
elif nubmers_game(tmp + [c[1]], t, ss, ol):
return True
pd[key] = False
return False
if __name__ == '__main__':
args = parse_arguments()
if len(args.list) != 6:
print(f'The set of numbers in Countdown is 6.')
sys.exit(-1)
if args.target < 0 or args.target > 999:
print(f'The target number in Countdown is between 0 and 999.')
sys.exit(-1)
if not nubmers_game(args.list, args.target, [], args.list):
print(f'Target: {args.target}')
print(f'Numbers: {args.list}')
print(f'Solution: Not found.')
#!/usr/bin/python
import sys
import copy
import argparse
import itertools
def parse_arguments():
parser = argparse.ArgumentParser(description = 'Countdown - Numbers Game',
add_help = False)
parser._optionals.title = 'Target and List Numbers'
parser.add_argument('-h', '--help', action = 'help',
default = argparse.SUPPRESS,
help = 'Countdown Numbers Game. Inform a list of six numbers (-l) and a target (-t).')
parser.add_argument('-t', '--target', type = int, action = 'store',
dest = 'target', default = 100, help = 'The target of the game.')
parser.add_argument('-l', '--list', type = int, nargs = '+',
default = [1, 2, 4, 8, 10, 25], help = 'List with six integers.')
arguments = parser.parse_args()
return arguments
pd = {}
def nubmers_game(L, t, s, ol):
global pd
ops = ['+', '-', '*', '/']
ss = copy.deepcopy(s)
key = str((ss, L))
if key in pd:
return pd[key]
if len(L) == 1:
if L[0] == t:
print(f'Target: {t}\nNumbers: {ol}\nSolution: {ss}')
return True
else:
pd[key] = False
return False
else:
for c in itertools.combinations(L, 2):
if not c[0] or not c[1]:
continue
tmp = L[:]
tmp.remove(c[0])
tmp.remove(c[1])
exp1 = f'{c[0]} %s {c[1]}'
exp2 = f'{c[1]} %s {c[0]}'
if nubmers_game(tmp + [c[0] + c[1]], t, ss + [exp1 % ('+')], ol):
return True
elif nubmers_game(tmp + [c[0] - c[1]], t, ss + [exp1 % ('-')], ol):
return True
elif nubmers_game(tmp + [c[1] - c[0]], t, ss + [exp2 % ('-')], ol):
return True
elif nubmers_game(tmp + [c[0] * c[1]], t, ss + [exp1 % ('*')], ol):
return True
elif c[0] % c[1] == 0 and nubmers_game(tmp + [c[0] // c[1]], t, ss + [exp1 % ('/')], ol):
return True
elif c[1] % c[0] == 0 and nubmers_game(tmp + [c[1] // c[0]], t, ss + [exp2 % ('/')], ol):
return True
elif nubmers_game(tmp + [c[0]], t, ss, ol):
return True
elif nubmers_game(tmp + [c[1]], t, ss, ol):
return True
pd[key] = False
return False
if __name__ == '__main__':
args = parse_arguments()
if len(args.list) != 6:
print(f'The set of numbers in Countdown is 6.')
sys.exit(-1)
if args.target < 0 or args.target > 999:
print(f'The target number in Countdown is between 0 and 999.')
sys.exit(-1)
if not nubmers_game(args.list, args.target, [], args.list):
print(f'Target: {args.target}')
print(f'Numbers: {args.list}')
print(f'Solution: Not found.')

0
Crypt_Socket/cryptSocket_cliente.py Executable file → Normal file
View File

0
Crypt_Socket/cryptSocket_servidor.py Executable file → Normal file
View File

0
DOH-Dig/doh-dig Executable file → Normal file
View File

View File

@ -1,24 +1,24 @@
import os
import shutil
#The Path of the directory to be sorted
path = 'C:\\Users\\<USERNAME>\\Downloads'
#This populates a list with the filenames in the directory
list_ = os.listdir(path)
#Traverses every file
for file_ in list_:
name,ext = os.path.splitext(file_)
print(name)
#Stores the extension type
ext = ext[1:]
#If it is directory, it forces the next iteration
if ext == '':
continue
#If a directory with the name 'ext' exists, it moves the file to that directory
if os.path.exists(path+'/'+ext):
shutil.move(path+'/'+file_,path+'/'+ext+'/'+file_)
#If the directory does not exist, it creates a new directory
else:
os.makedirs(path+'/'+ext)
shutil.move(path+'/'+file_,path+'/'+ext+'/'+file_)
import os
import shutil
#The Path of the directory to be sorted
path = 'C:\\Users\\<USERNAME>\\Downloads'
#This populates a list with the filenames in the directory
list_ = os.listdir(path)
#Traverses every file
for file_ in list_:
name,ext = os.path.splitext(file_)
print(name)
#Stores the extension type
ext = ext[1:]
#If it is directory, it forces the next iteration
if ext == '':
continue
#If a directory with the name 'ext' exists, it moves the file to that directory
if os.path.exists(path+'/'+ext):
shutil.move(path+'/'+file_,path+'/'+ext+'/'+file_)
#If the directory does not exist, it creates a new directory
else:
os.makedirs(path+'/'+ext)
shutil.move(path+'/'+file_,path+'/'+ext+'/'+file_)

View File

@ -1,207 +1,207 @@
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
import os
import telegram
import shutil
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
import os
import telegram
import shutil
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
#list of authorized users
#create a list of telegram usernames to authorise them, 0th username is admin.
username_list = []
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
"""Send a message when the command /start is issued."""
reply = "Welcome to World of Automation. \nI am a bot developed by a Lazy Programmer.\nSend /help command to see what i can do."
update.message.reply_text(reply)
def help(bot, update):
"""Send a message when the command /help is issued."""
admin = update.message.from_user.username
if admin == username_list[0]:
reply = '''Send /get folder_name/file_name.extension to receive a file.
\nSend /ls folder_name to show list of files.
\nSend /put folder_name/file_name.extension to upload last sent file.
\nSend /mkdir folder_name to create a Folder.
\nSend /remove folder_name/filename.extension to delete a file.
\nSend /adduser username to give access.
\nSend /removeuser username to revoke access.
\nSend /showuser to show list of users
'''
else:
reply = '''Send /get folder_name/file_name.extension to receive a file.
\nSend /ls folder_name to show list of files.
\nSend /put folder_name/file_name.extension to upload last sent file.
\nSend /mkdir folder_name to create a Folder.
'''
update.message.reply_text(reply)
def get(bot, update):
"""Send requested file."""
username = update.message.from_user.username
if(username not in username_list):
update.message.reply_text("You are not Authorized.")
return
file = update.message.text.split(" ")[-1]
if(file == "/send"):
update.message.reply_text("Invalid File name.")
else:
reply = "Findind and Sending a requested file to you. Hold on..."
update.message.reply_text(reply)
path = os.getcwd()+'/'+file
if (os.path.exists(path)):
bot.send_document(chat_id=update.message.chat_id,document=open(path, 'rb'), timeout = 100)
else:
update.message.reply_text("File not Found.")
def ls(bot, update):
"""Show files in requested directory."""
username = update.message.from_user.username
if(username not in username_list):
update.message.reply_text("You are not Authorized.")
return
file = update.message.text.split(" ")[-1]
if(file == "/show"):
update.message.reply_text("Invalid Directory name.")
else:
reply = "Findind and Sending a list of files to you. Hold on..."
update.message.reply_text(reply)
path = os.getcwd()+'/'+file
if (os.path.exists(path)):
update.message.reply_text(os.listdir(path))
else:
update.message.reply_text("Directory not Found.")
def put(bot, update):
f = open(str(os.getcwd())+"/file", "r")
file_id = f.read()
f.close
if file_id == "":
update.message.reply_text("You didn't upload file.")
else:
new_file = bot.get_file(file_id)
message = update.message.text.split(" ")
path = message[-1]
if len(path) < 1:
update.message.reply_text("Enter Path correctly.")
else:
new_file.download(os.getcwd()+'/'+path)
update.message.reply_text("File Stored.")
def mkdir(bot, update):
message = update.message.text.split(" ")
if len(message) < 1 or message[-1] == "/mkdir":
update.message.reply_text("Invalid Syntax. Refer syntax in help section.")
return
path = os.getcwd() + "/" + message[-1]
os.mkdir(path)
update.message.reply_text("Folder Created.")
def echo(bot, update):
"""Echo the user message."""
if update.message.document:
file_id = update.message.document.file_id
f = open(str(os.getcwd())+"/file", "w")
f.write(file_id)
f.close
update.message.reply_text("Received.Now send file name and location to store. using /put command")
else:
reply = "Invalid Input."
update.message.reply_text(reply)
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def add_user(bot, update):
admin = update.message.from_user.username
if admin == username_list[0]:
username = update.message.text.split(" ")[-1]
username_list.append(username)
update.message.reply_text("User added.")
else:
update.message.reply_text("You are not Authorized.")
def show_user(bot, update):
admin = update.message.from_user.username
if admin == username_list[0]:
update.message.reply_text(username_list)
else:
update.message.reply_text("You are not Authorized.")
def remove_user(bot, update):
admin = update.message.from_user.username
if admin == username_list[0]:
username = update.message.text.split(" ")[-1]
username_list.remove(username)
update.message.reply_text("User Removed.")
else:
update.message.reply_text("You are not Authorized.")
def remove(bot, update):
admin = update.message.from_user.username
if admin == username_list[0]:
filename = update.message.text.split(" ")[-1]
os.remove(os.getcwd()+ "/" + filename)
update.message.reply_text("File Removed.")
else:
update.message.reply_text("You are not Authorized.")
def rmdir(bot, update):
admin = update.message.from_user.username
if admin == username_list[0]:
filename = update.message.text.split(" ")[-1]
shutil.rmtree(os.getcwd()+ "/" + filename)
update.message.reply_text("Folder Removed.")
else:
update.message.reply_text("You are not Authorized.")
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
TOKEN = os.environ['TOKEN']
updater = Updater(TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("get", get))
dp.add_handler(CommandHandler("ls", ls))
dp.add_handler(CommandHandler("put", put))
dp.add_handler(CommandHandler("mkdir", mkdir))
#admin functionalities
dp.add_handler(CommandHandler("adduser", add_user))
dp.add_handler(CommandHandler("showuser", show_user))
dp.add_handler(CommandHandler("removeUser", remove_user))
dp.add_handler(CommandHandler("remove", remove))
dp.add_handler(CommandHandler("rmdir", rmdir))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.document, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
#create a list of telegram usernames to authorise them, 0th username is admin.
username_list = []
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
"""Send a message when the command /start is issued."""
reply = "Welcome to World of Automation. \nI am a bot developed by a Lazy Programmer.\nSend /help command to see what i can do."
update.message.reply_text(reply)
def help(bot, update):
"""Send a message when the command /help is issued."""
admin = update.message.from_user.username
if admin == username_list[0]:
reply = '''Send /get folder_name/file_name.extension to receive a file.
\nSend /ls folder_name to show list of files.
\nSend /put folder_name/file_name.extension to upload last sent file.
\nSend /mkdir folder_name to create a Folder.
\nSend /remove folder_name/filename.extension to delete a file.
\nSend /adduser username to give access.
\nSend /removeuser username to revoke access.
\nSend /showuser to show list of users
'''
else:
reply = '''Send /get folder_name/file_name.extension to receive a file.
\nSend /ls folder_name to show list of files.
\nSend /put folder_name/file_name.extension to upload last sent file.
\nSend /mkdir folder_name to create a Folder.
'''
update.message.reply_text(reply)
def get(bot, update):
"""Send requested file."""
username = update.message.from_user.username
if(username not in username_list):
update.message.reply_text("You are not Authorized.")
return
file = update.message.text.split(" ")[-1]
if(file == "/send"):
update.message.reply_text("Invalid File name.")
else:
reply = "Findind and Sending a requested file to you. Hold on..."
update.message.reply_text(reply)
path = os.getcwd()+'/'+file
if (os.path.exists(path)):
bot.send_document(chat_id=update.message.chat_id,document=open(path, 'rb'), timeout = 100)
else:
update.message.reply_text("File not Found.")
def ls(bot, update):
"""Show files in requested directory."""
username = update.message.from_user.username
if(username not in username_list):
update.message.reply_text("You are not Authorized.")
return
file = update.message.text.split(" ")[-1]
if(file == "/show"):
update.message.reply_text("Invalid Directory name.")
else:
reply = "Findind and Sending a list of files to you. Hold on..."
update.message.reply_text(reply)
path = os.getcwd()+'/'+file
if (os.path.exists(path)):
update.message.reply_text(os.listdir(path))
else:
update.message.reply_text("Directory not Found.")
def put(bot, update):
f = open(str(os.getcwd())+"/file", "r")
file_id = f.read()
f.close
if file_id == "":
update.message.reply_text("You didn't upload file.")
else:
new_file = bot.get_file(file_id)
message = update.message.text.split(" ")
path = message[-1]
if len(path) < 1:
update.message.reply_text("Enter Path correctly.")
else:
new_file.download(os.getcwd()+'/'+path)
update.message.reply_text("File Stored.")
def mkdir(bot, update):
message = update.message.text.split(" ")
if len(message) < 1 or message[-1] == "/mkdir":
update.message.reply_text("Invalid Syntax. Refer syntax in help section.")
return
path = os.getcwd() + "/" + message[-1]
os.mkdir(path)
update.message.reply_text("Folder Created.")
def echo(bot, update):
"""Echo the user message."""
if update.message.document:
file_id = update.message.document.file_id
f = open(str(os.getcwd())+"/file", "w")
f.write(file_id)
f.close
update.message.reply_text("Received.Now send file name and location to store. using /put command")
else:
reply = "Invalid Input."
update.message.reply_text(reply)
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def add_user(bot, update):
admin = update.message.from_user.username
if admin == username_list[0]:
username = update.message.text.split(" ")[-1]
username_list.append(username)
update.message.reply_text("User added.")
else:
update.message.reply_text("You are not Authorized.")
def show_user(bot, update):
admin = update.message.from_user.username
if admin == username_list[0]:
update.message.reply_text(username_list)
else:
update.message.reply_text("You are not Authorized.")
def remove_user(bot, update):
admin = update.message.from_user.username
if admin == username_list[0]:
username = update.message.text.split(" ")[-1]
username_list.remove(username)
update.message.reply_text("User Removed.")
else:
update.message.reply_text("You are not Authorized.")
def remove(bot, update):
admin = update.message.from_user.username
if admin == username_list[0]:
filename = update.message.text.split(" ")[-1]
os.remove(os.getcwd()+ "/" + filename)
update.message.reply_text("File Removed.")
else:
update.message.reply_text("You are not Authorized.")
def rmdir(bot, update):
admin = update.message.from_user.username
if admin == username_list[0]:
filename = update.message.text.split(" ")[-1]
shutil.rmtree(os.getcwd()+ "/" + filename)
update.message.reply_text("Folder Removed.")
else:
update.message.reply_text("You are not Authorized.")
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
TOKEN = os.environ['TOKEN']
updater = Updater(TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("get", get))
dp.add_handler(CommandHandler("ls", ls))
dp.add_handler(CommandHandler("put", put))
dp.add_handler(CommandHandler("mkdir", mkdir))
#admin functionalities
dp.add_handler(CommandHandler("adduser", add_user))
dp.add_handler(CommandHandler("showuser", show_user))
dp.add_handler(CommandHandler("removeUser", remove_user))
dp.add_handler(CommandHandler("remove", remove))
dp.add_handler(CommandHandler("rmdir", rmdir))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.document, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()

View File

@ -1 +1 @@
python-telegram-bot==10.1.0
python-telegram-bot==10.1.0

View File

@ -1,9 +1,9 @@
# Github_Bot
A CLI tool to get github user and repository details.
```
>python main.py -f user -l username
>python main.py -f repo -l username reponame
```
![](readme_assets/img.png)
# Github_Bot
A CLI tool to get github user and repository details.
```
>python main.py -f user -l username
>python main.py -f repo -l username reponame
```
![](readme_assets/img.png)

View File

@ -1,12 +1,12 @@
import PIL
from PIL import Image
from tkinter.filedialog import *
file_path=askopenfilenames()
img = PIL.Image.open(file_path)
myHeight,myWidth = img.size
img=img.resize((myHeight,myWidth),PIL.Image.ANTILIAS)
save_path=asksaveasfile()
import PIL
from PIL import Image
from tkinter.filedialog import *
file_path=askopenfilenames()
img = PIL.Image.open(file_path)
myHeight,myWidth = img.size
img=img.resize((myHeight,myWidth),PIL.Image.ANTILIAS)
save_path=asksaveasfile()
img.save(save_path+"_compressed.JPG")

View File

@ -1,20 +1,20 @@
# Keylogger
A script written in Python that logs your input from the keyboard.
### Steps to run this on terminal
- Clone the project.
- Install the dependencies listed in requirements.txt.
- Run `python keylogger.py` in your terminal.
### PS
- You can use Delete key to exit the script.
- You can open log.txt to view your log.
### Author
# Keylogger
A script written in Python that logs your input from the keyboard.
### Steps to run this on terminal
- Clone the project.
- Install the dependencies listed in requirements.txt.
- Run `python keylogger.py` in your terminal.
### PS
- You can use Delete key to exit the script.
- You can open log.txt to view your log.
### Author
**[Preet Mishra](https://www.github.com/preetmishra)**

View File

@ -1,13 +1,13 @@
astroid==2.1.0
autopep8==1.4.3
certifi==2022.12.7
colorama==0.4.1
isort==4.3.4
lazy-object-proxy==1.3.1
mccabe==0.6.1
pycodestyle==2.4.0
pylint==2.2.2
pynput==1.4.4
six==1.12.0
wincertstore==0.2
wrapt==1.10.11
astroid==2.1.0
autopep8==1.4.3
certifi==2022.12.7
colorama==0.4.1
isort==4.3.4
lazy-object-proxy==1.3.1
mccabe==0.6.1
pycodestyle==2.4.0
pylint==2.2.2
pynput==1.4.4
six==1.12.0
wincertstore==0.2
wrapt==1.10.11

View File

@ -1,26 +1,26 @@
# Importing the required packages.
import PyPDF2
import pyttsx3
text = None
# Reading a PDF file from your computer by specifying the path and setting the read mode to binary.
pdf_reader = PyPDF2.PdfFileReader(open(r"D:\MyPdf.pdf", "rb"))
# Getting the handle to speaker i.e. creating a reference to pyttsx3.Engine instance.
speaker = pyttsx3.init()
# Splitting the PDF file into pages and reading one at a time.
for page_number in range(pdf_reader.numPages):
text = pdf_reader.getPage(page_number).extractText()
# Generating speech.
speaker.say(text)
speaker.runAndWait()
# Stopping the speaker after the complete audio has been created.
speaker.stop()
# Saving the audiobook to your computer.
engine = pyttsx3.init()
engine.save_to_file(text, r"D:\MyAudio.mp3")
engine.runAndWait()
# Importing the required packages.
import PyPDF2
import pyttsx3
text = None
# Reading a PDF file from your computer by specifying the path and setting the read mode to binary.
pdf_reader = PyPDF2.PdfFileReader(open(r"D:\MyPdf.pdf", "rb"))
# Getting the handle to speaker i.e. creating a reference to pyttsx3.Engine instance.
speaker = pyttsx3.init()
# Splitting the PDF file into pages and reading one at a time.
for page_number in range(pdf_reader.numPages):
text = pdf_reader.getPage(page_number).extractText()
# Generating speech.
speaker.say(text)
speaker.runAndWait()
# Stopping the speaker after the complete audio has been created.
speaker.stop()
# Saving the audiobook to your computer.
engine = pyttsx3.init()
engine.save_to_file(text, r"D:\MyAudio.mp3")
engine.runAndWait()

View File

@ -1,2 +1,2 @@
PyPDF2
PyPDF2
pyttsx3

View File

@ -177,7 +177,7 @@ So far, the following projects have been integrated to this repo:
|[Random_Email_Generator](Random_Email_Generator)|[Shubham Garg](https://github.com/shub-garg)|
|[WiFi Password Viewer](Wifi-Password)|[Sagar Patel](https://github.com/sagar627)|
|[Tambola_Ticket_Generator](Tambola_Ticket_Generator)|[Amandeep_Singh](https://github.com/Synster)|
| [Py_Cleaner](Py_Cleaner) | [Abhishek Dobliyal](https://github.com/Abhishek-Dobliyal)|
|[Py_Cleaner](Py_Cleaner) | [Abhishek Dobliyal](https://github.com/Abhishek-Dobliyal)|
|[Send messages to sqs in parallel](send_sqs_messages_in_parallel)|[Jinam Shah](https://github.com/jinamshah)|
|[Codeforces Checker](codeforcesChecker)|[Jinesh Parakh](https://github.com/jineshparakh)|
|[Github repo creator](https://github.com/hastagAB/Awesome-Python-Scripts/tree/master/Git_repo_creator)|[Harish Tiwari ](https://github.com/optimist2309)|

View File

@ -1,62 +1,62 @@
import random
import string
import csv
import progressbar
'''
Asks user for how many emails they want generated. Must be Integer.
If not an integer, keeps recursively cycling back until it gets an integer.
'''
def getcount():
rownums = input("How many email addresses?: ")
try:
rowint = int(rownums)
return rowint
except ValueError:
print ("Please enter an integer value")
return getcount()
'''
Creates a random string of digits between 1 and 20 characters alphanumeric and adds it to a fake domain and fake extension
Most of these emails are completely bogus (eg - gmail.gov) but will meet formatting requirements for my purposes
'''
def makeEmail():
extensions = ['com','net','org','gov']
domains = ['gmail','yahoo','comcast','verizon','charter','hotmail','outlook','frontier']
winext = extensions[random.randint(0,len(extensions)-1)]
windom = domains[random.randint(0,len(domains)-1)]
acclen = random.randint(1,20)
winacc = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(acclen))
finale = winacc + "@" + windom + "." + winext
return finale
#save count to var
howmany = getcount()
#counter for While loop
counter = 0
#empty array for loop
emailarray = []
#uses counter to figure out how many emails to keep making
print ("Creating email addresses...")
print ("Progress: ")
prebar = progressbar.ProgressBar(maxval=int(howmany))
for i in prebar(range(howmany)):
while counter < howmany:
emailarray.append(str(makeEmail()))
counter = counter+1
prebar.update(i)
print ("Creation completed.")
for i in emailarray:
print(i)
import random
import string
import csv
import progressbar
'''
Asks user for how many emails they want generated. Must be Integer.
If not an integer, keeps recursively cycling back until it gets an integer.
'''
def getcount():
rownums = input("How many email addresses?: ")
try:
rowint = int(rownums)
return rowint
except ValueError:
print ("Please enter an integer value")
return getcount()
'''
Creates a random string of digits between 1 and 20 characters alphanumeric and adds it to a fake domain and fake extension
Most of these emails are completely bogus (eg - gmail.gov) but will meet formatting requirements for my purposes
'''
def makeEmail():
extensions = ['com','net','org','gov']
domains = ['gmail','yahoo','comcast','verizon','charter','hotmail','outlook','frontier']
winext = extensions[random.randint(0,len(extensions)-1)]
windom = domains[random.randint(0,len(domains)-1)]
acclen = random.randint(1,20)
winacc = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(acclen))
finale = winacc + "@" + windom + "." + winext
return finale
#save count to var
howmany = getcount()
#counter for While loop
counter = 0
#empty array for loop
emailarray = []
#uses counter to figure out how many emails to keep making
print ("Creating email addresses...")
print ("Progress: ")
prebar = progressbar.ProgressBar(maxval=int(howmany))
for i in prebar(range(howmany)):
while counter < howmany:
emailarray.append(str(makeEmail()))
counter = counter+1
prebar.update(i)
print ("Creation completed.")
for i in emailarray:
print(i)

View File

@ -1,60 +1,60 @@
import random
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+`~[]{]\|;:,<.>/?'
welcomeMessage = "Welcome to the Password Generator!"
detailsMessage = "This program will generate a secure password using a random arrangement of letters (CAPS ON & caps off), numbers, and punctuations."
creatorMessage = "Created by Professor Renderer on October 3rd, 2018."
print(welcomeMessage + '\n' + detailsMessage + '\n' + creatorMessage + '\n')
exitMessage = 0
passwordGeneratorUsage = 1
passwordGeneratorPrompt = 1
while exitMessage != 1:
while passwordGeneratorUsage == 1:
passwordGeneratorPrompt = 1
passwordNum = input('How many passwords would you like to generate? ')
passwordNum = int(passwordNum)
passwordLength = input('How long will the password(s) be? ')
passwordLength = int(passwordLength)
print('\n')
print('Here are your password(s): \n')
passwordFile = open('Passwords.txt', 'w')
for p in range(passwordNum):
password = ''
for c in range(passwordLength):
password += random.choice(chars)
print(password)
passwordFile.write(password + '\n')
passwordFile.close()
print('\n')
while passwordGeneratorPrompt == 1:
getContinue = input('Do you want to use the Password Generator again? (Y/N)')
print('\n')
if getContinue == "Y" or getContinue == "y":
passwordGeneratorPrompt = 0
print('\n')
elif getContinue == "N" or getContinue == "n":
exitMessage = 1
passwordGeneratorUsage = 0
passwordGeneratorPrompt = 0
else:
print("Please enter 'Y' or 'N.'\n")
print('\n')
print('Thank you for using the Password Generator. Have a nice day!')
import random
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+`~[]{]\|;:,<.>/?'
welcomeMessage = "Welcome to the Password Generator!"
detailsMessage = "This program will generate a secure password using a random arrangement of letters (CAPS ON & caps off), numbers, and punctuations."
creatorMessage = "Created by Professor Renderer on October 3rd, 2018."
print(welcomeMessage + '\n' + detailsMessage + '\n' + creatorMessage + '\n')
exitMessage = 0
passwordGeneratorUsage = 1
passwordGeneratorPrompt = 1
while exitMessage != 1:
while passwordGeneratorUsage == 1:
passwordGeneratorPrompt = 1
passwordNum = input('How many passwords would you like to generate? ')
passwordNum = int(passwordNum)
passwordLength = input('How long will the password(s) be? ')
passwordLength = int(passwordLength)
print('\n')
print('Here are your password(s): \n')
passwordFile = open('Passwords.txt', 'w')
for p in range(passwordNum):
password = ''
for c in range(passwordLength):
password += random.choice(chars)
print(password)
passwordFile.write(password + '\n')
passwordFile.close()
print('\n')
while passwordGeneratorPrompt == 1:
getContinue = input('Do you want to use the Password Generator again? (Y/N)')
print('\n')
if getContinue == "Y" or getContinue == "y":
passwordGeneratorPrompt = 0
print('\n')
elif getContinue == "N" or getContinue == "n":
exitMessage = 1
passwordGeneratorUsage = 0
passwordGeneratorPrompt = 0
else:
print("Please enter 'Y' or 'N.'\n")
print('\n')
print('Thank you for using the Password Generator. Have a nice day!')

View File

@ -1,20 +1,20 @@
AaGhi>]!Tkz0{ik0S)mU<P@%6
E|;>k7wuVdpSIkc:8V{q)e_*N
!+B.C;YJ4+;/_$g>]FK/^vD]X
I[dgz&|>uoh(K:-i;xgE:F!!C
$Ab\ag_?lD57,L]Gf3(]j04aw
nCC&RS7K]]GK(%pDHr,>fyv?[
|VT3$kK5AGir))o9A6+ApR`%X
:<Q/G13@Y2p4<rUz=Qj*^YSvZ
kP3Hk.=\bhjnk]ILD6Ek)MQFH
+wIXDLOl(I[8|NRaBw=J&iT^1
wwly,3z;0X<-6kd>T<0],Kzm]
XVp,+V.ko[c/-C3M22*+p@J3>
zTR_S+lDuRn|MwGIVGFwu]pgH
]p_8k1Z03$8]aJL@o^kY$#(Ez
MGe:td4Ql~cZY&G.]u$IK){(p
/&1>(jI|SEdg*L6$Zz,NfetZp
1dN6clgIgi-EfIYB@cn>#^mix
)cci)3*:0l$lNZ*Upi3ME?-C]
<W2bM,E]PBQW%HE$sW1bwWDe!
J^gQZ4.p%^|e>XC$#Rc*B+/Jr
AaGhi>]!Tkz0{ik0S)mU<P@%6
E|;>k7wuVdpSIkc:8V{q)e_*N
!+B.C;YJ4+;/_$g>]FK/^vD]X
I[dgz&|>uoh(K:-i;xgE:F!!C
$Ab\ag_?lD57,L]Gf3(]j04aw
nCC&RS7K]]GK(%pDHr,>fyv?[
|VT3$kK5AGir))o9A6+ApR`%X
:<Q/G13@Y2p4<rUz=Qj*^YSvZ
kP3Hk.=\bhjnk]ILD6Ek)MQFH
+wIXDLOl(I[8|NRaBw=J&iT^1
wwly,3z;0X<-6kd>T<0],Kzm]
XVp,+V.ko[c/-C3M22*+p@J3>
zTR_S+lDuRn|MwGIVGFwu]pgH
]p_8k1Z03$8]aJL@o^kY$#(Ez
MGe:td4Ql~cZY&G.]u$IK){(p
/&1>(jI|SEdg*L6$Zz,NfetZp
1dN6clgIgi-EfIYB@cn>#^mix
)cci)3*:0l$lNZ*Upi3ME?-C]
<W2bM,E]PBQW%HE$sW1bwWDe!
J^gQZ4.p%^|e>XC$#Rc*B+/Jr

View File

@ -1,29 +1,29 @@
# Programs
## [PasswordGenerator.py](./PasswordGenerator.py)
This program randomly generates a secure password using a mix of letters, both caps on and off, numbers, and punctuation, then outputs the results and saves them as a text document.
## [createPassword.py](./createPassword.py)
This program uses the Python 3 module `secrets` to create a pseudo random password with alphanumeric, numbers, and special characters. The output will be printed into the terminal.
# Requirements
* [PasswordGenerator.py](./PasswordGenerator.py) can use Python 3 and higher or Python 2 and higher
* [createPassword.py](./createPassword.py) can run on python 3.6 or higher or for Python 2 do:
* `cd Random_Password_Generator/` to change directory into this folder.
* Create virtual environment with `virtualvenv env`
* do `source venv/bin/activate` to activate virtual environment.
* do `pip install -r requirements.txt` to install python2-secrets
* **TIP**: to deactivate virtual environment, do `deactivate`.
# Usage
For Windows users:
```bash
$ python PasswordGenerator.py
```
For Mac/Linux/Unix users:
```bash
$ ./PasswordGenerator.py
# Programs
## [PasswordGenerator.py](./PasswordGenerator.py)
This program randomly generates a secure password using a mix of letters, both caps on and off, numbers, and punctuation, then outputs the results and saves them as a text document.
## [createPassword.py](./createPassword.py)
This program uses the Python 3 module `secrets` to create a pseudo random password with alphanumeric, numbers, and special characters. The output will be printed into the terminal.
# Requirements
* [PasswordGenerator.py](./PasswordGenerator.py) can use Python 3 and higher or Python 2 and higher
* [createPassword.py](./createPassword.py) can run on python 3.6 or higher or for Python 2 do:
* `cd Random_Password_Generator/` to change directory into this folder.
* Create virtual environment with `virtualvenv env`
* do `source venv/bin/activate` to activate virtual environment.
* do `pip install -r requirements.txt` to install python2-secrets
* **TIP**: to deactivate virtual environment, do `deactivate`.
# Usage
For Windows users:
```bash
$ python PasswordGenerator.py
```
For Mac/Linux/Unix users:
```bash
$ ./PasswordGenerator.py
```

0
SSH_Host_Adder/ssh_adder Executable file → Normal file
View File

View File

@ -1,3 +1,3 @@
author: Omar Sameh
email: o.s.dr.who@gmail.com
author: Omar Sameh
email: o.s.dr.who@gmail.com
no requirments enjoy!

View File

@ -1,53 +1,53 @@
import random
board = [" "," "," "," "," "," "," "," "," "]
def display_board():
print("")
print("| "+board[0]+" | "+board[1]+" | "+board[2]+" | ")
print("| "+board[3]+" | "+board[4]+" | "+board[5]+" | ")
print("| "+board[6]+" | "+board[7]+" | "+board[8]+" | ")
print("")
def wincheck(mark):
return((board[0]==mark and board[1]== mark and board[2]==mark )or #for row1
(board[3]==mark and board[4]==mark and board[5]==mark )or
(board[6]==mark and board[7]==mark and board[8]==mark )or
(board[0]==mark and board[3]==mark and board[6]== mark )or
(board[1]==mark and board[4]==mark and board[7]==mark )or
(board[2]==mark and board[5]==mark and board[8]==mark )or
(board[0]==mark and board[4]==mark and board[8]==mark )or
(board[2]==mark and board[4]==mark and board[6]==mark ))
def make_turn(turn, pos):
if turn:
letter = "O"
else:
letter = "X"
board[pos-1] = letter
display_board()
turn = random.randint(0, 1)
#display_board()
print("""
board alignment:
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
""")
while True:
if turn:
player = "O"
else:
player = "X"
pos= int(input(player + "'s turn: "))
if board[pos-1] != " ":
print("Taken, choose another")
continue
make_turn(turn, pos)
if wincheck(player):
print(player + " wins!")
break
elif " " not in board:
print("Draw")
break
turn = not turn
print("-" * 20)
input("")
import random
board = [" "," "," "," "," "," "," "," "," "]
def display_board():
print("")
print("| "+board[0]+" | "+board[1]+" | "+board[2]+" | ")
print("| "+board[3]+" | "+board[4]+" | "+board[5]+" | ")
print("| "+board[6]+" | "+board[7]+" | "+board[8]+" | ")
print("")
def wincheck(mark):
return((board[0]==mark and board[1]== mark and board[2]==mark )or #for row1
(board[3]==mark and board[4]==mark and board[5]==mark )or
(board[6]==mark and board[7]==mark and board[8]==mark )or
(board[0]==mark and board[3]==mark and board[6]== mark )or
(board[1]==mark and board[4]==mark and board[7]==mark )or
(board[2]==mark and board[5]==mark and board[8]==mark )or
(board[0]==mark and board[4]==mark and board[8]==mark )or
(board[2]==mark and board[4]==mark and board[6]==mark ))
def make_turn(turn, pos):
if turn:
letter = "O"
else:
letter = "X"
board[pos-1] = letter
display_board()
turn = random.randint(0, 1)
#display_board()
print("""
board alignment:
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
""")
while True:
if turn:
player = "O"
else:
player = "X"
pos= int(input(player + "'s turn: "))
if board[pos-1] != " ":
print("Taken, choose another")
continue
make_turn(turn, pos)
if wincheck(player):
print(player + " wins!")
break
elif " " not in board:
print("Draw")
break
turn = not turn
print("-" * 20)
input("")

View File

@ -1,60 +1,60 @@
import random
def wincheck(board):
score = {
"O": 1,
"X": -1
}
for mark in ["O", "X"]:
if ((board[0]==mark and board[1]== mark and board[2]==mark )or
(board[3]==mark and board[4]==mark and board[5]==mark )or
(board[6]==mark and board[7]==mark and board[8]==mark )or
(board[0]==mark and board[3]==mark and board[6]== mark )or
(board[1]==mark and board[4]==mark and board[7]==mark )or
(board[2]==mark and board[5]==mark and board[8]==mark )or
(board[0]==mark and board[4]==mark and board[8]==mark )or
(board[2]==mark and board[4]==mark and board[6]==mark )):
return score[mark]
if " " not in board:
return 0
depth = [0]
def bestMove(board):
if depth[0] == 1:
return random.choice([i+1 for i in range(len(board)) if board[i] == " "])
best = float("inf")
move = 0
if board.count(" ") in [8, 9] and board[4] == " ":
return 5
for i in range(len(board)):
if board[i] == " ":
board[i] = "X"
Try = findBestMove(board, 1, depth[0])
if Try < best:
best = Try
move = i
board[i] = " "
return move+1
def findBestMove(board, maximizing, depth):
if wincheck(board) is not None:
return wincheck(board)
if depth > 0:
depth -= 1
if maximizing == 1:
best = float("-inf")
for i in range(len(board)):
if board[i] == " ":
board[i] = "O"
Try = findBestMove(board, 0, depth)
board[i] = " "
best = max(best, Try)
return best
if maximizing == 0:
best = float("inf")
for i in range(len(board)):
if board[i] == " ":
board[i] = "X"
Try = findBestMove(board, 1, depth)
board[i] = " "
best = min(best, Try)
return best
else:
return 0
import random
def wincheck(board):
score = {
"O": 1,
"X": -1
}
for mark in ["O", "X"]:
if ((board[0]==mark and board[1]== mark and board[2]==mark )or
(board[3]==mark and board[4]==mark and board[5]==mark )or
(board[6]==mark and board[7]==mark and board[8]==mark )or
(board[0]==mark and board[3]==mark and board[6]== mark )or
(board[1]==mark and board[4]==mark and board[7]==mark )or
(board[2]==mark and board[5]==mark and board[8]==mark )or
(board[0]==mark and board[4]==mark and board[8]==mark )or
(board[2]==mark and board[4]==mark and board[6]==mark )):
return score[mark]
if " " not in board:
return 0
depth = [0]
def bestMove(board):
if depth[0] == 1:
return random.choice([i+1 for i in range(len(board)) if board[i] == " "])
best = float("inf")
move = 0
if board.count(" ") in [8, 9] and board[4] == " ":
return 5
for i in range(len(board)):
if board[i] == " ":
board[i] = "X"
Try = findBestMove(board, 1, depth[0])
if Try < best:
best = Try
move = i
board[i] = " "
return move+1
def findBestMove(board, maximizing, depth):
if wincheck(board) is not None:
return wincheck(board)
if depth > 0:
depth -= 1
if maximizing == 1:
best = float("-inf")
for i in range(len(board)):
if board[i] == " ":
board[i] = "O"
Try = findBestMove(board, 0, depth)
board[i] = " "
best = max(best, Try)
return best
if maximizing == 0:
best = float("inf")
for i in range(len(board)):
if board[i] == " ":
board[i] = "X"
Try = findBestMove(board, 1, depth)
board[i] = " "
best = min(best, Try)
return best
else:
return 0

View File

@ -1,67 +1,67 @@
import random
import TicTacToeAI
depth = int(input(
"""Choose difficulty:
Easy: 1
Medium: 2
Hard: 3
choice: """))
print("""
board alignment:
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
""")
TicTacToeAI.depth[0] = depth
board = [" "," "," "," "," "," "," "," "," "]
def display_board():
print("")
print("| "+board[0]+" | "+board[1]+" | "+board[2]+" | ")
print("| "+board[3]+" | "+board[4]+" | "+board[5]+" | ")
print("| "+board[6]+" | "+board[7]+" | "+board[8]+" | ")
print("")
def wincheck(mark):
return((board[0]==mark and board[1]== mark and board[2]==mark )or #for row1
(board[3]==mark and board[4]==mark and board[5]==mark )or
(board[6]==mark and board[7]==mark and board[8]==mark )or
(board[0]==mark and board[3]==mark and board[6]== mark )or
(board[1]==mark and board[4]==mark and board[7]==mark )or
(board[2]==mark and board[5]==mark and board[8]==mark )or
(board[0]==mark and board[4]==mark and board[8]==mark )or
(board[2]==mark and board[4]==mark and board[6]==mark ))
def make_turn(turn, pos):
if turn:
letter = "O"
else:
letter = "X"
board[pos-1] = letter
display_board()
turn = random.randint(0, 1)
#display_board()
while True:
if turn:
player = "O"
else:
player = "X"
if player == "O":
pos= int(input(player + "'s turn: "))
else:
pos = TicTacToeAI.bestMove(board)
if board[pos-1] != " ":
print("Taken, choose another")
continue
make_turn(turn, pos)
if wincheck(player):
print(player + " wins!")
break
elif " " not in board:
print("Draw")
break
turn = not turn
print("-" * 20)
input("")
import random
import TicTacToeAI
depth = int(input(
"""Choose difficulty:
Easy: 1
Medium: 2
Hard: 3
choice: """))
print("""
board alignment:
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
""")
TicTacToeAI.depth[0] = depth
board = [" "," "," "," "," "," "," "," "," "]
def display_board():
print("")
print("| "+board[0]+" | "+board[1]+" | "+board[2]+" | ")
print("| "+board[3]+" | "+board[4]+" | "+board[5]+" | ")
print("| "+board[6]+" | "+board[7]+" | "+board[8]+" | ")
print("")
def wincheck(mark):
return((board[0]==mark and board[1]== mark and board[2]==mark )or #for row1
(board[3]==mark and board[4]==mark and board[5]==mark )or
(board[6]==mark and board[7]==mark and board[8]==mark )or
(board[0]==mark and board[3]==mark and board[6]== mark )or
(board[1]==mark and board[4]==mark and board[7]==mark )or
(board[2]==mark and board[5]==mark and board[8]==mark )or
(board[0]==mark and board[4]==mark and board[8]==mark )or
(board[2]==mark and board[4]==mark and board[6]==mark ))
def make_turn(turn, pos):
if turn:
letter = "O"
else:
letter = "X"
board[pos-1] = letter
display_board()
turn = random.randint(0, 1)
#display_board()
while True:
if turn:
player = "O"
else:
player = "X"
if player == "O":
pos= int(input(player + "'s turn: "))
else:
pos = TicTacToeAI.bestMove(board)
if board[pos-1] != " ":
print("Taken, choose another")
continue
make_turn(turn, pos)
if wincheck(player):
print(player + " wins!")
break
elif " " not in board:
print("Draw")
break
turn = not turn
print("-" * 20)
input("")

0
To Do Bot/Procfile Executable file → Normal file
View File

0
To Do Bot/README.md Executable file → Normal file
View File

0
To Do Bot/bot.py Executable file → Normal file
View File

0
To Do Bot/dbhelper.py Executable file → Normal file
View File

10
To Do Bot/requirements.txt Executable file → Normal file
View File

@ -1,5 +1,5 @@
python-dateutil==2.6.0
requests
telepot==10.5
urllib3
virtualenv==15.1.0
python-dateutil==2.6.0
requests
telepot==10.5
urllib3
virtualenv==15.1.0

0
To Do Bot/runtime.txt Executable file → Normal file
View File

View File

@ -1,34 +1,34 @@
import argparse
import re
import requests
def run(url: str) -> None:
"""
Detect all the URLs on a given website.
:param url: the url of the website to process
:return:
"""
# Load the website's HTML.
website = requests.get(url)
html = website.text
# Detect the URLs.
URL_REGEX = r"http[s]?://(?:[a-zA-Z#]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
detected_urls = re.findall(URL_REGEX, html)
# Filter invalid URLs.
suffixes = "aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mn|mn|mo|mp|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|nom|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ra|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw".split("|")
detected_urls = [x for x in detected_urls if any("."+suffix in x for suffix in suffixes)]
print("\n".join(detected_urls))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--website",
required=True,
help="URL of a website to detect other URLs on"
)
args = parser.parse_args()
# Detect the URLs.
import argparse
import re
import requests
def run(url: str) -> None:
"""
Detect all the URLs on a given website.
:param url: the url of the website to process
:return:
"""
# Load the website's HTML.
website = requests.get(url)
html = website.text
# Detect the URLs.
URL_REGEX = r"http[s]?://(?:[a-zA-Z#]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
detected_urls = re.findall(URL_REGEX, html)
# Filter invalid URLs.
suffixes = "aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mn|mn|mo|mp|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|nom|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ra|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw".split("|")
detected_urls = [x for x in detected_urls if any("."+suffix in x for suffix in suffixes)]
print("\n".join(detected_urls))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--website",
required=True,
help="URL of a website to detect other URLs on"
)
args = parser.parse_args()
# Detect the URLs.
run(args.website)

View File

@ -1,3 +1,3 @@
argparse
re
argparse
re
requests==2.31.0

View File

@ -1,77 +1,77 @@
import argparse
from nltk.corpus import stopwords
from nltk.probability import FreqDist
from nltk.tokenize import word_tokenize
import re
import string
def preprocess(text: str) -> str:
"""
Pre-process the input text.
- Remove punctuation
- Remove numbers
- Lowercase
:param text: text to pre-process
:return: the pre-processed text
"""
# Lowercase.
text = text.lower()
# Remove numbers.
text = re.sub(r"[0-9]+", "", text)
# Remove punctuation.
text = text.translate(str.maketrans("", "", string.punctuation))
return text
def run(text: str) -> FreqDist:
"""
Count the word frequencies in a text.
The text is pre-processed beforehand to remove uninformative
tokens such as punctuation, numbers, stopwords, and to unify
the same tokens by lowercasing the text.
:param text: text to count the word frequencies in
:return: the word frequencies in the text
"""
# Pre-process the text.
text = preprocess(text)
# Tokenize the text.
tokens = word_tokenize(text)
# Remove stopwords.
stop_words = set(stopwords.words("english"))
tokens = [token for token in tokens if token not in stop_words]
# Count the frequencies.
freq_dist = FreqDist(tokens)
print("Top 10 most frequent words:")
print(freq_dist.most_common(10))
return freq_dist
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--filepath",
"-f",
required=True,
help="path to the text file"
)
args = parser.parse_args()
# Open the text file.
with open(args.filepath, "r") as f:
text = f.read()
# Count the frequencies.
freq_dist = run(text)
freq_dist_str = "\n".join([str(x) for x in freq_dist.most_common(freq_dist.B())])
# Save the result.
old_file_name = args.filepath.split("/")[-1].split(".")[0]
new_file_name = old_file_name + "_freq_dist"
new_filepath = args.filepath.replace(old_file_name, new_file_name)
with open(new_filepath, "w") as f:
f.write(freq_dist_str)
print(f"\nSaved the word frequencies to '{new_filepath}'")
import argparse
from nltk.corpus import stopwords
from nltk.probability import FreqDist
from nltk.tokenize import word_tokenize
import re
import string
def preprocess(text: str) -> str:
"""
Pre-process the input text.
- Remove punctuation
- Remove numbers
- Lowercase
:param text: text to pre-process
:return: the pre-processed text
"""
# Lowercase.
text = text.lower()
# Remove numbers.
text = re.sub(r"[0-9]+", "", text)
# Remove punctuation.
text = text.translate(str.maketrans("", "", string.punctuation))
return text
def run(text: str) -> FreqDist:
"""
Count the word frequencies in a text.
The text is pre-processed beforehand to remove uninformative
tokens such as punctuation, numbers, stopwords, and to unify
the same tokens by lowercasing the text.
:param text: text to count the word frequencies in
:return: the word frequencies in the text
"""
# Pre-process the text.
text = preprocess(text)
# Tokenize the text.
tokens = word_tokenize(text)
# Remove stopwords.
stop_words = set(stopwords.words("english"))
tokens = [token for token in tokens if token not in stop_words]
# Count the frequencies.
freq_dist = FreqDist(tokens)
print("Top 10 most frequent words:")
print(freq_dist.most_common(10))
return freq_dist
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--filepath",
"-f",
required=True,
help="path to the text file"
)
args = parser.parse_args()
# Open the text file.
with open(args.filepath, "r") as f:
text = f.read()
# Count the frequencies.
freq_dist = run(text)
freq_dist_str = "\n".join([str(x) for x in freq_dist.most_common(freq_dist.B())])
# Save the result.
old_file_name = args.filepath.split("/")[-1].split(".")[0]
new_file_name = old_file_name + "_freq_dist"
new_filepath = args.filepath.replace(old_file_name, new_file_name)
with open(new_filepath, "w") as f:
f.write(freq_dist_str)
print(f"\nSaved the word frequencies to '{new_filepath}'")

View File

@ -1,4 +1,4 @@
argparse
nltk==3.4.5
re
argparse
nltk==3.4.5
re
string

View File

@ -1,3 +1,3 @@
Once upon a time, a princess named Snow White lived in a castle with her father, the King, and her stepmother, the Queen. Her father had always said to his daughter that she must be fair to everyone at court. Said he, "People come here to the castle when they have a problem. They need the ruler to make a fair decision. Nothing is more important than to be fair."
Once upon a time, a princess named Snow White lived in a castle with her father, the King, and her stepmother, the Queen. Her father had always said to his daughter that she must be fair to everyone at court. Said he, "People come here to the castle when they have a problem. They need the ruler to make a fair decision. Nothing is more important than to be fair."
The Queen, Snow White's stepmother, knew how much this meant to her husband. At the first chance, she went to her magic mirror. "Mirror, mirror, on the wall," said the Queen. "Who is the fairest of them all?"

View File

@ -1,46 +1,46 @@
`Work log generator`
--------------------
📝 C'est quoi?
===============
Ce simple script python permet de générer un journal de travail au format rst à partir des commits de l'un de vos dépôts.
🔘 Comment l'utiliser?
=======================
Il est nécessaire de commencer par générer un jeton d'accès et de l'entrer dans le premier champ de la fenêtre.
Pour le générer, rendez-vous `ici`_ dans la section "Personal access tokens".
À présent, il est possible de presser sur le bouton de connexion. Dès lors, une liste déroulante affiche les dépôts disponibles.
Après le choix du dépôt, le dernier bouton permet d'ouvrir le log, de le modifier et de le sauvegarder au format rst.
Il est maintenant possible de le convertir en utilisant pandoc ou n'importe quelle autre convertisseur que vous préférez.
Enjoy!
📝 What is this?
================
This simple python script allows you to generate a worklog in rst format based on your repo commits.
🔘 How to use it?
=================
Simply generate a personnal access token and enter it in the first field of the window.
In order to generate this token, go `here`_ under "Personal access tokens".
Then, it is possible to press on the connection button. Since then a dropdown list display the available repositories.
After choosing the repository, the last button allows you to open the log, edit it and save it in rst format.
You can then convert it using pandoc or any other converter you prefer.
Enjoy!
.. _`ici`: https://github.com/settings/tokens
.. _`here`: https://github.com/settings/tokens
`Work log generator`
--------------------
📝 C'est quoi?
===============
Ce simple script python permet de générer un journal de travail au format rst à partir des commits de l'un de vos dépôts.
🔘 Comment l'utiliser?
=======================
Il est nécessaire de commencer par générer un jeton d'accès et de l'entrer dans le premier champ de la fenêtre.
Pour le générer, rendez-vous `ici`_ dans la section "Personal access tokens".
À présent, il est possible de presser sur le bouton de connexion. Dès lors, une liste déroulante affiche les dépôts disponibles.
Après le choix du dépôt, le dernier bouton permet d'ouvrir le log, de le modifier et de le sauvegarder au format rst.
Il est maintenant possible de le convertir en utilisant pandoc ou n'importe quelle autre convertisseur que vous préférez.
Enjoy!
📝 What is this?
================
This simple python script allows you to generate a worklog in rst format based on your repo commits.
🔘 How to use it?
=================
Simply generate a personnal access token and enter it in the first field of the window.
In order to generate this token, go `here`_ under "Personal access tokens".
Then, it is possible to press on the connection button. Since then a dropdown list display the available repositories.
After choosing the repository, the last button allows you to open the log, edit it and save it in rst format.
You can then convert it using pandoc or any other converter you prefer.
Enjoy!
.. _`ici`: https://github.com/settings/tokens
.. _`here`: https://github.com/settings/tokens

0
caesar_cipher/caesar.py Executable file → Normal file
View File

0
git_automation/.my_commands.sh Executable file → Normal file
View File

0
git_automation/README.md Executable file → Normal file
View File

0
git_automation/create.py Executable file → Normal file
View File

0
git_automation/requirements.txt Executable file → Normal file
View File

View File

@ -1,3 +1,3 @@
meeting_id_1
meeting_id_2
meeting_id_3
meeting_id_1
meeting_id_2
meeting_id_3

View File

@ -1,3 +1,3 @@
meeting_time_1
meeting_time_2
meeting_time_3
meeting_time_1
meeting_time_2
meeting_time_3

View File

@ -1,2 +1,2 @@
PyAutoGUI==0.9.53
PyAutoGUI==0.9.53
schedule==1.1.0

View File

@ -1,12 +1,12 @@
# Instagram Video Downloader
### Downlaods all the videos from instagram post. User needs to provide instagram post id as parameter
>> Example
```
python instavideo.py B3NUFfmgRYW
```
>> Example output file
```
B3NUFfmgRYW_0.mp4
# Instagram Video Downloader
### Downlaods all the videos from instagram post. User needs to provide instagram post id as parameter
>> Example
```
python instavideo.py B3NUFfmgRYW
```
>> Example output file
```
B3NUFfmgRYW_0.mp4
```

View File

@ -1,38 +1,38 @@
import urllib.request
import requests
import json
import re
import sys
def download(post_id):
multiple_posts = False
videos = []
data = requests.get("https://instagram.com/p/{}".format(post_id))
if data.status_code == 404:
print("Specified post not found")
sys.exit()
json_data = json.loads(re.findall(r'window._sharedData\s=\s(\{.*\});</script>', data.text)[0])
data = json_data['entry_data']['PostPage'][0]['graphql']['shortcode_media']
if 'edge_sidecar_to_children' in data.keys():
multiple_posts = True
caption = data['edge_media_to_caption']['edges'][0]['node']['text']
media_url = data['display_resources'][2]['src']
is_video = data['is_video']
if not is_video and not multiple_posts:
print("No Videos found")
sys.exit()
if is_video:
videos.append(data['video_url'])
if multiple_posts:
for post in data['edge_sidecar_to_children']['edges']:
if post['node']['is_video']:
videos.append(post['node']['video_url'])
print("Found total {} videos".format(len(videos)))
for no, video in zip(list(range(len(videos))), videos):
print("Downloading video {}".format(no))
urllib.request.urlretrieve(video, "{}_{}.mp4".format(post_id, no))
if len(sys.argv) == 1:
print("Please provide instagram post id")
else:
import urllib.request
import requests
import json
import re
import sys
def download(post_id):
multiple_posts = False
videos = []
data = requests.get("https://instagram.com/p/{}".format(post_id))
if data.status_code == 404:
print("Specified post not found")
sys.exit()
json_data = json.loads(re.findall(r'window._sharedData\s=\s(\{.*\});</script>', data.text)[0])
data = json_data['entry_data']['PostPage'][0]['graphql']['shortcode_media']
if 'edge_sidecar_to_children' in data.keys():
multiple_posts = True
caption = data['edge_media_to_caption']['edges'][0]['node']['text']
media_url = data['display_resources'][2]['src']
is_video = data['is_video']
if not is_video and not multiple_posts:
print("No Videos found")
sys.exit()
if is_video:
videos.append(data['video_url'])
if multiple_posts:
for post in data['edge_sidecar_to_children']['edges']:
if post['node']['is_video']:
videos.append(post['node']['video_url'])
print("Found total {} videos".format(len(videos)))
for no, video in zip(list(range(len(videos))), videos):
print("Downloading video {}".format(no))
urllib.request.urlretrieve(video, "{}_{}.mp4".format(post_id, no))
if len(sys.argv) == 1:
print("Please provide instagram post id")
else:
download(sys.argv[1])

View File

@ -1 +1 @@
requests
requests

0
mailing/gmail_messenger.py Executable file → Normal file
View File

View File

@ -1,2 +1,2 @@
random
random
string

View File

@ -1,24 +1,24 @@
import random
import string
def speak_like_yoda(sentence):
"""
Translate the input sentence into Yoda-speak.
:param sentence: input string
:return: translation to Yoda-speak
"""
sentence = sentence.lower()
for p in string.punctuation.replace("'", ''):
sentence = sentence.replace(p, '')
words = sentence.split()
random.shuffle(words)
new_sent = ' '.join(words)
print()
print('Your Yodenglish sentence:')
print(new_sent.capitalize())
if __name__ == '__main__':
print('Your English sentence:')
sentence = str(input())
speak_like_yoda(sentence)
import random
import string
def speak_like_yoda(sentence):
"""
Translate the input sentence into Yoda-speak.
:param sentence: input string
:return: translation to Yoda-speak
"""
sentence = sentence.lower()
for p in string.punctuation.replace("'", ''):
sentence = sentence.replace(p, '')
words = sentence.split()
random.shuffle(words)
new_sent = ' '.join(words)
print()
print('Your Yodenglish sentence:')
print(new_sent.capitalize())
if __name__ == '__main__':
print('Your English sentence:')
sentence = str(input())
speak_like_yoda(sentence)

0
url_shortener/url_shortener.py Executable file → Normal file
View File