From f3470d45f05093f6dc4566b49bd0dc73371d1456 Mon Sep 17 00:00:00 2001 From: slowy07 Date: Sat, 24 Jul 2021 21:50:07 +0700 Subject: [PATCH] fixing module, code, and code cleanup (reformatted) --- Differentiate_List.py | 22 ++--- .../move_to_directory.py | 65 ++++++------- Password Generator/pass_gen.py | 63 ++++++++----- Pong_game.py | 37 ++++---- WeatherGUI.py | 2 +- diceV2_dynamic.py | 22 +++-- flappyBird_pygame/flappy_bird.py | 92 ++++++++----------- floodfill/floodfill.py | 56 ++++++++--- nDigitNumberCombinations.py | 5 +- recyclebin.py | 23 +++-- 10 files changed, 218 insertions(+), 169 deletions(-) diff --git a/Differentiate_List.py b/Differentiate_List.py index b4cc4a59f7f..1c6dc3b629b 100644 --- a/Differentiate_List.py +++ b/Differentiate_List.py @@ -1,15 +1,15 @@ -#this code gives the numbers of integers, floats, and strings present in the list +# this code gives the numbers of integers, floats, and strings present in the list -a= ['Hello',35,'b',45.5,'world',60] -i=f=s=0 +a = ["Hello", 35, "b", 45.5, "world", 60] +i = f = s = 0 for j in a: - if isinstance(j,int): - i=i+1 - elif isinstance(j,float): - f=f+1 + if isinstance(j, int): + i = i + 1 + elif isinstance(j, float): + f = f + 1 else: - s=s+1 -print('Number of integers are:',i) -print('Number of Floats are:',f) -print("numbers of strings are:",s) + s = s + 1 +print(f"Number of integers are: {i}") +print(f"Number of Floats are: {f}") +print(f"numbers of strings are: {s}") diff --git a/Downloaded Files Organizer/move_to_directory.py b/Downloaded Files Organizer/move_to_directory.py index 586e57ae0a4..6bb0d522959 100644 --- a/Downloaded Files Organizer/move_to_directory.py +++ b/Downloaded Files Organizer/move_to_directory.py @@ -1,55 +1,58 @@ import os -import sys import shutil -ext={"web":"css less scss wasm ", - "audio":"aac aiff ape au flac gsm it m3u m4a mid mod mp3 mpa pls ra s3m sid wav wma xm ", - "code":"c cc class clj cpp cs cxx el go h java lua m m4 php pl po py rb rs swift vb vcxproj xcodeproj xml diff patch html js ", - "slide":"ppt odp ","sheet":"ods xls xlsx csv ics vcf ", - "image":"3dm 3ds max bmp dds gif jpg jpeg png psd xcf tga thm tif tiff ai eps ps svg dwg dxf gpx kml kmz webp ", - "archiv":"7z a apk ar bz2 cab cpio deb dmg egg gz iso jar lha mar pea rar rpm s7z shar tar tbz2 tgz tlz war whl xpi zip zipx xz pak ", - "book":"mobi epub azw1 azw3 azw4 azw6 azw cbr cbz ", - "text":"doc docx ebook log md msg odt org pages pdf rtf rst tex txt wpd wps ", - "exec":"exe msi bin command sh bat crx ","font":"eot otf ttf woff woff2 ", - "video":"3g2 3gp aaf asf avchd avi drc flv m2v m4p m4v mkv mng mov mp2 mp4 mpe mpeg mpg mpv mxf nsv ogg ogv ogm qt rm rmvb roq srt svi vob webm wmv yuv "} - -for key,value in ext.items(): - value = value.split() - ext[key]=value +ext = { + "web": "css less scss wasm ", + "audio": "aac aiff ape au flac gsm it m3u m4a mid mod mp3 mpa pls ra s3m sid wav wma xm ", + "code": "c cc class clj cpp cs cxx el go h java lua m m4 php pl po py rb rs swift vb vcxproj xcodeproj xml diff patch html js ", + "slide": "ppt odp ", + "sheet": "ods xls xlsx csv ics vcf ", + "image": "3dm 3ds max bmp dds gif jpg jpeg png psd xcf tga thm tif tiff ai eps ps svg dwg dxf gpx kml kmz webp ", + "archiv": "7z a apk ar bz2 cab cpio deb dmg egg gz iso jar lha mar pea rar rpm s7z shar tar tbz2 tgz tlz war whl xpi zip zipx xz pak ", + "book": "mobi epub azw1 azw3 azw4 azw6 azw cbr cbz ", + "text": "doc docx ebook log md msg odt org pages pdf rtf rst tex txt wpd wps ", + "exec": "exe msi bin command sh bat crx ", + "font": "eot otf ttf woff woff2 ", + "video": "3g2 3gp aaf asf avchd avi drc flv m2v m4p m4v mkv mng mov mp2 mp4 mpe mpeg mpg mpv mxf nsv ogg ogv ogm qt rm rmvb roq srt svi vob webm wmv yuv ", +} + +for key, value in ext.items(): + value = value.split() + ext[key] = value -def add_to_dir(ex,src_path,path): - file_with_ex=os.path.basename(src_path) - file_without_ex=file_with_ex[:file_with_ex.find(ex)-1] - for cat,extensions in ext.items(): +def add_to_dir(ex, src_path, path): + file_with_ex = os.path.basename(src_path) + file_without_ex = file_with_ex[: file_with_ex.find(ex) - 1] + for cat, extensions in ext.items(): if ex in extensions: os.chdir(path) - dest_path=path+'\\'+cat + dest_path = path + "\\" + cat if cat in os.listdir(): try: - shutil.move(src_path,dest_path) + shutil.move(src_path, dest_path) except shutil.Error: - renamed_file = rename(file_without_ex,ex,dest_path) + renamed_file = rename(file_without_ex, ex, dest_path) os.chdir(path) - os.rename(file_with_ex,renamed_file) + os.rename(file_with_ex, renamed_file) os.chdir(dest_path) - shutil.move(path+'\\'+renamed_file,dest_path) + shutil.move(path + "\\" + renamed_file, dest_path) else: os.mkdir(cat) - try : - shutil.move(src_path,dest_path) + try: + shutil.move(src_path, dest_path) except Exception as e: print(e) if os.path.exists(src_path): os.unlink(src_path) -def rename(search,ex,dest_path): - count=0 +def rename(search, ex, dest_path): + count = 0 os.chdir(dest_path) for filename in os.listdir(): - if filename.find(search,0,len(search)-1): - count=count+1 + if filename.find(search, 0, len(search) - 1): + count = count + 1 - return search+str(count)+'.'+ex + return search + str(count) + "." + ex diff --git a/Password Generator/pass_gen.py b/Password Generator/pass_gen.py index d1c34d60238..298f5931192 100644 --- a/Password Generator/pass_gen.py +++ b/Password Generator/pass_gen.py @@ -1,56 +1,72 @@ import string as str import secrets -import random #this is the module used to generate random numbers on your given range -class PasswordGenerator(): +import random # this is the module used to generate random numbers on your given range + +class PasswordGenerator: @staticmethod - def gen_sequence(conditions): #must have conditions (in a list format), for each member of the list possible_characters - possible_characters=[str.ascii_lowercase, str.ascii_uppercase, str.digits, str.punctuation] - sequence="" + def gen_sequence( + conditions, + ): # must have conditions (in a list format), for each member of the list possible_characters + possible_characters = [ + str.ascii_lowercase, + str.ascii_uppercase, + str.digits, + str.punctuation, + ] + sequence = "" for x in range(len(conditions)): if conditions[x]: - sequence+=possible_characters[x] + sequence += possible_characters[x] else: pass return sequence @staticmethod def gen_password(sequence, passlength=8): - password = ''.join((secrets.choice(sequence) for i in range(passlength))) + password = "".join((secrets.choice(sequence) for i in range(passlength))) return password -class Interface(): - has_characters={ - "lowercase":True, - "uppercase":True, - "digits":True, - "punctuation":True + +class Interface: + has_characters = { + "lowercase": True, + "uppercase": True, + "digits": True, + "punctuation": True, } + @classmethod def change_has_characters(cls, change): try: - cls.has_characters[change] #to check if the specified key exists in the dicitonary - except: - print("Invalid") + cls.has_characters[ + change + ] # to check if the specified key exists in the dicitonary + except Exception as err: + print(f"Invalid \nan Exception: {err}") else: - cls.has_characters[change]= not cls.has_characters[change] #automaticly changres to the oppesite value already there + cls.has_characters[change] = not cls.has_characters[ + change + ] # automaticly changres to the oppesite value already there print(f"{change} is now set to {cls.has_characters[change]}") + @classmethod def show_has_characters(cls): - print(cls.has_characters) # print the output - + print(cls.has_characters) # print the output def generate_password(self, lenght): sequence = PasswordGenerator.gen_sequence(list(self.has_characters.values())) print(PasswordGenerator.gen_password(sequence, lenght)) + def list_to_vertical_string(list): - to_return ="" + to_return = "" for member in list: to_return += f"{member}\n" return to_return -class Run(): + +class Run: def decide_operation(self): user_input = input(": ") try: @@ -62,11 +78,8 @@ def decide_operation(self): finally: print("\n\n") - - def run(self): - menu = \ -f"""Welcome to the PassGen App! + menu = f"""Welcome to the PassGen App! Commands: generate password -> diff --git a/Pong_game.py b/Pong_game.py index 636f2296b01..3c89cc5bddf 100644 --- a/Pong_game.py +++ b/Pong_game.py @@ -81,8 +81,9 @@ sketch.penup() sketch.hideturtle() sketch.goto(0, 260) -sketch.write("Left_player : 0 Right_player: 0", - align="center", font=("Courier", 24, "normal")) +sketch.write( + "Left_player : 0 Right_player: 0", align="center", font=("Courier", 24, "normal") +) # Functions to move paddle vertically @@ -137,30 +138,34 @@ def paddlebdown(): hit_ball.dy *= -1 left_player += 1 sketch.clear() - sketch.write("Left_player : {} Right_player: {}".format( - left_player, right_player), align="center", - font=("Courier", 24, "normal")) + sketch.write( + "Left_player : {} Right_player: {}".format(left_player, right_player), + align="center", + font=("Courier", 24, "normal"), + ) if hit_ball.xcor() < -500: hit_ball.goto(0, 0) hit_ball.dy *= -1 right_player += 1 sketch.clear() - sketch.write("Left_player : {} Right_player: {}".format( - left_player, right_player), align="center", - font=("Courier", 24, "normal")) + sketch.write( + "Left_player : {} Right_player: {}".format(left_player, right_player), + align="center", + font=("Courier", 24, "normal"), + ) # Paddle ball collision - if ((hit_ball.xcor() > 360 and - hit_ball.xcor() < 370) and - (hit_ball.ycor() < right_pad.ycor() + 40 and - hit_ball.ycor() > right_pad.ycor() - 40)): + if (hit_ball.xcor() > 360 and hit_ball.xcor() < 370) and ( + hit_ball.ycor() < right_pad.ycor() + 40 + and hit_ball.ycor() > right_pad.ycor() - 40 + ): hit_ball.setx(360) hit_ball.dx *= -1 - if ((hit_ball.xcor() < -360 and - hit_ball.xcor() > -370) and - (hit_ball.ycor() < left_pad.ycor() + 40 and - hit_ball.ycor() > left_pad.ycor() - 40)): + if (hit_ball.xcor() < -360 and hit_ball.xcor() > -370) and ( + hit_ball.ycor() < left_pad.ycor() + 40 + and hit_ball.ycor() > left_pad.ycor() - 40 + ): hit_ball.setx(-360) hit_ball.dx *= -1 diff --git a/WeatherGUI.py b/WeatherGUI.py index d21f099b151..41ea61c8981 100644 --- a/WeatherGUI.py +++ b/WeatherGUI.py @@ -17,7 +17,7 @@ def getWeather(): airqualitytitle = soup.find('span',class_='_1VMr2').text sunrise = soup.find('div',class_='_2ATeV').text sunset = soup.find('div',class_='_2_gJb _2ATeV').text - humidity = soup.find('div',class_='_23DP5').text + # humidity = soup.find('div',class_='_23DP5').text wind = soup.find('span',class_='_1Va1P undefined').text pressure = soup.find('span',class_='_3olKd undefined').text locationlabel.config(text=(location)) diff --git a/diceV2_dynamic.py b/diceV2_dynamic.py index 99d07b5025e..a0dcbcfbc61 100644 --- a/diceV2_dynamic.py +++ b/diceV2_dynamic.py @@ -10,8 +10,10 @@ def setSides(self, sides): if sides > 3: self.sides = sides else: - print("This absolutely shouldn't ever happen. The programmer sucks or someone " - "has tweaked with code they weren't supposed to touch!") + print( + "This absolutely shouldn't ever happen. The programmer sucks or someone " + "has tweaked with code they weren't supposed to touch!" + ) def roll(self): return random.randint(1, self.sides) @@ -25,12 +27,14 @@ def roll(self): def checkInput(sides): try: if int(sides) != 0: - if float(sides) % int(sides) == 0: # excludes the possibility of inputted floats being rounded. + if ( + float(sides) % int(sides) == 0 + ): # excludes the possibility of inputted floats being rounded. return int(sides) else: return int(sides) - except: + except ValueError: print("Invalid input!") return None @@ -58,7 +62,9 @@ def getDices(): diceLowerLimit = 1 # Do Not Touch! sides = pickNumber(sides, "How many sides will the dices have?: ", sideLowerLimit) - diceAmount = pickNumber(diceAmount, "How many dices will do you want?: ", diceLowerLimit) + diceAmount = pickNumber( + diceAmount, "How many dices will do you want?: ", diceLowerLimit + ) for i in range(0, diceAmount): d = Dice() @@ -71,6 +77,7 @@ def getDices(): # ================================================================= # Output section. + def output(): dices = getDices() input("Do you wanna roll? press enter") @@ -83,9 +90,10 @@ def output(): print(rollOutput) print("do you want to roll again?") - ans = input('press enter to continue, and [exit] to exit') - if ans == 'exit': + ans = input("press enter to continue, and [exit] to exit") + if ans == "exit": cont = False + if __name__ == "__main__": output() diff --git a/flappyBird_pygame/flappy_bird.py b/flappyBird_pygame/flappy_bird.py index 34b3206b7e2..568bf8bc2f5 100644 --- a/flappyBird_pygame/flappy_bird.py +++ b/flappyBird_pygame/flappy_bird.py @@ -17,17 +17,17 @@ FPS = 60 ANI_SPEED = 0.18 # pixels per millisecond -W_WIDTH = 284 * 2 # BG image size: 284x512 px; tiled twice +W_WIDTH = 284 * 2 # BG image size: 284x512 px; tiled twice W_HEIGHT = 512 class Bird(pygame.sprite.Sprite): - WIDTH = 32 # bird image width - HEIGHT = 32 # bird image height - DOWN_SPEED = 0.18 # pix per ms -y - UP_SPEED = 0.3 # pix per ms +y - UP_DURATION = 150 # time for which bird go up + WIDTH = 32 # bird image width + HEIGHT = 32 # bird image height + DOWN_SPEED = 0.18 # pix per ms -y + UP_SPEED = 0.3 # pix per ms +y + UP_DURATION = 150 # time for which bird go up def __init__(self, x, y, ms_to_up, images): @@ -41,12 +41,9 @@ def __init__(self, x, y, ms_to_up, images): def update(self, delta_frames=1): if self.ms_to_up > 0: - frac_climb_done = 1 - self.ms_to_up / Bird.UP_DURATION - self.y -= ( - Bird.UP_SPEED - * frames_to_msec(delta_frames) - * (1 - math.cos(frac_climb_done * math.pi)) - ) + frac_climb_done = 1 - self.ms_to_up/Bird.UP_DURATION + self.y -= (Bird.UP_SPEED * frames_to_msec(delta_frames) * + (1 - math.cos(frac_climb_done * math.pi))) self.ms_to_up -= frames_to_msec(delta_frames) else: self.y += Bird.DOWN_SPEED * frames_to_msec(delta_frames) @@ -75,7 +72,7 @@ def rect(self): class PipePair(pygame.sprite.Sprite): - WIDTH = 80 # width of pipe + WIDTH = 80 # width of pipe PIECE_HEIGHT = 32 ADD_INTERVAL = 3000 @@ -85,22 +82,20 @@ def __init__(self, pipe_end_img, pipe_body_img): self.score_counted = False self.image = pygame.Surface((PipePair.WIDTH, W_HEIGHT), SRCALPHA) - self.image.convert() # speeds up blitting + self.image.convert() # speeds up blitting self.image.fill((0, 0, 0, 0)) total_pipe_body_pieces = int( - ( - W_HEIGHT - - 3 * Bird.HEIGHT # fill window from top to bottom - - 3 * PipePair.PIECE_HEIGHT # make room for bird to fit through - ) - / PipePair.PIECE_HEIGHT # 2 end pieces + 1 body piece # to get number of pipe pieces + (W_HEIGHT - # fill window from top to bottom + 3 * Bird.HEIGHT - # make room for bird to fit through + 3 * PipePair.PIECE_HEIGHT) / # 2 end pieces + 1 body piece + PipePair.PIECE_HEIGHT # to get number of pipe pieces ) self.bottom_pieces = randint(1, total_pipe_body_pieces) self.top_pieces = total_pipe_body_pieces - self.bottom_pieces # bottom pipe for i in range(1, self.bottom_pieces + 1): - piece_pos = (0, W_HEIGHT - i * PipePair.PIECE_HEIGHT) + piece_pos = (0, W_HEIGHT - i*PipePair.PIECE_HEIGHT) self.image.blit(pipe_body_img, piece_pos) bottom_pipe_end_y = W_HEIGHT - self.bottom_height_px bottom_end_piece_pos = (0, bottom_pipe_end_y - PipePair.PIECE_HEIGHT) @@ -149,22 +144,22 @@ def collides_with(self, bird): def load_images(): + + def load_image(img_file_name): - file_name = os.path.join(".", "images", img_file_name) + file_name = os.path.join('.', 'images', img_file_name) img = pygame.image.load(file_name) img.convert() return img - return { - "background": load_image("background.png"), - "pipe-end": load_image("pipe_end.png"), - "pipe-body": load_image("pipe_body.png"), - # images for animating the flapping bird -- animated GIFs are - # not supported in pygame - "bird-wingup": load_image("bird_wing_up.png"), - "bird-wingdown": load_image("bird_wing_down.png"), - } + return {'background': load_image('background.png'), + 'pipe-end': load_image('pipe_end.png'), + 'pipe-body': load_image('pipe_body.png'), + # images for animating the flapping bird -- animated GIFs are + # not supported in pygame + 'bird-wingup': load_image('bird_wing_up.png'), + 'bird-wingdown': load_image('bird_wing_down.png')} def frames_to_msec(frames, fps=FPS): @@ -175,13 +170,11 @@ def frames_to_msec(frames, fps=FPS): def msec_to_frames(milliseconds, fps=FPS): return fps * milliseconds / 1000.0 - - -""" +''' def gameover(display, score): font = pygame.font.SysFont(None,55) text = font.render("Game Over! Score: {}".format(score),True,(255,0,0)) - display.blit(text, [150,250])""" + display.blit(text, [150,250])''' def main(): @@ -189,7 +182,7 @@ def main(): pygame.init() display_surface = pygame.display.set_mode((W_WIDTH, W_HEIGHT)) - pygame.display.set_caption("Flappy Bird by PMN") + pygame.display.set_caption('Flappy Bird by PMN') clock = pygame.time.Clock() score_font = pygame.font.SysFont(None, 32, bold=True) # default font @@ -197,12 +190,8 @@ def main(): # the bird stays in the same x position, so bird.x is a constant # center bird on screen - bird = Bird( - 50, - int(W_HEIGHT / 2 - Bird.HEIGHT / 2), - 2, - (images["bird-wingup"], images["bird-wingdown"]), - ) + bird = Bird(50, int(W_HEIGHT/2 - Bird.HEIGHT/2), 2, + (images['bird-wingup'], images['bird-wingdown'])) pipes = deque() @@ -215,7 +204,7 @@ def main(): # Handle this 'manually'. If we used pygame.time.set_timer(), # pipe addition would be messed up when paused. if not (paused or frame_clock % msec_to_frames(PipePair.ADD_INTERVAL)): - pp = PipePair(images["pipe-end"], images["pipe-body"]) + pp = PipePair(images['pipe-end'], images['pipe-body']) pipes.append(pp) for e in pygame.event.get(): @@ -224,9 +213,8 @@ def main(): break elif e.type == KEYUP and e.key in (K_PAUSE, K_p): paused = not paused - elif e.type == MOUSEBUTTONUP or ( - e.type == KEYUP and e.key in (K_UP, K_RETURN, K_SPACE) - ): + elif e.type == MOUSEBUTTONUP or (e.type == KEYUP and + e.key in (K_UP, K_RETURN, K_SPACE)): bird.ms_to_up = Bird.UP_DURATION if paused: @@ -238,7 +226,7 @@ def main(): done = True for x in (0, W_WIDTH / 2): - display_surface.blit(images["background"], (x, 0)) + display_surface.blit(images['background'], (x, 0)) while pipes and not pipes[0].visible: pipes.popleft() @@ -257,19 +245,19 @@ def main(): p.score_counted = True score_surface = score_font.render(str(score), True, (255, 255, 255)) - score_x = W_WIDTH / 2 - score_surface.get_width() / 2 + score_x = W_WIDTH/2 - score_surface.get_width()/2 display_surface.blit(score_surface, (score_x, PipePair.PIECE_HEIGHT)) pygame.display.flip() frame_clock += 1 - # gameover(display_surface, score) + #gameover(display_surface, score) - print("Game over! Score: %i" % score) + print('Game over! Score: %i' % score) pygame.quit() -if __name__ == "__main__": +if __name__ == '__main__': # If this module had been imported, __name__ would be 'flappybird'. # It was executed (e.g. by double-clicking the file), so call main. - main() + main() \ No newline at end of file diff --git a/floodfill/floodfill.py b/floodfill/floodfill.py index dccb75e1de8..b4c39735f23 100644 --- a/floodfill/floodfill.py +++ b/floodfill/floodfill.py @@ -1,10 +1,11 @@ import pygame -''' +""" Visualises how a floodfill algorithm runs and work using pygame Pass two int arguments for the window width and the window height `python floodfill.py ` -''' +""" + class FloodFill: def __init__(self, window_width, window_height): @@ -17,16 +18,17 @@ def __init__(self, window_width, window_height): self.surface = pygame.Surface(self.display.get_size()) self.surface.fill((0, 0, 0)) - self.generateClosedPolygons() # for visualisation purposes + self.generateClosedPolygons() # for visualisation purposes self.queue = [] def generateClosedPolygons(self): if self.window_height < 128 or self.window_width < 128: - return # surface too small + return # surface too small from random import randint, uniform from math import pi, sin, cos + for n in range(0, randint(0, 5)): x = randint(50, self.window_width - 50) y = randint(50, self.window_height - 50) @@ -37,13 +39,19 @@ def generateClosedPolygons(self): for i in range(0, randint(3, 7)): dist = randint(10, 50) - vertices.append((int(x + cos(angle) * dist), int(y + sin(angle) * dist))) - angle += uniform(0, pi/2) + vertices.append( + (int(x + cos(angle) * dist), int(y + sin(angle) * dist)) + ) + angle += uniform(0, pi / 2) for i in range(0, len(vertices) - 1): - pygame.draw.line(self.surface, (255, 0, 0), vertices[i], vertices[i + 1]) + pygame.draw.line( + self.surface, (255, 0, 0), vertices[i], vertices[i + 1] + ) - pygame.draw.line(self.surface, (255, 0, 0), vertices[len(vertices) - 1], vertices[0]) + pygame.draw.line( + self.surface, (255, 0, 0), vertices[len(vertices) - 1], vertices[0] + ) def run(self): looping = True @@ -53,7 +61,7 @@ def run(self): if ev.type == pygame.QUIT: looping = False else: - evsforturn.append(ev) # TODO: Maybe extend with more events + evsforturn.append(ev) # TODO: Maybe extend with more events self.update(evsforturn) self.display.blit(self.surface, (0, 0)) pygame.display.flip() @@ -82,15 +90,31 @@ def update(self, events): top = (point[0], point[1] + 1) bottom = (point[0], point[1] - 1) - if self.inBounds(left) and left not in self.queue and pixArr[left[0], left[1]] == self.surface.map_rgb((0, 0, 0)): + if ( + self.inBounds(left) + and left not in self.queue + and pixArr[left[0], left[1]] == self.surface.map_rgb((0, 0, 0)) + ): self.queue.append(left) - if self.inBounds(right) and right not in self.queue and pixArr[right[0], right[1]] == self.surface.map_rgb((0, 0, 0)): + if ( + self.inBounds(right) + and right not in self.queue + and pixArr[right[0], right[1]] == self.surface.map_rgb((0, 0, 0)) + ): self.queue.append(right) - if self.inBounds(top) and top not in self.queue and pixArr[top[0], top[1]] == self.surface.map_rgb((0, 0, 0)): + if ( + self.inBounds(top) + and top not in self.queue + and pixArr[top[0], top[1]] == self.surface.map_rgb((0, 0, 0)) + ): self.queue.append(top) - if self.inBounds(bottom) and bottom not in self.queue and pixArr[bottom[0], bottom[1]] == self.surface.map_rgb((0, 0, 0)): + if ( + self.inBounds(bottom) + and bottom not in self.queue + and pixArr[bottom[0], bottom[1]] == self.surface.map_rgb((0, 0, 0)) + ): self.queue.append(bottom) - + del pixArr def inBounds(self, coord): @@ -100,7 +124,9 @@ def inBounds(self, coord): return False return True + if __name__ == "__main__": import sys + floodfill = FloodFill(sys.argv[1], sys.argv[2]) - floodfill.run() \ No newline at end of file + floodfill.run() diff --git a/nDigitNumberCombinations.py b/nDigitNumberCombinations.py index e34752f1bb3..caad36e5e8d 100644 --- a/nDigitNumberCombinations.py +++ b/nDigitNumberCombinations.py @@ -6,10 +6,11 @@ def nDigitCombinations(n): for code in range(npow): code = str(code).zfill(n) numbers.append(code) - except: + except Exception: # handle all other exceptions pass - return (numbers) + return numbers + # An alternate solution: # from itertools import product diff --git a/recyclebin.py b/recyclebin.py index 9627a2dc90a..83222be716e 100644 --- a/recyclebin.py +++ b/recyclebin.py @@ -16,16 +16,19 @@ def sid2user(sid): # Start of the function to gather the user try: - key = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + '\\' + sid) - (value, type) = QueryValueEx(key, 'ProfileImagePath') - user = value.split('\\')[-1] + key = OpenKey( + HKEY_LOCAL_MACHINE, + "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + "\\" + sid, + ) + (value, type) = QueryValueEx(key, "ProfileImagePath") + user = value.split("\\")[-1] return user - except: + except Exception: return sid def returnDir(): # Start of the function to search through the recyclebin - dirs = ['c:\\Recycler\\', 'C:\\Recycled\\', 'C:\\$RECYCLE.BIN\\'] + dirs = ["c:\\Recycler\\", "C:\\Recycled\\", "C:\\$RECYCLE.BIN\\"] # dirs=['c:\\$RECYCLE.BIN\\'] for recycleDir in dirs: if os.path.isdir(recycleDir): @@ -33,15 +36,17 @@ def returnDir(): # Start of the function to search through the recyclebin return None -def findRecycled(recycleDir): # Start of the function, list the contents of the recyclebin +def findRecycled( + recycleDir, +): # Start of the function, list the contents of the recyclebin dirList = os.listdir(recycleDir) for sid in dirList: files = os.listdir(recycleDir + sid) user = sid2user(sid) - print('\n[*] Listing Files for User: ' + str(user)) + print("\n[*] Listing Files for User: " + str(user)) for file in files: - print('[+] Found File: ' + str(file)) + print("[+] Found File: " + str(file)) def main(): @@ -49,5 +54,5 @@ def main(): findRecycled(recycleDir) -if __name__ == '__main__': +if __name__ == "__main__": main()