Exemple #1
0
    def asking_categories(self):
        """
        User program : listing categories from Category table and asking for a choice
        """

        all_categories = self.session.query(Category).all()

        print(ansi.clear_screen())
        print(f"\nListe des catégories :\n")
        for category in all_categories:
            print(f"\t {category.id}  {category.name}")

        user_input = input(f"\nVeuillez choisir votre catégorie : ")

        try:
            if int(user_input) in range(1, CONSTANTS.NUMBER_OF_CATEGORIES + 1):
                self._products_in_category(user_input)
            else:
                print(ansi.clear_screen())
                print(
                    f"{CONSTANTS.RED}Entrée invalide. Veuillez choisir un nombre entre 1 et "
                    f"{CONSTANTS.NUMBER_OF_CATEGORIES}.")
                self.asking_categories()
        except ValueError:
            print(ansi.clear_screen())
            print(
                f"{CONSTANTS.RED}Entrée invalide. Veuillez choisir un nombre entre 1 et "
                f"{CONSTANTS.NUMBER_OF_CATEGORIES} : ")
            self.asking_categories()
Exemple #2
0
    def _registering_product(self, initial_product, best_product):
        """
        Registering product in History table
        :param initial_product: product from self._products_in_category
        :param best_product: product from self._best_product
        """

        inp = input(
            f"Voulez-vous enregistrer cette recherche ? 1 pour OUI, 2 pour NON : "
        )

        try:
            if inp == "1":
                self.session.add(
                    History(id_initial_product=initial_product.id,
                            id_new_product=best_product.id,
                            date=datetime.now()))
                self.session.commit()
                print(ansi.clear_screen())
                print(f"\n{CONSTANTS.GREEN}Le résultat a été enregistré.")
                self.menu()
            elif inp == "2":
                print(ansi.clear_screen())
                self.menu()
            else:
                print(ansi.clear_screen())
                print(f"{CONSTANTS.RED}Entrée invalide.")
                self._registering_product(initial_product, best_product)
        except IntegrityError:
            print(ansi.clear_screen())
            print(
                f"\n{CONSTANTS.LIGHT_YELLOW}Cette recherche a déjà été enregistrée. "
                f"Retrouvez-la en tapant 2 dans le menu.")
            self.session.rollback()
            self.menu()
Exemple #3
0
def top():
    """
    CPU和内存监测

    CPU and memory monitoring

    :return: None
    """
    import time
    import math
    import colorama
    from colorama import Style, ansi, Cursor
    from .. import cur_time, dir_char, requirePackage
    from ..TuiTools import Bar
    from ..NetTools.NormalDL import size_format
    psutil = requirePackage('psutil')
    PrettyTable = requirePackage('prettytable', 'PrettyTable')

    def deal():
        print(ansi.clear_screen() + Cursor.POS(0, 0) + Style.RESET_ALL, end='')
        exit(0)

    colorama.init()
    _kernal = psutil.cpu_count()
    _total_mem = psutil.virtual_memory().total
    _cpu_dt = [0] * 40
    _mem_dt = [0] * 40
    _cpu_chart = Bar.RollBar(_cpu_dt, height=10)
    _mem_chart = Bar.RollBar(_mem_dt, height=10)
    charts = [_cpu_chart, _mem_chart]
    window = PrettyTable()
    window.add_row(charts)
    print(ansi.clear_screen())
    try:
        while True:
            _cpu_cur = sum(psutil.cpu_percent(percpu=True)) / _kernal
            _mem_cur = psutil.virtual_memory().used
            _cpu_chart.add(math.ceil(_cpu_cur))
            _mem_chart.add(math.ceil(_mem_cur / _total_mem * 100))
            window.field_names = [
                'CPU: %.2f%%' % _cpu_cur,
                'MEM: %s' % size_format(_mem_cur)
            ]
            print((ansi.clear_screen() if dir_char == '\\' else '') +
                  Cursor.POS(0, 0))
            print(' ' * 39, end='')
            cur_time()
            cur_img = '    '.join(str(window).split('\n') + [' '])
            print(cur_img)
            time.sleep(1)
    except:
        deal()
Exemple #4
0
def loading_sequence(*items):
    click.echo(clear_screen())

    for label, splash in items:
        click.echo(green)

        if label is not None:
            with click.progressbar(label=label, length=10) as bar:
                for i in range(10):
                    bar.update(i)
                    time.sleep(1.0 - (i * 0.1))
            click.echo(clear_screen())
        for line in splash.splitlines():
            click.echo(line)
            time.sleep(0.05)
Exemple #5
0
    def show_history(self):
        """
        Printing all rows from History table in a nice format
        """

        history_list = self.session.query(History).order_by(desc(
            History.date)).all()

        print(ansi.clear_screen())
        for row in history_list:
            initial_product = self.session.query(Product).filter(
                Product.id == row.id_initial_product).first()
            new_product = self.session.query(Product).filter(
                Product.id == row.id_new_product).first()

            print(
                f"\n\tNous vous proposons de remplacer le produit "
                f"'{CONSTANTS.RED}{initial_product.name}'{CONSTANTS.RESET_COLOR} par "
                f"{CONSTANTS.LIGHT_GREEN}'{new_product.name}'.")
            print(
                f"\tPlus d'informations disponibles sur ce produit ici : {new_product.url}"
            )
            print("\t****")

        self.menu()
Exemple #6
0
 def run(self):
     WIN32 = sys.platform == 'win32'
     decode_key = lambda key: key if type(key) == int else int.from_bytes(key.encode(), byteorder='big')
     while True:
         print(clear_screen())
         print(self.menu)
         key = getch()
         if WIN32 and key == b'\xe0':
             arrow = getch()
             if arrow == b'H':    # up
                 self.menu.prev()
             elif arrow == b'P':  # down
                 self.menu.next()
         elif not WIN32 and len(key) > 1:
             if key == b'[A':    # up
                 self.menu.prev()
             elif key == b'[B':  # down
                 self.menu.next()
         elif key == b'\r' or key == b'\n':
             if self.menu.activate():
                 break
         elif key >= b'0' and key <= b'9':
             self.menu.select(key[0] - ord('0'))
             if self.menu.activate():
                 break
         elif key == b'\x1b' or key == b'\x03' or key == b'q':
             break
Exemple #7
0
    def menu(self, first_start=False):
        """
        Main menu of the program
        User can choose between self.asking_categories, self.show_history, self.delete_history or Quit
        :param first_start:  printing opening lines when user opens the program
        """

        if first_start:
            print(
                f"\nBienvenue dans l'application {CONSTANTS.LIGHT_YELLOW}Pur Beurre{CONSTANTS.RESET_COLOR}, "
                f"où vous pourrez substituer des aliments plus sains à vos envies !!"
            )

        print(f"\n\t {CONSTANTS.LIGHT_GREEN}1 Substituer un nouvel aliment.")
        if len(self.session.query(History).all()) != 0:
            print(
                f"\t {CONSTANTS.LIGHT_BLUE}2 Voir vos recherches enregistrées."
            )
            print(f"\t {CONSTANTS.LIGHT_BLUE}E Effacer les recherches.")
        print(f"\t {CONSTANTS.RED}Q Quitter le programme.\n")

        inp = input("Votre choix : ")

        if inp in ["1", "2", "e", "q", "E", "Q"]:
            if inp == "1":
                self.asking_categories()
            elif inp.lower() == "q":
                print(ansi.clear_screen())
                print(
                    f"\nMerci d'avoir utilisé notre programme ! L'équipe {CONSTANTS.LIGHT_YELLOW}Pur Beurre."
                )
            elif len(self.session.query(History).all()) != 0:
                if inp.lower() == "e":
                    self._delete_history()
                    self.menu()
                elif inp == "2":
                    self.show_history()
            else:
                print(ansi.clear_screen())
                print(f"{CONSTANTS.RED}Entrée invalide, veuillez recommencer.")
                self.menu()
        else:
            print(ansi.clear_screen())
            print(f"{CONSTANTS.RED}Entrée invalide, veuillez recommencer.")
            self.menu()
Exemple #8
0
    def _delete_history(self):
        """
        Deleting all rows from History table
        """

        print(ansi.clear_screen())
        print(
            f"\n{CONSTANTS.LIGHT_BLUE}Vos recherches enregistrées ont été effacées !"
        )

        self.session.query(History).delete()
        self.session.commit()
Exemple #9
0
def main():
    parser = argparse.ArgumentParser(
        description="Grayskull - Conda recipe generator")
    parser.add_argument(
        "repo_type",
        nargs=1,
        help="Specify the repository (pypi, cran).",
    )
    parser.add_argument(
        "packages",
        nargs="+",
        help="Specify the packages name.",
    )
    parser.add_argument("--heman",
                        "--shera",
                        default=False,
                        action="store_true",
                        dest="grayskull_power")
    parser.add_argument(
        "--output",
        "-o",
        dest="output",
        default=".",
        help="Path to where the recipe will be created",
    )
    parser.add_argument("--version",
                        "-v",
                        default="",
                        dest="version",
                        help="Package version ")

    args = parser.parse_args()
    logging.debug(f"All arguments received: args: {args}")
    print(Style.RESET_ALL)
    print(clear_screen())
    if args.grayskull_power:
        print(f"{Fore.BLUE}By the power of Grayskull...\n"
              f"{Style.BRIGHT}I have the power!")

    for pkg_name in args.packages:
        logging.debug(f"Starting grayskull for pkg: {pkg_name}")
        print(
            f"{Fore.GREEN}\n\n"
            f"#### Initializing recipe for "
            f"{Fore.BLUE}{pkg_name} ({args.repo_type[0]}) {Fore.GREEN}####\n")
        recipe = GrayskullFactory.create_recipe(args.repo_type[0], pkg_name,
                                                args.version)
        recipe.generate_recipe(args.output)
        print(f"\n{Fore.GREEN}#### Recipe generated on "
              f"{os.path.realpath(args.output)} for {pkg_name} ####\n")
Exemple #10
0
    def _products_in_category(self, category_id):
        """
        User program :  listing 10 products from the chosen category and asking for a choice
        :param category_id:  user input between 1 and NUMBER_OF_CATEGORIES
        """

        distinct_names = self.session.query(Product.name.distinct()).filter(Product.category == category_id)\
                                               .order_by(desc(Product.note)).limit(10)

        products_name = []
        for row in distinct_names:
            products_name.append(*row)

        print(ansi.clear_screen())
        print(f"\nChoisissez l'aliment que vous voulez remplacer : \n")

        for i, name in enumerate(products_name):
            print(f'\t{i + 1}  {name}')

        inp = input("\nVotre choix : ")

        try:
            if int(inp) in range(1, len(products_name) + 1):
                self._best_product(category_id, products_name[int(inp) - 1])
            else:
                print(ansi.clear_screen())
                print(
                    f"Entrée invalide. Choisissez un nombre entre 1 et {len(products_name)}"
                )
                self._products_in_category(category_id)
        except ValueError:
            print(ansi.clear_screen())
            print(
                f"Entrée invalide. Choisissez un nombre entre 1 et {len(products_name)}"
            )
            self._products_in_category(category_id)
Exemple #11
0
def client_id():
    print(ansi.clear_screen())
    if processes.is_running("eurotrucks2.exe"):
        base.km_mil = 0
        base.vehicle_list += config.truckMake("ETS2")
        return config.getID("ETS2", "529016610137309184")

    elif processes.is_running("amtrucks.exe"):
        base.km_mil = 1
        base.vehicle_list += config.truckMake("ATS")
        return config.getID("ATS", "529069002874421249")
    else:
        print(Fore.RED + "No game detected /:\\")
        for i in reversed(range(0, 6)):
            sleep(1)
            print("Checking again in: " + Fore.YELLOW + str(i))
        return client_id()
Exemple #12
0
import time
import socket
import threading
from fake_useragent import UserAgent
from colorama import Fore, init, ansi

init()
ansi.clear_screen()

print(f"""{Fore.CYAN}

██████╗░██████╗░██╗██╗░░░░░███████╗██████╗░
██╔══██╗██╔══██╗██║██║░░░░░██╔════╝██╔══██╗
██████╦╝██████╔╝██║██║░░░░░█████╗░░██████╔╝
██╔══██╗██╔══██╗██║██║░░░░░██╔══╝░░██╔══██╗
██████╦╝██║░░██║██║███████╗███████╗██║░░██║
╚═════╝░╚═╝░░╚═╝╚═╝╚══════╝╚══════╝╚═╝░░╚═╝
-------------------------------------------
██████╗░██████╗░░█████╗░░██████╗
██╔══██╗██╔══██╗██╔══██╗██╔════╝
██║░░██║██║░░██║██║░░██║╚█████╗░
██║░░██║██║░░██║██║░░██║░╚═══██╗
██████╔╝██████╔╝╚█████╔╝██████╔╝
╚═════╝░╚═════╝░░╚════╝░╚═════╝░
    {Fore.YELLOW}NOTE: CTRL + C If you want to Quit.{Fore.RESET}
""")

address = ''
while not address:
    address = input(f'Ip: ')
Exemple #13
0
def tracker():
    global d
    while True:
        try:
            while True:
                if d["data"]["jobData"]["status"] == 0:
                    time.sleep(3)
                    print(ansi.clear_screen())
                    print('No job detected, refreshing...')
                if d["data"]["jobData"]["status"] == 1:
                    print(Fore.GREEN + 'Job found!')
                    break

            while True:
                if d["data"]["jobData"]["status"] == 1:
                    time.sleep(3)
                    print(ansi.clear_screen())
                    print('On job, refreshing...')
                    now = now = datetime.now()
                    current_time = now.strftime("%H:%M:%S")
                    file1 = open('log.txt', 'a')
                    L = "onJob time:" + current_time + "\n"
                    file1.writelines(L)
                    file1.close()
                if d["data"]["jobData"]["status"] == 2:
                    print(Fore.GREEN + 'Job finished! Sending to API...')
                    now = now = datetime.now()
                    current_time = now.strftime("%H:%M:%S")
                    file1 = open('log.txt', 'a')
                    finsihedJobText = "finishedJob time:" + current_time + "\n"
                    file1.writelines(finsihedJobText)
                    file1.close()

                    timetaken = d["data"]["jobData"]["realTimeTaken"]
                    _time = (timetaken / (1000 * 60)) % 60
                    hrs = (timetaken / (1000 * 60 * 60))
                    _timee = floor(_time)
                    _hrs = floor(hrs)
                    distance = d["data"]["jobData"]["distanceDriven"]
                    cargo = d["data"]["jobData"]["cargo"]
                    source = d["data"]["jobData"]["sourceCity"]
                    sourcec = d["data"]["jobData"]["sourceCompany"]
                    destination = d["data"]["jobData"]["destinationCity"]
                    destinationc = d["data"]["jobData"]["destinationCompany"]
                    g = d["data"]["telemetry"]["game"]["isMultiplayer"]
                    if g is True:
                        game = "Multiplayer"
                    else:
                        game = "Singleplayer"
                    mass = d["data"]["jobData"]["trailerMass"]
                    _mass = round(mass)
                    brand = d["data"]["jobData"]["truckMake"]
                    model = d["data"]["jobData"]["truckModel"]
                    fuel = d["data"]["jobData"]["fuelBurned"]
                    consumption = d["data"]["jobData"]["fuelBurned"] * 100 / distance
                    _distance = round(distance, 1)
                    _consumption = round(consumption, 2)
                    _fuel = round(fuel, 0)
                    wr = {"user": user, "name": _name, "cargo": cargo, "source": "{}, {}".format(source, sourcec),
                          "destination": "{}, {}".format(destination, destinationc),
                          "fuel": _fuel, "consumption": _consumption, "Hours": _hrs, "Minutes": _timee,
                          "distance": _distance,
                          "Game": game, "mass": mass, "Truck": "{} {}".format(brand, model)}
                    w = json.dumps(wr)
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    sock.connect(('ip_address', 9999))
                    sock.send(w.encode())
                    sock.close()
                    break

                if d["data"]["jobData"]["status"] == 3:
                    print(Fore.GREEN + 'Job cancelled! Sending to API...')
                    file1 = open('log.txt', 'a')
                    finsihedJobText = "cancelledJob time:" + current_time + "\n"
                    file1.writelines(finsihedJobText)
                    file1.close()
                    timetaken = d["data"]["jobData"]["realTimeTaken"]
                    _time = (timetaken / (1000 * 60)) % 60
                    hrs = (timetaken / (1000 * 60 * 60))
                    _timee = floor(_time)
                    _hrs = floor(hrs)
                    distance = d["data"]["jobData"]["distanceDriven"]
                    cargo = d["data"]["jobData"]["cargo"]
                    source = d["data"]["jobData"]["sourceCity"]
                    sourcec = d["data"]["jobData"]["sourceCompany"]
                    destination = d["data"]["jobData"]["destinationCity"]
                    destinationc = d["data"]["jobData"]["destinationCompany"]
                    g = d["data"]["telemetry"]["game"]["isMultiplayer"]
                    if g is True:
                        game = "Multiplayer"
                    else:
                        game = "Singleplayer"
                    mass = d["data"]["jobData"]["trailerMass"]
                    _mass = round(mass)
                    brand = d["data"]["jobData"]["truckMake"]
                    model = d["data"]["jobData"]["truckModel"]
                    fuel = d["data"]["jobData"]["fuelBurned"]
                    consumption = d["data"]["jobData"]["fuelBurned"] * 100 / distance
                    _distance = round(distance, 1)
                    _consumption = round(consumption, 2)
                    _fuel = round(fuel, 0)
                    wr = {"user": user, "name": _name, "cargo": cargo, "source": "{}, {}".format(source, sourcec),
                          "destination": "{}, {}".format(destination, destinationc),
                          "fuel": _fuel, "consumption": _consumption, "Hours": _hrs, "Minutes": _timee,
                          "distance": _distance,
                          "Game": game, "mass": mass, "Truck": "{} {}".format(brand, model)}
                    w = json.dumps(wr)
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    sock.connect(('ip_address', 9999))
                    sock.send(w.encode())
                    sock.close()
                    break

            while True:
                print(ansi.clear_screen())
                if d["data"]["jobData"]["status"] == 2:
                    print('Waiting for another job...')
                    time.sleep(3)
                if d["data"]["jobData"]["status"] == 3:
                    print('Waiting for another job...')
                    time.sleep(3)
                if d["data"]["jobData"]["status"] == 1:
                    break
        except Exception as _e:
            print(_e)
            break
Exemple #14
0
def clear_screen():
    """Зачистить экран"""
    print(ansi.clear_screen())
Exemple #15
0
def main(args=None):
    if not args:
        args = sys.argv[1:] or ["--help"]

    parser = argparse.ArgumentParser(
        description="Grayskull - Conda recipe generator")
    pypi_parser = parser.add_subparsers(
        help="Options to generate PyPI recipes")
    pypi_cmds = pypi_parser.add_parser("pypi",
                                       help="Generate recipes based on PyPI")
    pypi_cmds.add_argument("pypi_packages",
                           nargs="+",
                           help="Specify the PyPI packages name.",
                           default=[])
    pypi_cmds.add_argument(
        "--download",
        "-d",
        dest="download",
        action="store_true",
        default=False,
        help="Download the sdist package and PyPI information in the same folder"
        " the recipe is located.",
    )
    pypi_cmds.add_argument(
        "--maintainers",
        "-m",
        dest="maintainers",
        nargs="+",
        help="List of maintainers which will be added to the recipe.",
    )
    parser.add_argument(
        "--version",
        "-v",
        default=False,
        action="store_true",
        dest="version",
        help="Print Grayskull version and exit",
    )
    parser.add_argument(
        "--heman",
        "--shera",
        default=False,
        action="store_true",
        dest="grayskull_power",
        help=argparse.SUPPRESS,
    )
    pypi_cmds.add_argument(
        "--output",
        "-o",
        dest="output",
        default=".",
        help="Path to where the recipe will be created",
    )
    pypi_cmds.add_argument(
        "--stdout",
        dest="stdout",
        default=True,
        help="Disable or enable stdout, if it is False, Grayskull"
        " will disable the prints. Default is True",
    )
    pypi_cmds.add_argument(
        "--list-missing-deps",
        default=False,
        action="store_true",
        dest="list_missing_deps",
        help=
        "After the execution Grayskull will print all the missing dependencies.",
    )
    pypi_cmds.add_argument(
        "--strict-conda-forge",
        default=False,
        action="store_true",
        dest="is_strict_conda_forge",
        help="It will generate the recipes strict for the conda-forge channel.",
    )
    pypi_cmds.add_argument(
        "--pypi-url",
        default="https://pypi.org/pypi/",
        dest="url_pypi_metadata",
        help="Pypi url server",
    )
    pypi_cmds.add_argument(
        "--recursive",
        "-r",
        default=False,
        action="store_true",
        dest="is_recursive",
        help="Recursively run grayskull on missing dependencies.",
    )
    pypi_cmds.add_argument(
        "--sections",
        "-s",
        default=None,
        required=False,
        choices=(
            "package",
            "source",
            "build",
            "requirements",
            "test",
            "about",
            "extra",
        ),
        nargs="+",
        dest="sections_populate",
        help=
        "If sections are specified, grayskull will populate just the sections "
        "informed.",
    )
    pypi_cmds.add_argument(
        "--extras-require-test",
        default=None,
        dest="extras_require_test",
        help="Extra requirements to run tests.",
    )

    args = parser.parse_args(args)

    if args.version:
        print(grayskull.__version__)
        return

    logging.debug(f"All arguments received: args: {args}")

    if args.grayskull_power:
        print(f"{Fore.BLUE}By the power of Grayskull...\n"
              f"{Style.BRIGHT}I have the power!")
        return

    CLIConfig().stdout = args.stdout
    CLIConfig().list_missing_deps = args.list_missing_deps

    print_msg(Style.RESET_ALL)
    print_msg(clear_screen())

    generate_recipes_from_list(args.pypi_packages, args)
Exemple #16
0
def main(args=None):
    if not args:
        args = sys.argv[1:] if sys.argv[1:] else ["--help"]

    parser = argparse.ArgumentParser(
        description="Grayskull - Conda recipe generator")
    pypi_parser = parser.add_subparsers(
        help="Options to generate PyPI recipes")
    pypi_cmds = pypi_parser.add_parser("pypi",
                                       help="Generate recipes based on PyPI")
    pypi_cmds.add_argument("pypi_packages",
                           nargs="+",
                           help="Specify the PyPI packages name.",
                           default=[])
    pypi_cmds.add_argument(
        "--download",
        "-d",
        dest="download",
        action="store_true",
        default=False,
        help="Download the sdist package and PyPI information in the same folder"
        " the recipe is located.",
    )
    pypi_cmds.add_argument(
        "--maintainers",
        "-m",
        dest="maintainers",
        nargs="+",
        help="List of maintainers which will be added to the recipe.",
    )
    parser.add_argument(
        "--version",
        "-v",
        default=False,
        action="store_true",
        dest="version",
        help="Print Grayskull version and exit",
    )
    parser.add_argument(
        "--heman",
        "--shera",
        default=False,
        action="store_true",
        dest="grayskull_power",
        help=argparse.SUPPRESS,
    )
    pypi_cmds.add_argument(
        "--output",
        "-o",
        dest="output",
        default=".",
        help="Path to where the recipe will be created",
    )
    pypi_cmds.add_argument(
        "--stdout",
        dest="stdout",
        default=True,
        help="Disable or enable stdout, if it is False, Grayskull"
        " will disable the prints. Default is True",
    )
    pypi_cmds.add_argument(
        "--list-missing-deps",
        default=False,
        action="store_true",
        dest="list_missing_deps",
        help=
        "After the execution Grayskull will print all the missing dependencies.",
    )
    pypi_cmds.add_argument(
        "--strict-conda-forge",
        default=False,
        action="store_true",
        dest="is_strict_conda_forge",
        help="It will generate the recipes strict for the conda-forge channel.",
    )

    args = parser.parse_args(args)

    if args.version:
        print(grayskull.__version__)
        return

    logging.debug(f"All arguments received: args: {args}")

    if args.grayskull_power:
        print(f"{Fore.BLUE}By the power of Grayskull...\n"
              f"{Style.BRIGHT}I have the power!")
        return

    CLIConfig().stdout = args.stdout
    CLIConfig().list_missing_deps = args.list_missing_deps

    print_msg(Style.RESET_ALL)
    print_msg(clear_screen())

    for pkg_name in args.pypi_packages:
        logging.debug(f"Starting grayskull for pkg: {pkg_name}")
        pypi_label = "" if origin_is_github(pkg_name) else " (pypi)"
        print_msg(f"{Fore.GREEN}\n\n"
                  f"#### Initializing recipe for "
                  f"{Fore.BLUE}{pkg_name}{pypi_label} {Fore.GREEN}####\n")
        pkg_name, pkg_version = parse_pkg_name_version(pkg_name)
        try:
            recipe = GrayskullFactory.create_recipe(
                "pypi",
                pkg_name,
                pkg_version,
                download=args.download,
                is_strict_cf=args.is_strict_conda_forge,
            )
        except requests.exceptions.HTTPError as err:
            print_msg(
                f"{Fore.RED}Package seems to be missing on pypi.\nException: {err}\n\n"
            )
            continue
        recipe.generate_recipe(args.output, mantainers=args.maintainers)
        print_msg(f"\n{Fore.GREEN}#### Recipe generated on "
                  f"{os.path.realpath(args.output)} for {pkg_name} ####\n")
Exemple #17
0
 def do_clear_screen(self, param) -> None:
     """clear terminal screen"""
     self.poutput(clear_screen())
     self.poutput(self.intro)
Exemple #18
0
        avg_brightness = (pixel[0] + pixel[1] + pixel[2]) // 3
    elif algo == "L":
        avg_brightness = int(0.21 * pixel[0] + 0.72 * pixel[1] + 0.07 * pixel[2])
    elif algo == "MIN_MAX":
        avg_brightness = (max(pixel[0], pixel[1], pixel[2]) + min(pixel[0], pixel[1], pixel[2])) // 2

    max_ascii_level = len(ascii_brightness_levels) - 1
    return ascii_brightness_levels[int((max_ascii_level / MAX_BRIGHTNESS_LEVEL) * avg_brightness)]


if __name__ == "__main__":
    # input_image = Image.open("input.jpg")
    colorama.init()

    # Clear the screen before outputting the ascii image
    print(ansi.clear_screen())

    try:
        while True:
            input_image = get_webcam_image()
            width, height = input_image.size

            resize_to = min(width, height, MAX_TERMINAL_IMAGE_SIZE)
            input_image = input_image.resize((resize_to, resize_to))

            output_matrix = []
            for y in range(resize_to):
                current_matrix_row = []
                for x in range(resize_to):
                    pixel = input_image.getpixel((x, y))
                    ascii_char = get_ascii_for_pixel(pixel, algo="L")
Exemple #19
0
 def deal():
     print(ansi.clear_screen() + Cursor.POS(0, 0) + Style.RESET_ALL, end='')
     exit(0)
Exemple #20
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    parser = argparse.ArgumentParser(
        description="Grayskull - Conda recipe generator")
    pypi_parser = parser.add_subparsers(
        help="Options to generate PyPI recipes")
    pypi_cmds = pypi_parser.add_parser("pypi",
                                       help="Generate recipes based on PyPI")
    pypi_cmds.add_argument("pypi_packages",
                           nargs="+",
                           help="Specify the PyPI packages name.",
                           default=[])
    pypi_cmds.add_argument(
        "--download",
        "-d",
        dest="download",
        action="store_true",
        default=False,
        help="Download the sdist package and PyPI information in the same folder"
        " the recipe is located.",
    )
    pypi_cmds.add_argument(
        "--maintainers",
        "-m",
        dest="maintainers",
        nargs="+",
        help="List of maintainers which will be added to the recipe.",
    )
    parser.add_argument(
        "--version",
        "-v",
        default=False,
        action="store_true",
        dest="version",
        help="Print Grayskull version and exit",
    )
    parser.add_argument(
        "--heman",
        "--shera",
        default=False,
        action="store_true",
        dest="grayskull_power",
        help=argparse.SUPPRESS,
    )
    pypi_cmds.add_argument(
        "--output",
        "-o",
        dest="output",
        default=".",
        help="Path to where the recipe will be created",
    )
    pypi_cmds.add_argument(
        "--stdout",
        dest="stdout",
        default=True,
        help="Disable or enable stdout, if it is False, Grayskull"
        " will disable the prints. Default is True",
    )

    args = parser.parse_args(args)

    if args.version:
        print(grayskull.__version__)
        return

    logging.debug(f"All arguments received: args: {args}")

    if args.grayskull_power:
        print(f"{Fore.BLUE}By the power of Grayskull...\n"
              f"{Style.BRIGHT}I have the power!")
        return

    CLIConfig().stdout = args.stdout

    print_msg(Style.RESET_ALL)
    print_msg(clear_screen())

    for pkg_name in args.pypi_packages:
        logging.debug(f"Starting grayskull for pkg: {pkg_name}")
        print_msg(f"{Fore.GREEN}\n\n"
                  f"#### Initializing recipe for "
                  f"{Fore.BLUE}{pkg_name} (pypi) {Fore.GREEN}####\n")
        pkg_name, pkg_version = parse_pkg_name_version(pkg_name)
        recipe = GrayskullFactory.create_recipe("pypi",
                                                pkg_name,
                                                pkg_version,
                                                download=args.download)
        recipe.generate_recipe(args.output, mantainers=args.maintainers)
        print_msg(f"\n{Fore.GREEN}#### Recipe generated on "
                  f"{os.path.realpath(args.output)} for {pkg_name} ####\n")
Exemple #21
0
def clear_screen():
    """Зачистить экран"""
    print(ansi.clear_screen())