Пример #1
0
def getREPODATA(username, reponame):
    spinner = Spinner()
    spinner.start()
    print(Fore.YELLOW + Style.BRIGHT + "Getting information about repo ",
          end='')
    print(Fore.RED + Style.BRIGHT + reponame)
    url = API_URL + 'repos/' + username + '/' + reponame
    response = requests.get(url)
    if (response.status_code == 200):
        print(Style.BRIGHT + Fore.GREEN + "Successfull...")
    elif (response.status_code == 404):
        print(Style.BRIGHT + Fore.RED + "username or repo not found")
        spinner.stop()
        sys.exit()
    elif (response.status_code == 403):
        print(Style.BRIGHT + Fore.RED +
              "Warning: Maximum Number of Ateempts Limit Crossed")
        spinner.stop()
        sys.exit()

    data = response.json()
    spinner.stop()

    if (data['name']):
        print(Style.BRIGHT + Fore.CYAN + "\nRepository Name: ", end='')
        print(Style.BRIGHT + data['name'])
    if (data['description']):
        print(Style.BRIGHT + Fore.CYAN + "Description: ", end='')
        print(Style.BRIGHT + data['description'])
    if (data['homepage']):
        print(Style.BRIGHT + Fore.CYAN + "Project HomePage: ", end='')
        print(Style.BRIGHT + data['homepage'])
    if (data['html_url']):
        print(Style.BRIGHT + Fore.CYAN + "Github Link: ", end='')
        print(Style.BRIGHT + data['html_url'])
    if ('parent' in data.keys()):
        print()
        print(Style.BRIGHT + Fore.CYAN + "This repo is forked from ", end='')
        print(Style.BRIGHT + data['parent']['owner']['login'])
        print(Style.BRIGHT + Fore.CYAN + "Origial Owner: ", end='')
        print(Style.BRIGHT + data['parent']['owner']['login'])
        print(Style.BRIGHT + Fore.CYAN + "Original Github Link: ", end='')
        print(Style.BRIGHT + data['parent']['html_url'])

    headers = [
        "Language", "Watching", "Stars", "Forks", "Issues", "Size (KB)",
        "Default Branch"
    ]
    table = [[
        data['language'], data['subscribers_count'], data['stargazers_count'],
        data['forks_count'], data['open_issues_count'], data['size'],
        data['default_branch']
    ]]
    print(tabulate(table, headers, tablefmt="fancy_grid", numalign='center'))
Пример #2
0
    def remove(self):
        stdout.write("{:<40}".format("Removing Bad Files..."))
        Spinner().start()

        with open('bad_files.txt', 'r') as f:
            for line in f:
                os.system("rm {}".format(line))

        Spinner().stop()
        stdout.write('\b     [Done]')
        stdout.write("\n")
        stdout.flush()
Пример #3
0
def getUSERDATA(username):
    spinner = Spinner()
    spinner.start()
    print(Fore.YELLOW + Style.BRIGHT + "Getting information about user ",
          end='')
    print(Fore.RED + Style.BRIGHT + username)
    url = API_URL + 'users/' + username
    response = requests.get(url)
    if (response.status_code == 200):
        print(Style.BRIGHT + Fore.GREEN + "Successfull...")
    elif (response.status_code == 404):
        print(Style.BRIGHT + Fore.RED + "username not found")
        spinner.stop()
        sys.exit()
    elif (response.status_code == 403):
        print(Style.BRIGHT + Fore.RED +
              "Warning: Maximum Number of Ateempts Limit Crossed")
        spinner.stop()
        sys.exit()

    data = response.json()
    spinner.stop()

    if (data['login']):
        print(Style.BRIGHT + Fore.CYAN + "\nUsername: "******"Name: ", end='')
        print(Style.BRIGHT + data['name'])
    if (data['company']):
        print(Style.BRIGHT + Fore.CYAN + "Company: ", end='')
        print(Style.BRIGHT + data['company'])
    if (data['bio']):
        print(Style.BRIGHT + Fore.CYAN + "Bio: ", end='')
        print(Style.BRIGHT + data['bio'])
    if (data['blog']):
        print(Style.BRIGHT + Fore.CYAN + "Blog: ", end='')
        print(Style.BRIGHT + data['blog'])
    if (data['location']):
        print(Style.BRIGHT + Fore.CYAN + "Location: ", end='')
        print(Style.BRIGHT + data['location'])
    if (data['html_url']):
        print(Style.BRIGHT + Fore.CYAN + "Github Profile: ", end='')
        print(Style.BRIGHT + data['html_url'])

    headers = ["Public Repos", "Public Gists", "Followers", "Following"]
    table = [[
        data['public_repos'], data['public_gists'], data['followers'],
        data['following']
    ]]

    print(tabulate(table, headers, tablefmt="fancy_grid", numalign='center'))
Пример #4
0
    def __init__(self, parent=None):
        cprint("RESETTER-CLI [ALPHA]", 'white', 'on_blue', attrs=['bold', 'underline'])

        self.loop = True
        self.euid = os.geteuid()
        self.os_info = lsb_release.get_lsb_information()
        self.d_env = Settings()
        self.spinner = Spinner()
        self.manifest = self.d_env.manifest
        self.userlist = self.d_env.userlist
        self.user = self.d_env.user
        self.isWritten = False
        self.isDone = False
        self.non_defaults = []
Пример #5
0
    def __init__(self, session, defpath=None):
        self.skin = SpinnerSelectionBox.skin
        Screen.__init__(self, session)
        list = []
        self['text'] = Label(
            'please wait while downloading preview /n Press Ok to exits')
        self.url = 'http://www.tunisia-dreambox.info/e2-addons-manager/Spinners/spinners_collection/enigma2-spinner-elephant_06.05.2011_mipsel2.ipk'
        self['actions'] = ActionMap(['SetupActions'], {
            'ok': self.close,
            'cancel': self.close
        }, -1)
        cursel = 'spinner'
        self.Bilder = []
        if cursel:
            for i in range(64):
                if os.path.isfile(
                        '/usr/share/enigma2/skin_default/%s/wait%d.png' %
                    (cursel, i + 1)):
                    self.Bilder.append(
                        '/usr/share/enigma2/skin_default/%s/wait%d.png' %
                        (cursel, i + 1))

        else:
            self.Bilder = []
        self['text'].setText('Press ok to exit')
        self['bild'] = Spinner(self.Bilder)
Пример #6
0
	def __init__(self, session,defpath=None):
	        self.skin = SpinnerSscreen.skin
		Screen.__init__(self, session)
		#<widget name="bild" position="200,10" zPosition="1" size="300,200" transparent="1" zPosition="2" />
                list=[]
		self["text"] = Label("please wait while downloading preview /n Press Ok to exits")
		self.url="http://www.tunisia-dreambox.info/e2-addons-manager/Spinners/spinners_collection/enigma2-spinner-elephant_06.05.2011_mipsel2.ipk"
	        
						
		self["actions"] = ActionMap(["SetupActions"], 
		{
			"ok": self.close,
			"cancel": self.close,
			#"up": self.up,
			#"down": self.down
		}, -1)
		
		#self.timer = eTimer()
                #self.timer.callback.append(self.downloadspinner)
                #self.timer.start(100, 1)
	        cursel = "spinner"
                
		self.Bilder = []
		if cursel:
			for i in range(64):
				if (os.path.isfile("/usr/share/enigma2/skin_default/%s/wait%d.png"%(cursel,i+1))):
					self.Bilder.append("/usr/share/enigma2/skin_default/%s/wait%d.png"%(cursel,i+1))
		else:
		        self.Bilder = []
                self["text"].setText("Press ok to exit")
                self["bild"] = Spinner(self.Bilder)
        
                	
        
                        
Пример #7
0
class Resize:
    DIRECTORY = [
        './imageset/blue', './imageset/brown', './imageset/green',
        './imageset/grey', './imageset/orange', './imageset/purple',
        './imageset/red', './imageset/yellow'
    ]

    # create spinner instance
    spinner = Spinner()

    def __init__(self):
        stdout.write("{:<40}".format("Resizing Images..."))
        self.spinner.start()
        for x in range(0, len(self.DIRECTORY)):
            working_directory = self.DIRECTORY[x]
            files = os.listdir(working_directory)

            for file in files:
                os.system('mogrify -resize 299x299 {}/{}'.format(
                    working_directory, file))

        self.spinner.stop()
        stdout.write('\b     [Done]')
        stdout.write('\n')
        stdout.flush()
Пример #8
0
    def verify(self):
        stdout.write("{:<40}".format("Checking JPEG files..."))
        Spinner().start()

        for root, subdirs, files in os.walk('./imageset'):
            for file in files:
                if os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg'):
                    filename = os.path.join(root, file)
                    try:
                        img = Image.open('./' + filename)
                        img.verify()
                    except (IOError, SyntaxError) as e:
                        with open('bad_files.txt', 'a') as f:
                            f.write(filename + '\n')

        Spinner().stop()
        stdout.write('\b     [Done]')
        stdout.write("\n")
        stdout.flush()
Пример #9
0
    def __init__(self):
        stdout.write("{:<40}".format("Downloading Imageset..."))
        Spinner().start()
        # pylint: disable=line-too-long
        os.system(
            'wget -qO imageset.zip https://chryseplanitia.nyc3.cdn.digitaloceanspaces.com/colourvision_imageset.zip'
        )
        # pylint: enable=line-too-long
        Spinner().stop()
        stdout.write('\b     [Done]')
        stdout.write("\n")
        stdout.flush()

        stdout.write("{:<40}".format("Extracting Imageset..."))
        Spinner().start()
        os.system('unzip -qq imageset.zip')
        Spinner().stop()
        stdout.write('\b     [Done]')
        stdout.write("\n")
        stdout.flush()
def main():
    """
    Main function

    """

    file_path, download_subs, show_omdb_info = get_args()
    video_file = Video.fromname(file_path)

    # Display the short info
    short_info = short_details(video_file)
    print(short_info)

    # If -i flag is set show the info from the omdb api
    if show_omdb_info is True:
        spinner = Spinner()
        spinner.start()
        omdb_details(video_file.title, video_file.year)
        spinner.stop()

    # If -d flag is set download the best matching subtitles
    if download_subs is True:
        spinner = Spinner()
        spinner.start()
        # Set the cache
        region.configure('dogpile.cache.dbm', arguments={'filename': 'cachefile.dbm'})
        # Download subtitles in serbian and english
        best_subtitles = download_best_subtitles([video_file], {Language('eng'),\
                        Language('srp')}, providers=None)
        spinner.stop()
        print(best_subtitles[video_file])
        best_subtitle_sr = best_subtitles[video_file][0]
        best_subtitle_en = best_subtitles[video_file][1]
        # Save the 2 subtitle files
        save_subtitles(video_file, [best_subtitle_sr])
        save_subtitles(video_file, [best_subtitle_en])
Пример #11
0
    def game(self, screen, background):
        music = pygame.mixer.music
        music.load("files/music.ogg")
        music.play(-1)

        RULES_rect = pygame.Rect(80, 740, 100, 50)
        NEXT_TURN_rect = pygame.Rect(220, 740, 100, 50)
        self.NEXT_TURN = PygButton.PygButton(
            NEXT_TURN_rect, 'Next Turn', (0, 0, 0), (255, 0, 0),
            pygame.font.SysFont("Verdana", 18))
        self.RULES = PygButton.PygButton(RULES_rect, 'Rules', (0, 0, 0),
                                         (255, 0, 0),
                                         pygame.font.SysFont("Verdana", 20))

        self.spinner = Spinner(screen)
        self.dice = Dice(screen, 140, 225)
        self.dice2 = Dice(screen, 140, 285)

        self.ANGLE = 0
        self.SPINS_TILL_DONE = 0
        self.DICE_TILL_DONE = 0
        self.showDiceNum = 0
        self.showDiceNum2 = 1
        self.switchDie = 0

        self.player = Player(screen)
        self.PLAYER_TURN = 0
        self.MOVE_SPEED = 20
        self.movePlayer = False
        self.PLAYER_MOVE_X = 0
        self.PLAYER_MOVE_Y = 0

        picture = Picture(screen)

        n = True

        keep_going = True
        clock = pygame.time.Clock()
        hideRules = True
        muteState = False

        while keep_going:
            clock.tick(20)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    keep_going = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        hideRules = True
                    elif event.key == pygame.K_ESCAPE:
                        keep_going = False
                    elif event.key == pygame.K_q:
                        keep_going = False
                    elif event.key == pygame.K_p:
                        if muteState == False:
                            music.pause()
                            muteState = True
                        else:
                            music.unpause()
                            muteState = False

                if event.type == pygame.MOUSEBUTTONUP:

                    x, y = pygame.mouse.get_pos()
                    #        print (x)
                    #        print (y)

                    spin = self.checkDoSpinner()

                    if spin == False:
                        dice = self.checkDoDice()

                        if dice == False:
                            self.movePlayer = True

                            x, y = pygame.mouse.get_pos()
                            self.PLAYER_MOVE_X = x
                            self.PLAYER_MOVE_Y = y

                    self.distance()

                if 'click' in self.NEXT_TURN.handleEvent(event):

                    self.movePlayer = False

                    if self.PLAYER_TURN == 2:
                        self.PLAYER_TURN = 0
                    else:
                        self.PLAYER_TURN += 1
                #    print ("CLICKED")
                #  if random.randint(0, 1) == 0:

                    picture.newRotatePicture(random.randint(1, 4), True,
                                             self.player)

                if 'click' in self.RULES.handleEvent(event):
                    hideRules = False
                    self.movePlayer = False

            screen.blit(background, (0, 0))

            circus = ("C", "", "R", "C", "U", "S")
            circles = ("C", "", "R", "C", "L", "E", "S")

            if hideRules:
                picture.drawPicture()
                picture.rotatePicture(self.player)
                self.NEXT_TURN.draw(screen)
                self.RULES.draw(screen)
                for i in range(0, 6):
                    Label(screen, circus[i], 80, 50, 230 + i * 80)
                for i in range(0, 7):
                    Label(screen, circles[i], 80, 1100, 200 + i * 80)
                Label(screen, "I", 80, 60, 310)
                Label(screen, "I", 80, 1110, 280)
                Label(screen, "Player 1", 25, 150, 700)
                Label(screen, "Player 2", 25, 950, 70)
                Label(screen, "Player 3", 25, 910, 750)
                self.spinnerAnimation()
                self.diceAnimation()
                self.playerAnimation()

            else:
                Photo(screen, "files/rules.png", 0, 0)

            pygame.display.flip()
Пример #12
0
class Game():
    def game(self, screen, background):
        music = pygame.mixer.music
        music.load("files/music.ogg")
        music.play(-1)

        RULES_rect = pygame.Rect(80, 740, 100, 50)
        NEXT_TURN_rect = pygame.Rect(220, 740, 100, 50)
        self.NEXT_TURN = PygButton.PygButton(
            NEXT_TURN_rect, 'Next Turn', (0, 0, 0), (255, 0, 0),
            pygame.font.SysFont("Verdana", 18))
        self.RULES = PygButton.PygButton(RULES_rect, 'Rules', (0, 0, 0),
                                         (255, 0, 0),
                                         pygame.font.SysFont("Verdana", 20))

        self.spinner = Spinner(screen)
        self.dice = Dice(screen, 140, 225)
        self.dice2 = Dice(screen, 140, 285)

        self.ANGLE = 0
        self.SPINS_TILL_DONE = 0
        self.DICE_TILL_DONE = 0
        self.showDiceNum = 0
        self.showDiceNum2 = 1
        self.switchDie = 0

        self.player = Player(screen)
        self.PLAYER_TURN = 0
        self.MOVE_SPEED = 20
        self.movePlayer = False
        self.PLAYER_MOVE_X = 0
        self.PLAYER_MOVE_Y = 0

        picture = Picture(screen)

        n = True

        keep_going = True
        clock = pygame.time.Clock()
        hideRules = True
        muteState = False

        while keep_going:
            clock.tick(20)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    keep_going = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        hideRules = True
                    elif event.key == pygame.K_ESCAPE:
                        keep_going = False
                    elif event.key == pygame.K_q:
                        keep_going = False
                    elif event.key == pygame.K_p:
                        if muteState == False:
                            music.pause()
                            muteState = True
                        else:
                            music.unpause()
                            muteState = False

                if event.type == pygame.MOUSEBUTTONUP:

                    x, y = pygame.mouse.get_pos()
                    #        print (x)
                    #        print (y)

                    spin = self.checkDoSpinner()

                    if spin == False:
                        dice = self.checkDoDice()

                        if dice == False:
                            self.movePlayer = True

                            x, y = pygame.mouse.get_pos()
                            self.PLAYER_MOVE_X = x
                            self.PLAYER_MOVE_Y = y

                    self.distance()

                if 'click' in self.NEXT_TURN.handleEvent(event):

                    self.movePlayer = False

                    if self.PLAYER_TURN == 2:
                        self.PLAYER_TURN = 0
                    else:
                        self.PLAYER_TURN += 1
                #    print ("CLICKED")
                #  if random.randint(0, 1) == 0:

                    picture.newRotatePicture(random.randint(1, 4), True,
                                             self.player)

                if 'click' in self.RULES.handleEvent(event):
                    hideRules = False
                    self.movePlayer = False

            screen.blit(background, (0, 0))

            circus = ("C", "", "R", "C", "U", "S")
            circles = ("C", "", "R", "C", "L", "E", "S")

            if hideRules:
                picture.drawPicture()
                picture.rotatePicture(self.player)
                self.NEXT_TURN.draw(screen)
                self.RULES.draw(screen)
                for i in range(0, 6):
                    Label(screen, circus[i], 80, 50, 230 + i * 80)
                for i in range(0, 7):
                    Label(screen, circles[i], 80, 1100, 200 + i * 80)
                Label(screen, "I", 80, 60, 310)
                Label(screen, "I", 80, 1110, 280)
                Label(screen, "Player 1", 25, 150, 700)
                Label(screen, "Player 2", 25, 950, 70)
                Label(screen, "Player 3", 25, 910, 750)
                self.spinnerAnimation()
                self.diceAnimation()
                self.playerAnimation()

            else:
                Photo(screen, "files/rules.png", 0, 0)

            pygame.display.flip()
        #music.stop()

    def checkDoSpinner(self):

        x, y = pygame.mouse.get_pos()

        x1 = self.spinner.SPINNER_CIRCLE_RECT.x + (
            self.spinner.SPINNER_CIRCLE_WIDTH / 2)
        y1 = self.spinner.SPINNER_CIRCLE_RECT.y + (
            self.spinner.SPINNER_CIRCLE_HEIGHT / 2)

        distance = math.sqrt(math.pow((x - x1), 2) + math.pow((y - y1), 2))
        #   print "SPinner   ",(distance)
        if distance <= 100:
            self.SPINS_TILL_DONE = random.randint(18, 26)
            return True
        else:
            return False

    def checkDoDice(self):

        x, y = pygame.mouse.get_pos()

        x1 = self.dice.DICE_RECT.x + (self.dice.DICE_WIDTH / 2)
        y1 = self.dice.DICE_RECT.y + (self.dice.DICE_HEIGHT / 2)

        distance = math.sqrt(math.pow((x - x1), 2) + math.pow((y - y1), 2))

        x2 = self.dice2.DICE_RECT.x + (self.dice2.DICE_WIDTH / 2)
        y2 = self.dice2.DICE_RECT.y + (self.dice2.DICE_HEIGHT / 2)

        distance2 = math.sqrt(math.pow((x - x2), 2) + math.pow((y - y2), 2))

        #    print "dice    ",(distance)
        if distance <= 35 or distance2 <= 35:
            self.switchDie = 0
            self.DICE_TILL_DONE = 12
            return True
        else:
            return False

    def spinnerAnimation(self):

        self.spinner.drawCircle()
        self.spinner.drawSpinner(self.ANGLE)

        if self.SPINS_TILL_DONE >= 2:

            num = random.randint(0, 10)

            if num == 0:
                self.SPINS_TILL_DONE -= 2

            self.ANGLE += self.SPINS_TILL_DONE

    def diceAnimation(self):

        self.dice.drawDice(self.showDiceNum)
        self.dice2.drawDice(self.showDiceNum2)

        if self.DICE_TILL_DONE >= 6:

            self.switchDie += 20

            if 60 - self.switchDie <= 0:
                self.switchDie = 0
                self.DICE_TILL_DONE -= 1
                self.showDiceNum = random.randint(0, 5)
                self.showDiceNum2 = random.randint(1, 4)

    def playerAnimation(self):

        self.player.drawPlayers()

        x = self.PLAYER_MOVE_X
        y = self.PLAYER_MOVE_Y

        player_x, player_y = self.player.PLAYER_IMAGE_RECT_LIST[
            self.PLAYER_TURN].center

        distance = math.sqrt(
            math.pow((x - player_x), 2) + math.pow((y - player_y), 2))

        if distance >= 10 and self.movePlayer == True:

            angle = math.atan2(y - player_y, x - player_x)

            new_x = math.cos(angle) * self.MOVE_SPEED
            new_y = math.sin(angle) * self.MOVE_SPEED

            self.player.movePlayer(self.PLAYER_TURN, new_x, new_y)

        else:
            self.movePlayer = False

    def distance(self):
        x, y = pygame.mouse.get_pos()
        distance = math.sqrt(math.pow((600 - x), 2) + math.pow((400 - y), 2))
        #    print ("distance   ",distance)

        new_x = (math.cos(45) * (x - 600)) - (math.sin(45) * (y - 400)) + 600

        new_y = (math.sin(45) * (x - 600)) + (math.cos(45) * (y - 400)) + 400
Пример #13
0
def getALLREPOS(username):
    spinner = Spinner()
    spinner.start()
    print(Fore.YELLOW + Style.BRIGHT +
          "Getting information about all repo of user ",
          end='')
    print(Fore.RED + Style.BRIGHT + username)
    count = 0
    boolean = True
    while boolean:
        url = API_URL_1 + username + '/repos'
        payload = {'type': 'all', 'page': count, 'per_page': 100}

        response = requests.get(url, payload)

        if (response.status_code == 200):
            print(Style.BRIGHT + Fore.GREEN + "Successfull...")
        elif (response.status_code == 404):
            print(Style.BRIGHT + Fore.RED + "username or repo not found")
            spinner.stop()
            sys.exit()
        elif (response.status_code == 403):
            print(Style.BRIGHT + Fore.RED +
                  "Warning: Maximum Number of Ateempts Limit Crossed")
            spinner.stop()
            sys.exit()

        link = response.headers.get('link', None)
        data = response.json()
        spinner.stop()

        for d in data:
            print(d['name'])
        if link is None:
            boolean = False
        count = count + 1

    spinner.stop()
Пример #14
0
class ResetterMenu(object):
    def __init__(self, parent=None):
        cprint("RESETTER-CLI [ALPHA]", 'white', 'on_blue', attrs=['bold', 'underline'])

        self.loop = True
        self.euid = os.geteuid()
        self.os_info = lsb_release.get_lsb_information()
        self.d_env = Settings()
        self.spinner = Spinner()
        self.manifest = self.d_env.manifest
        self.userlist = self.d_env.userlist
        self.user = self.d_env.user
        self.isWritten = False
        self.isDone = False
        self.non_defaults = []

        # self.detectRoot()

    def menu(self):
        while self.loop:  # While loop which will keep going until loop = False
            cprint("1. Automatic Reset", 'white', 'on_blue',  attrs=['bold'])
            cprint("2. Custom Reset", 'white', 'on_blue',  attrs=['bold'])
            cprint("3. Fix broken packages", 'white', 'on_blue',  attrs=['bold'])
            cprint("4. Remove old kernels", 'white', 'on_blue',  attrs=['bold'])
            cprint("5. About",'white', 'on_blue', attrs=['bold'])
            cprint("6. Exit ", 'white', 'on_blue', attrs=['bold'])
            try:
                choice = int(input(colored("Choose an option [1-6]: ", 'blue',
                                               attrs=['bold'])))
                if choice == 1:
                    self.autoReset()

                elif choice == 2:
                    self.customReset()

                elif choice == 3:
                    self.fixBroken()

                elif choice == 4:
                    self.removeOldKernels()
                elif choice == 5:
                    print ("\n\nAlpha dev branch\n\n")

                elif choice == 6:
                    print("Goodbye")
                    self.loop = False
                else:
                    print("")
                    cprint("Invalid Choice", 'white', 'on_red', attrs=['bold'])
                    print("")


            except ValueError:
                print("")
                cprint("Invalid Choice", 'white', 'on_red', attrs=['bold'])
                print("")
    def autoReset(self):
        yes = set(['yes', 'y', ''])
        no = set(['no', 'n'])
        choice = input(colored("This will reset your " + str(self.os_info['DESCRIPTION']) +
                                   " installation to its factory defaults. "
                                   "Local user accounts and all their contents will also be removed. "
                                   "Are you sure you'd like to continue?: ",
                               'yellow')).lower()
        if str(choice).lower() in yes:
            rapps = []
            self.spinner.start()
            self.getMissingPackages()
            if self.lineCount('apps-to-remove') > 0:
                self.getLocalUserList()
                self.findNonDefaultUsers()
                with open('apps-to-remove') as atr:
                    for line in atr:
                        rapps.append(line)
                self.spinner.stop()
                rapps.sort()
                opts = Picker(
                    title='Automatic Reset: All of these packages will be removed',
                    options=rapps,
                    checkall=True,
                    mut=True
                ).getSelected()
                if not opts:
                    print('')
            else:
                print("All removable packages have already been removed, there are no more packages left")
        elif choice.lower() in no:
            pass
        else:
            print("Please respond with 'yes' or 'no'")

    def fixBroken(self):
        proc = subprocess.Popen(['bash', '/usr/lib/resetter/data/scripts/fix-broken.sh'], stderr=subprocess.PIPE,
                                stdout=subprocess.PIPE)
        while True:
            line = proc.stdout.readline()
            if line.decode() != '':
                sys.stdout.write(line.decode())
            else:
                break

    def customReset(self):
        self.spinner.start()
        time.sleep(3)
        self.getMissingPackages()
        rapps = []

        if self.lineCount('apps-to-remove') > 0:
            self.getLocalUserList()
            self.getOldKernels()
            self.getLocalUserList()
            self.findNonDefaultUsers()
            with open('apps-to-remove', 'r') as atr:
                for line in atr:
                    rapps.append(line)
            self.spinner.stop()
            rapps.sort()
            opts = Picker(
                title='Custom Reset: Select packages to remove',
                options=rapps
            ).getSelected()
            if not opts:
                print("")
            else:
                path = 'custom-remove'
                mode = 'a' if self.isWritten else 'w'
                with open(path, mode) as f_out:
                    for item in opts:
                        f_out.write(item)
        else:
            print("All removable packages have already been removed, there are no more packages left")

    def getMissingPackages(self):
        self.getInstalledList()
        self.processManifest()
        try:
            if self.os_info['RELEASE'] == '17.3':
                word = "vivid"
            else:
                word = None
            black_list = (['linux-image', 'linux-headers', 'linux-generic', 'linux-kernel-generic',
                           'openjdk-7-jre', 'grub'])
            with open("apps-to-install", "w") as output, open("installed", "r") as installed, \
                    open(self.manifest, "r") as man:
                diff = set(man).difference(installed)
                for line in diff:
                    if word is not None and word in line:
                        black_list.append(line)
                    if not any(s in line for s in black_list):
                        output.writelines(line)
        except Exception as e:
            print(e.message)

    def save(self):
        self.getInstalledList()
        now = datetime.datetime.now()
        time = '{}{}{}'.format(now.hour, now.minute, now.second)
        name = 'snapshot - {}'.format(time)
        self.copy("installed", name)

    def removeOldKernels(self):
        self.getOldKernels()
        cache = apt.Cache(None)
        cache.open()
        try:
            with open('Kernels') as k:
                for pkg_name in k:
                    pkg = cache[pkg_name.strip()]
                    pkg.mark_delete(True, True)
            cache.commit()
        except subprocess.CalledProcessError as e:
            print(e.output)
        else:
            cache.close()

    def getOldKernels(self):
        try:
            results = subprocess.check_output(['bash', '/usr/lib/resetter-cli/data/scripts/remove-old-kernels.sh'])
            with open("Kernels", "w") as kernels:
                for line in results.splitlines():
                    kernels.writelines(line.decode() + '\n')
        except subprocess.CalledProcessError as e:
            print(e.output)

    def getInstalledList(self):
        try:
            result = subprocess.check_output(['dpkg', '--get-selections'])
            with open('installed', "w") as output:
                for line in result.splitlines():
                    p_line = line.decode().split('\t', 1)[0]
                    output.writelines(p_line + '\n')
        except subprocess.CalledProcessError as e:
            print(e.ouput)

    def processManifest(self):
        try:
            with open(self.manifest) as f, open('processed-manifest', 'w') as output:
                for line in f:
                    line = line.split('\t', 1)[0]
                    if line.endswith('\n'):
                        line = line.strip()
                    output.write(line + '\n')
            self.compareFiles()
        except Exception as e:
            print(e)

    def lineCount(self, file_path):
        x = open(file_path).readlines()
        line_count = len(x)
        return line_count

    def compareFiles(self):
        try:
            black_list = ('linux-image', 'linux-headers', 'linux-generic', 'ca-certificates', 'pyqt4-dev-tools',
                           'python-apt', 'python-aptdaemon', 'python-qt4', 'python-qt4-doc', 'libqt',
                           'pyqt4-dev-tools', 'openjdk', 'python-sip', 'gksu', 'grub', 'python-mechanize',
                           'python-bs4')
            with open('apps-to-remove', 'w') as output, open('installed', 'r') as installed, \
                    open(self.manifest, 'r') as pman:
                diff = set(installed).difference(pman)
                for line in diff:
                    if not any(s in line for s in black_list):
                        output.writelines(line)
        except Exception as e:
           print(e.message)

    def getLocalUserList(self):
        try:
            result = subprocess.check_output(['bash', '/usr/lib/resetter-cli/data/scripts/get-users.sh'])
            black_list = ['root']
            with open('users', 'w') as output:
                for line in result.splitlines():
                    line = line.decode()
                    if not any(s in line for s in black_list):
                        output.writelines(line + '\n')
        except (subprocess.CalledProcessError, Exception) as e:
            print("an error has occured while getting users, please check the log file {}".format(e))

    def findNonDefaultUsers(self):
        try:
            cmd = subprocess.check_output(['bash', '-c', 'compgen -u'])
            black_list = []
            with open(self.userlist, 'r') as userlist, open('users', 'r') as normal_users:
                for user in userlist:
                    black_list.append(user.strip())
                    for n_users in normal_users:
                        black_list.append(n_users.strip())
            with open('non-default-users', 'w') as output:
                for line in cmd.splitlines():
                    line = line.decode()
                    if not any(s in line for s in black_list):
                        self.non_defaults.append(line)
                        output.writelines(line + '\n')
        except (subprocess.CalledProcessError, Exception) as e:
            print("an error has occured while getting non-default users, please check the log file: {}".format(e))