Exemplo n.º 1
0
def current_month_task_analysis():
    now = datetime.datetime.now()
    no_of_days_current_month = calendar.monthrange(now.year, now.month)[1]
    total_tasks = 0
    total_incomplete_tasks = 0
    list_of_files = list_of_tasks_files()
    for i in range(0, len(list_of_files)):
        list_of_files[i] = os.path.join(DIARY_CONFIG_FOLDER_PATH,
                                        list_of_files[i])
    for i in list_of_files:
        with open(i, 'r') as fp:
            contents = yaml.load(fp)
            for entry in contents['entries']:
                total_tasks += 1
                total_incomplete_tasks += (1 if entry['status'] == 0 else 0)
    if total_tasks != 0:
        percent_incomplete_task = total_incomplete_tasks * 100 / total_tasks
        percent_complete_task = 100 - percent_incomplete_task
        entry_frequency = total_tasks * 100 / no_of_days_current_month
    else:
        percent_complete_task = 'NA'
        percent_incomplete_task = 'NA'
        entry_frequency = 0
    chalk.red('Percentage of incomplete task : ' +
              str(percent_incomplete_task))
    chalk.green('Percentage of complete task : ' + str(percent_complete_task))
    chalk.blue("Frequency of adding task (Task/Day) : " + str(entry_frequency))
Exemplo n.º 2
0
async def start_somewhere(runner):
    print("Searching for an open port...")
    for port in range(48654, 49150):
        if port == 49000:  # reserved
            continue

        site = web.TCPSite(runner, "", port)
        try:
            await site.start()
        except Exception as e:
            print(chalk.red(f"Unable to start on port {port}: {e}"))
            continue
        print(chalk.green(f"Started server on port {port} successfully!"))
        break
    else:
        print(chalk.red("Could not use any available port."))
        raise SystemExit(1)

    print("Opening port via UPnP...")
    upnp = miniupnpc.UPnP()
    upnp.discoverdelay = 10
    upnp.discover()
    upnp.selectigd()
    if upnp.addportmapping(port, "TCP", upnp.lanaddr, port, "PijulGit proxy",
                           ""):
        print(chalk.green(f"Opened port {port} successfully!"))
    else:
        print(chalk.red(f"Failed to open port {port} :("))

    return site, port
Exemplo n.º 3
0
def dep_with(account: act) -> int:
    # parameters work with welcome()

    while True:

        chalk.green("""
What would you like to do?
=====*=====*=====*=====*=====*=====*=====*=====*=====*=====
Deposit to checking: press 1 ➤ 
Deposit to savings: press 2 ➤  
Withdrawal from checking: press 3 ➤ 
Withdrawal from savings: press 4 ➤ 
""")
        choose = int(input('Enter ➤➤ '))

        if choose == 1:
            chalk.magenta("Enter deposit amount:")             # Deposit to checking
            new_dep = int(input('➤➤  '))

            # except ValueError:
            #     pass

            dep_amount = account.deposit(new_dep)

            new_balance = account.get_funds()
            chalk.magenta(f"""{dep_amount} has been deposited to your account.  
            Your new balance is {new_balance}.""")

        elif choose == 2:
            chalk.magenta("Enter deposit amount:")             # Deposit to savings
            new_svgs_dep = int(input('➤➤  '))

            svgs_dep_amount = account.deposit(new_svgs_dep)

            svgs_new_balance = account.get_funds()
            chalk.magenta(f"""{svgs_dep_amount} has been deposited to your account.  
            Your new balance is {svgs_new_balance}.""")

        elif choose == 3:
            chalk.magenta("Enter withdrawal amount:")          # Withdrawal from checking
            new_withdra = int(input('➤➤ '))
            account.withdrawal(new_withdra)

            new_balance = account.get_funds()
            chalk.magenta(f"""{new_withdra} has been withdrawn from your account.  
            Your new balance is {new_balance}.""")

        elif choose == 4:
            chalk.magenta("Enter withdrawal amount:")          # Withdrawal from savings
            svgs_new_withdra = int(input('➤➤ '))
            account.withdrawal(svgs_new_withdra)

            svgs_new_balance = account.get_funds()
            chalk.magenta(f"""{svgs_new_withdra} has been withdrawn from your account.
            Your new balance is {svgs_new_balance}.""")

        # except ValueError as error:
        #     chalk.red(error.args[0])

        return another_trans(account=account)   # how affect svgs_account
Exemplo n.º 4
0
def tasks():
    if os.path.isfile(TODAYS_TASKS_ENTRY_FILE_PATH):
        click.echo('Today\'s agenda:')
        click.echo('----------------')
        click.echo("Status |  Time   | Text")
        click.echo("-------|---------|-----")
        incomplete_tasks = 0
        total_tasks = 0
        with open(TODAYS_TASKS_ENTRY_FILE_PATH, 'r') as todays_tasks_entry:
            contents = yaml.load(todays_tasks_entry)
            for entry in contents['entries']:
                total_tasks += 1
                incomplete_tasks += (1 if entry['status'] == 0 else 0)
                time = entry['time']
                text = entry['text'] if entry['status'] == 0 else strike(
                    entry['text'])
                status = "O" if entry['status'] == 0 else "X"
                click.echo("   " + status + "   | " + time + ": " + text)
        click.echo('----------------')
        click.echo('')
        click.echo('Summary:')
        click.echo('----------------')
        if incomplete_tasks == 0:
            chalk.green(
                'All tasks have been competed! Add a new task by entering "dude  diary nt"'
            )
        else:
            chalk.red("Incomplete tasks: " + str(incomplete_tasks))
            chalk.green("Completed tasks: " +
                        str(total_tasks - incomplete_tasks))

    else:
        click.echo(
            'There are no tasks for today. Add a new task by entering "dude diary nt"'
        )
Exemplo n.º 5
0
def launch(*args, **options):
    "launch acts on the user specified action and options by executing Hedrix.run"
    action = args[0]
    if options['reload']:
        event_handler = Reload(options)
        observer = Observer()
        observer.schedule(event_handler, path='.', recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
            pid = os.getpid()
            chalk.eraser()
            chalk.green('\nHendrix successfully closed.')
            os.kill(pid, 15)
        observer.join()
        exit('\n')
    else:
        try:
            deploy = HendrixDeploy(action, options)
            deploy.run()
        except Exception, e:
            if options.get('traceback'):
                tb = sys.exc_info()[2]
                msg = traceback.format_exc(tb)
            else:
                msg = str(e)
            chalk.red(msg, pipe=chalk.stderr)
            os._exit(1)
Exemplo n.º 6
0
    async def on_ready(self):  #When the bot is ready
        print("\n")
        print(chalk.green(f"[SUCCESS] Connected to Discord as: {self.b.user}"))
        if conf.sharding is False:  #If sharding is disabled
            print(chalk.red(f"[WARNING] Sharding: Disabled"))
        elif conf.sharding is True:  #If sharding is Enabled
            print(chalk.green("[INFO] Sharding: Enabled"))
            print(chalk.yellow(f"[INFO] Using SHARD's {self.b.shard_ids}")
                  )  #Shows us how many shards we are currently using

        print(chalk.cyan(f"[INFO] Config name: '{conf.name}'")
              )  #Shows us the name defined in the config
        print(
            chalk.cyan(
                f"[INFO] Default Prefix: 'Prefix 1: {conf.prefix1} | Prefix 2: {conf.prefix2}'"
            ))  #Shows us the 2 prefixes defined in the config
        print(chalk.cyan("[INFO] Are you braindead: Most Likely"))  #Yup
        print(
            chalk.cyan(
                f"[INFO] I'm currently in [{len(self.b.guilds)}] server(s).")
        )  #Shows us how many servers we are in
        aaa = True
        for guild in self.b.guilds:  #Set all guild the doki is in to have triggers enabled on startup otherwise they no be in list which means triggers are off.
            conf.w_tog_on.insert(0, guild.id)
        while aaa:  #A loop to make the game activity change every 900 seconds
            for list in conf.playing_msg:
                await self.b.change_presence(activity=discord.Game(name=list))
                await asyncio.sleep(900)
Exemplo n.º 7
0
def book_catalog():
    """
    gather text file titles from path to a folder, offer user choice to pick a title, send that choice to 
    file_opener
    
    :return: None
    """

    book_list = [book for book in os.listdir(BOOKS) if '.txt' in book]
    menu_text = f"""To compute its automated readability index, 
pick from one of the files below:\n"""

    options = {index: book for index, book in enumerate(book_list, start=1)}
    options.update({'q)': 'quit'})

    chalk.green(menu_text)
    for index, book in options.items():
        print(f'{index}) {book}')

    choice = int(input("Enter number choice here >>> "))

    lookup_title = options.get(
        choice
    )  # gets choice of text file title from book_list stores in lookup_title
    full_path = BOOKS + lookup_title  # concats BOOKS URL with text file name and stores in full_path
    text = file_opener(
        full_path
    )  # full text url path is passed to file_opener function to display text
    score = compute_ari(
        text
    )  # text passed to compute_ari where it's cleaned, counted and computed with ARI equation
    output(
        score, lookup_title
    )  # final output score and ranking printed to screen, pass text title name for final print out
Exemplo n.º 8
0
def DjangoStaticResource(path, rel_url='static'):
    """
    takes an app level file dir to find the site root and servers static files
    from static
    Usage:
        [...in app.resource...]
        from hendrix.resources import DjangoStaticResource
        StaticResource = DjangoStaticResource('/abspath/to/static/folder')
        ... OR ...
        StaticResource = DjangoStaticResource(
            '/abspath/to/static/folder', 'custom-static-relative-url'
        )

        [...in settings...]
        HENDRIX_CHILD_RESOURCES = (
            ...,
            'app.resource.StaticResource',
            ...
        )
    """
    rel_url = rel_url.strip('/')
    StaticFilesResource = MediaResource(path)
    StaticFilesResource.namespace = rel_url
    chalk.green(
        "Adding media resource for URL '%s' at path '%s'" % (rel_url, path)
    )
    return StaticFilesResource
Exemplo n.º 9
0
def DjangoStaticResource(path, rel_url='static'):
    """
    takes an app level file dir to find the site root and servers static files
    from static
    Usage:
        [...in app.resource...]
        from hendrix.resources import DjangoStaticResource
        StaticResource = DjangoStaticResource('/abspath/to/static/folder')
        ... OR ...
        StaticResource = DjangoStaticResource(
            '/abspath/to/static/folder', 'custom-static-relative-url'
        )

        [...in settings...]
        HENDRIX_CHILD_RESOURCES = (
            ...,
            'app.resource.StaticResource',
            ...
        )
    """
    rel_url = rel_url.strip('/')
    StaticFilesResource = MediaResource(path)
    StaticFilesResource.namespace = rel_url
    chalk.green(
        "Adding media resource for URL '%s' at path '%s'" % (rel_url, path)
    )
    return StaticFilesResource
Exemplo n.º 10
0
async def embed(ctx, *, a_sMessage):
    embed = discord.Embed(description=a_sMessage, color=0xffdd00)
    embed.set_thumbnail(url=ctx.message.author.avatar_url)
    embed.set_author(name=ctx.message.author.name + " says..")
    embed.set_footer(text="Fox 0.3")
    await bot.delete_message(ctx.message)
    await bot.say(embed=embed)
    chalk.green(ctx.message.author.name + " has embedded a message in " + ctx.message.server.name)
Exemplo n.º 11
0
def thread_init():
    if len(THREAD_CONFIG):
        chalk.green('current time: %r' % utc_now())
        chalk.green('Found %d thread(s) specified by THREAD_CONFIG' %
                    len(THREAD_CONFIG))

        for index, thread_group_list in enumerate(THREAD_CONFIG):
            tm = ThreadManager(index, thread_group_list)
            tm.start()
Exemplo n.º 12
0
def stat_printer(rain_stat: tuple) -> None:
    """display results"""

    date, rain_amount = rain_stat[0], int(rain_stat[1][0] / 24)
    year, month, day = date[-4:], date[3:6].capitalize(), date[1:2]



    chalk.red(f"{month}. {day}, {year} had the most rain with {rain_amount} hunderedths of an inch on an hourly average.")
    chalk.green(f"The year with the most rain was {year} with {rain_amount} inches of rain.")
Exemplo n.º 13
0
def thread_init():
    if len(THREAD_CONFIG):
        chalk.green('current time: %r' % utc_now())
        chalk.green(
            'Found %d thread(s) specified by THREAD_CONFIG' % len(THREAD_CONFIG)
        )

        for index, thread_group_list in enumerate(THREAD_CONFIG):
            tm = ThreadManager(index, thread_group_list)
            tm.start()
Exemplo n.º 14
0
 def stop(self, sig=9):
     with open(self.pid) as pid_file:
         pids = pid_file.readlines()
         for pid in pids:
             try:
                 os.kill(int(pid), sig)
             except OSError:
                 # OSError raised when it trys to kill the child processes
                 pass
     os.remove(self.pid)
     chalk.green('Stopping Hendrix...')
Exemplo n.º 15
0
 def stop(self, sig=9):
     with open(self.pid) as pid_file:
         pids = pid_file.readlines()
         for pid in pids:
             try:
                 os.kill(int(pid), sig)
             except OSError:
                 # OSError raised when it trys to kill the child processes
                 pass
     os.remove(self.pid)
     chalk.green('Stopping Hendrix...')
Exemplo n.º 16
0
def thread_init():
    if len(THREAD_CONFIG):
        chalk.green('current time: %r' % utc_now())
        chalk.green(
            'Found %d thread(s) specified by THREAD_CONFIG' % len(THREAD_CONFIG)
        )

        for index, thread_group_list in enumerate(THREAD_CONFIG):
            runner = Runner(index, thread_group_list)

    tiempo_loop.start()
Exemplo n.º 17
0
async def pullPijul(url):
    # Check whether we have the repo downloaded already
    path = urlToPath(url)
    if os.path.isdir(path):
        print(f"  Pijul: Fetching {url} to {path}...")
        await run(f"cd {path}; pijul pull --all")
        print(chalk.green("  Done."))
    else:
        print(f"  Pijul: Cloning {url} to {path}...")
        await run(
            f"mkdir {path}; cd {path}; pijul init; pijul pull --set-default --set-remote origin \"{url}\" --all"
        )
        print(chalk.green("  Done."))
Exemplo n.º 18
0
    async def on_ready(self):
        botguild = next((item for item in self.bot.guilds if item.id == 615228970568515626), None)
        log = botguild.get_channel(625767405641007106)
        if not hasattr(self.bot, 'uptime'):
            self.bot.uptime = datetime.utcnow()

        print(chalk.bold(chalk.cyan('Ready: ')) + chalk.green(f'{self.bot.user}') + chalk.yellow(' | ') + chalk.bold(
            chalk.cyan('Servers: ')) + chalk.green(
            f'{len(self.bot.guilds)}'))
        await self.bot.change_presence(activity=discord.Game(type=0, name=self.config.playing),
                                       status=discord.Status.online)

        await log.send(f'```css\nReady! Guilds: {len(self.bot.guilds)}```')
Exemplo n.º 19
0
def responseInColor(request, status, headers, prefix='Response', opts=None):
    "Prints the response info in color"
    code, message = status.split(None, 1)
    message = '%s [%s] => Request %s %s %s on pid %d' % (
        prefix, code, str(
            request.host), request.method, request.path, os.getpid())
    signal = int(code) / 100
    if signal == 2:
        chalk.green(message, opts=opts)
    elif signal == 3:
        chalk.blue(message, opts=opts)
    else:
        chalk.red(message, opts=opts)
Exemplo n.º 20
0
def battle(good_guy, bad_guy):
    bad_guy_name = bad_guy.get_kind().title()
    good_guy_name = good_guy.get_kind().title()

    print(chalk.green(f"You are attacking a {bad_guy.get_kind()}, armed with a {bad_guy.get_weapon()}"))
    print(chalk.green("here are it's stats..."))
    print(chalk.green(bad_guy))
    ans = answer_question('Would you like to attack or run away (a/r)?', ['a', 'r'])
    while ans == 'a':
        rps_dictionary = {'r': 'rock', 'p': 'paper', 's': 'scissors'}
        ans = answer_question('Choose rock, paper, or scissors (r/p/s)', ['r', 'p', 's'])
        good_guy_choice = rps_dictionary[ans]
        bad_guy_choice = random.choice(['rock', 'paper', 'scissors'])

        print(chalk.green(f'You chose {good_guy_choice} and the enemy chose {bad_guy_choice}'))
        if bad_guy_choice == good_guy_choice:
            print(chalk.green("It's a tie! Do over!"))
        elif bad_guy_choice == 'rock' and good_guy_choice == 'paper':
            print(chalk.green("You've struck a blow! Good job!"))
            bad_guy.update_health(-1 * good_guy.get_attack_power())
        elif bad_guy_choice == 'paper' and good_guy_choice == 'scissors':
            print(chalk.green("You've struck a blow! Good job!"))
            bad_guy.update_health(-1 * good_guy.get_attack_power())
        elif bad_guy_choice == 'scissors' and good_guy_choice == 'rock':
            print(chalk.green("You've struck a blow! Good job!"))
            bad_guy.update_health(-1 * good_guy.get_attack_power())
        elif bad_guy_choice == 'scissors' and good_guy_choice == 'paper':
            print(chalk.red("You've taken a hit. Ouch!"))
            good_guy.update_health(-1 * bad_guy.get_attack_power())
        elif bad_guy_choice == 'paper' and good_guy_choice == 'rock':
            print(chalk.red("You've taken a hit. Ouch!"))
            good_guy.update_health(-1 * bad_guy.get_attack_power())
        elif bad_guy_choice == 'rock' and good_guy_choice == 'scissors':
            print(chalk.red("You've taken a hit. Ouch!"))
            good_guy.update_health(-1 * bad_guy.get_attack_power())

        if hero.get_health() <= 0:
            print_image('died_in_battle.txt')
            return good_guy, bad_guy
        elif bad_guy.get_health() <= 0:
            print_image('won_the_battle.txt')
            return good_guy, Thing(bad_guy.get_weapon(), bad_guy.get_location(), False, False)

        battle_status = good_guy_name + ': ' + str(good_guy.get_health()) + '  vs.  ' + bad_guy_name + ': ' \
                        + str(bad_guy.get_health())
        if good_guy.get_health() > 35:
            print(chalk.green(battle_status))
        elif good_guy.get_health() > 10:
            print(chalk.yellow(battle_status))
        else:
            print(chalk.red(battle_status))

        ans = answer_question('Would you like to attack or run away (a/r)?', ['a', 'r'])

    return hero, bad_guy
Exemplo n.º 21
0
async def reload(ctx):

    for extension in extensions:
        try:
            bot.unload_extension(f"cogs.{extension}")
            print(chalk.green(f"cogs.{extension} unloaded"))
            await ctx.send(f"cogs.{extension} unloaded")

            bot.load_extension(f"cogs.{extension}")
            print(chalk.green(f"cogs.{extension} loaded"))
            await ctx.send(f"cogs.{extension} loaded")

        except Exception as error:
            print(chalk.red(f"{extension} cannot be loaded. {error}"))
Exemplo n.º 22
0
def complete_task():
    not_valid_task_number = 1
    if os.path.isfile(TODAYS_TASKS_ENTRY_FILE_PATH):
        with open(TODAYS_TASKS_ENTRY_FILE_PATH, 'r') as todays_tasks_entry:
            contents = yaml.load(todays_tasks_entry)
            i = 0
            no_task_left = True
            for entry in contents['entries']:
                i += 1
                if entry['status'] == 0:
                    no_task_left = False

            if no_task_left:
                chalk.green(
                    'All tasks have been competed! Add a new task by entering "yoda  diary nt"'
                )
            else:
                click.echo('Today\'s agenda:')
                click.echo('----------------')
                click.echo("Number |  Time   | Task")
                click.echo("-------|---------|-----")

                i = 0
                for entry in contents['entries']:
                    i += 1
                    time = entry['time']
                    text = entry['text'] if entry['status'] == 0 else strike(
                        entry['text'])
                    status = "O" if entry['status'] == 0 else "X"
                    if entry['status'] == 0:
                        no_task_left = False
                        click.echo("   " + str(i) + "   | " + time + ": " +
                                   text)
                while not_valid_task_number:
                    chalk.blue(
                        'Enter the task number that you would like to set as completed'
                    )
                    task_to_be_completed = int(raw_input())
                    if (task_to_be_completed > len(contents['entries'])):
                        chalk.red('Please Enter a valid task number!')
                    else:
                        contents['entries'][task_to_be_completed -
                                            1]['status'] = 1
                        input_data(contents, TODAYS_TASKS_ENTRY_FILE_PATH)
                        not_valid_task_number = 0
    else:
        chalk.red(
            'There are no tasks for today. Add a new task by entering "yoda diary nt"'
        )
Exemplo n.º 23
0
def show_status():
	success = chalk.green(emoji.emojize(':heavy_check_mark:', use_aliases=True).center(10, " ") * 5)
	error = chalk.red(emoji.emojize(':x:', use_aliases=True).center(10, " ") * 5)

	if hasattr(F1, '_ts') and hasattr(F1, '_name'):
		print(success)
		print(chalk.green("¡Escala de tiempo inicializada!"))
		# TODO: Imprimir los datos de la escala de tiempo.
		# TODO: Emplear una tupla en vez de una lista.
		print(f"Datos de la escala de tiempo:")
		print(f"Su nombre es {F1._name}.")
		print(f'Conjunto T = {{{", ".join(map(str, F1._ts))}}}.')
	else:
		print(error)
		print(chalk.red("Se ha producido un error."))
Exemplo n.º 24
0
def main():
    "The function to execute when running hx"
    options, args = HendrixOptionParser.parse_args(sys.argv[1:])
    options = vars(options)

    try:
        action = args[0]
    except IndexError:
        HendrixOptionParser.print_help()
        return

    exposeProject(options)

    options = djangoVsWsgi(options)

    options = devFriendly(options)

    redirect = noiseControl(options)

    try:
        if action == 'start' and not options['daemonize']:
            chalk.eraser()
            chalk.blue('Starting Hendrix...')
        elif action == 'stop':
            chalk.green('Stopping Hendrix...')
        if options['daemonize']:
            daemonize, _reload, opts = cleanOptions(options)
            process = subprocess.Popen(
                ['hx', action] + opts, stdout=redirect, stderr=redirect
            )
            time.sleep(2)
            if process.poll():
                raise RuntimeError
        else:
            launch(*args, **options)
            if action not in ['start_reload', 'restart']:
                chalk.eraser()
                chalk.green('\nHendrix successfully closed.')
    except Exception, e:
        msg = (
            'ERROR: %s\nCould not %s hendrix. Try again using the --traceback '
            'flag for more information.'
        )
        chalk.red(msg % (str(e), action), pipe=chalk.stderr)
        if options['traceback']:
            raise
        else:
            os._exit(1)
Exemplo n.º 25
0
async def start(onBind, c):
    global config
    config = c

    import logging
    logger = logging.Logger("server")
    logger.setLevel(logging.DEBUG)

    # Create an app and a runner
    app = web.Application()
    app.add_routes([web.post("/fromGitlab", fromGitlab)])
    app.add_routes([web.post("/fromNest", fromNest)])
    runner = web.AppRunner(app, logger=logger)
    await runner.setup()

    site, port = await start_somewhere(runner)
    cur_ip = await get("https://api.ipify.org")
    await onBind(f"{cur_ip}:{port}")

    print(chalk.green(chalk.bold("  Initialization finished!")))

    # Listen for IP changes
    while True:
        await asyncio.sleep(5)
        ip = await get("https://api.ipify.org")
        if ip != cur_ip:
            print(
                chalk.yellow(
                    f"IP changed from {cur_ip} to {ip}, restarting server..."))
            await site.stop()
            site, port = await start_somewhere(runner)
            cur_ip = ip
            await onBind(f"{cur_ip}:{port}")
def outro_alt():
    sleep(2)
    print(
        chalk.yellow('''


                 ██████╗  █████╗ ███╗   ███╗███████╗
                ██╔════╝ ██╔══██╗████╗ ████║██╔════╝
                ██║  ███╗███████║██╔████╔██║█████╗  
                ██║   ██║██╔══██║██║╚██╔╝██║██╔══╝  
                ╚██████╔╝██║  ██║██║ ╚═╝ ██║███████╗
                 ╚═════╝ ╚═╝  ╚═╝╚═╝     ╚═╝╚══════╝
                  ██████╗ ██╗   ██╗███████╗██████╗ 
                 ██╔═══██╗██║   ██║██╔════╝██╔══██╗
                 ██║   ██║██║   ██║█████╗  ██████╔╝
                 ██║   ██║╚██╗ ██╔╝██╔══╝  ██╔══██╗
                 ╚██████╔╝ ╚████╔╝ ███████╗██║  ██║
                  ╚═════╝   ╚═══╝  ╚══════╝╚═╝  ╚═╝
    '''))
    s.sound_effect('audio/ending_theme_short.wav')
    print(
        chalk.yellow('''
                                         ...or is it?
    '''))
    sleep(2)
    print(chalk.green("\tWould you like to see the alternate ending? y/n"))
    ending = input("> ")
    if ending == 'y':
        alt()
Exemplo n.º 27
0
def from_images(ctx):
    args = {
        ctx.args[i].strip("--"): ctx.args[i + 1]
        for i in range(0, len(ctx.args), 2)
    }
    try:
        source = args.pop("source")
    except KeyError:
        click.echo(
            chalk.red("Source parameter is missing. "
                      "Use --source to provide the path."))
        return
    try:
        output = args.pop("output")
    except KeyError:
        click.echo(
            chalk.red("Output path is missing. "
                      "Use --output to provide the path."))
        return
    images = []
    if not os.path.isdir(source):
        click.echo(chalk.red("Source should be a directory."))
    for filename in os.listdir(source):
        if os.path.isfile(os.path.join(source, filename)):
            images.append(imageio.imread(os.path.join(source, filename)))

    try:
        with open(output, "w") as outfile:
            imageio.mimsave(outfile, images, format="gif", **args)
        click.echo(chalk.green("GIF exported at {}".format(output)))
    except (OSError, IOError):
        click.echo(
            chalk.red("Could not write to file {}. "
                      "Please check the path".format(output)))
Exemplo n.º 28
0
 def check_results(self):
     print(
         f"::set-output name=has_updated_sources::{str(self.has_updated_sources)}"
     )
     if self.status == "success":
         logging.info(
             c.green("✅ Successfully linted all files without errors"))
         config.delete()
     elif self.status == "warning":
         logging.warning(
             c.yellow(
                 "◬ Successfully linted all files, but with ignored errors")
         )
         config.delete()
     else:
         logging.error(c.red("❌ Error(s) have been found during linting"))
         logging.warning(
             "To disable linters or customize their checks, you can use a .mega-linter.yml file "
             "at the root of your repository")
         logging.warning(f"More info at {ML_DOC_URL}/configuration/")
         if self.cli is True:
             if config.get("DISABLE_ERRORS", "false") == "true":
                 config.delete()
                 sys.exit(0)
             else:
                 config.delete()
                 sys.exit(self.return_code)
         config.delete()
Exemplo n.º 29
0
async def setHooks(url, host):
    project = getUrlRepository(url)
    print(f"Setting hooks for {project} at Nest...")

    admin = await get(f"https://nest.pijul.com/{project}/admin")
    # Parse token
    token = (admin.split("""<input type="hidden" name="token" value=""" + "\"",
                         1)[1].split("\"")[0])
    # Delete old hooks
    while """<input type="hidden" name="hookid" value=""" + "\"" in admin:
        hook_id = (admin.split(
            """<input type="hidden" name="hookid" value=""" + "\"",
            1)[1].split("\"")[0])
        url, admin = (admin.split(
            """<input style="width:100%" type="text" name="url" value=""" +
            "\"", 1)[1].split("\"", 1))
        if "fromNest" in url:
            await post(f"https://nest.pijul.com/{project}/admin",
                       data={
                           "token": token,
                           "hookid": hook_id,
                           "hook_action_2": "2",
                           "action": "delete-hook"
                       })
    # Create hook
    await post(f"https://nest.pijul.com/{project}/admin",
               data={
                   "token": token,
                   "url": f"http://{host}/fromNest",
                   "secret": "",
                   "hook_action_2": "2"
               })
    print(chalk.green(f"Created Nest webhook successfully"))
 def shields(self, shield_level):
     if shield_level == 100:
         return chalk.green(f"Shields: {shield_level}%")
     if shield_level > 20:
         return chalk.yellow(f"Shields: {shield_level}%")
     else:
         return chalk.red(f"Shields: {shield_level}%")
Exemplo n.º 31
0
    def success(self, name: str = "Main Process", output: str = None):
        if output is None:
            return print(
                chalk.red(
                    f"{time.strftime('%c')} - [{name}]: No output provided!"))

        print(chalk.green(f"{time.strftime('%c')} - [{name}]: {output}"))
Exemplo n.º 32
0
def move_enemies(world):
    # Moving enemies around the board, if chosen direction is empty or hero, action is taken, otherwise they don't mainLoop.
    # Build list of enemies first then mainLoop them one at a time
    move_tuples = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    enemies = world.get_enemies()
    for enemy in enemies:
        current_location = enemy.get_location()
        while True:
            choice = random.choice(move_tuples)
            next_location = (current_location[0] + choice[0],
                             current_location[1] + choice[1])
            if 0 < next_location[0] <= world.get_rows(
            ) and 0 < next_location[1] <= world.get_columns():
                break
        if isinstance(world[next_location], Empty):
            world[next_location] = enemy
            enemy.update_location(next_location)
            world[current_location] = Empty('empty', current_location, True)
        elif world[next_location] == hero:
            print_image(enemy.get_kind() + '.txt')
            print(
                chalk.red(
                    f"Look out! You are being attacked by a {enemy.get_kind()} "
                    f"armed with a {enemy.get_weapon()}"))
            print(chalk.yellow("Here are it's stats..."))
            print(chalk.green(enemy))
            world[current_location] = battle(enemy)
    return
Exemplo n.º 33
0
async def syncPijulToGitPatch(branch, git, pijul, action, patch_id, author,
                              timestamp, message):
    small_patch_id = patch_id[:10] + "..."
    if action == "add":
        print(f"  Syncing new patch {small_patch_id}: {message}")
        await run(f"cd {pijul}; pijul apply {patch_id} --branch {branch}")
    elif action == "remove":
        print(f"  Reverting patch {small_patch_id}: {message}")
        await run(f"cd {pijul}; pijul unrecord {patch_id} --branch {branch}")

    await run(f"cd {pijul}; pijul revert --all --branch {branch}")

    # Synchronize
    await run(f"rsync -rv -f'- .git/' -f'- .pijul/' {pijul}/ {git}/")

    # Commit
    is_empty = (await run(f"cd {git}; git status --short")).strip() == ""

    if action == "add":
        message = shlex.quote(
            f"{message}\n\nImported from Pijul patch {patch_id}")
    elif action == "remove":
        message = shlex.quote(f"{message}\n\nReverted Pijul patch {patch_id}")
    author = shlex.quote(author)
    date = str(timestamp)
    await run(
        f"cd {git}; git add --all; git commit --author={author} --date='{date}' --message={message} --no-edit --allow-empty"
    )
    commit = (await run(f"cd {git}; git rev-parse HEAD")).strip()

    if is_empty:
        print(chalk.yellow(f"  No changes (fast-forward), committed {commit}"))
    else:
        print(chalk.green(f"  Done. Committed {commit}"))
Exemplo n.º 34
0
def another_trans(account: act) -> None:

        chalk.green("""
Would you like another transaction?
=====*=====*=====*=====*=====*=====*=====
Yes: press 1 
No: press 2  
""")

        choose = int(input('Enter ➤➤ '))

        if choose == 1:
            dep_with(account=account)

        else:
            chalk.magenta("Thank you! Have a nice day.")
            quit()
Exemplo n.º 35
0
def responseInColor(request, prefix='Response', opts=None):
    "Prints the response info in color"
    message = '%s [%s] => Request %s %s %s on pid %d' % (
        prefix,
        request.code,
        str(request.host),
        request.method,
        request.path,
        os.getpid()
    )
    signal = int(request.code)/100
    if signal == 2:
        chalk.green(message, opts=opts)
    elif signal == 3:
        chalk.blue(message, opts=opts)
    else:
        chalk.red(message, opts=opts)
Exemplo n.º 36
0
async def pullGit(url):
    # Check whether we have the repo downloaded already
    path = urlToPath(url)
    if os.path.isdir(path):
        print(f"  Git: Fetching {url} to {path}...")
        await run(f"cd {path}; git fetch")
        for r in (await run(f"cd {path}; git branch -r")).split("\n"):
            r = r[2:]
            if r.startswith("origin/"):
                branch = r.split("/", 1)[1]
                if not branch.startswith("HEAD -> "):
                    await run(f"cd {path}; git checkout {branch}")
        print(chalk.green("  Done."))
    else:
        print(f"  Git: Cloning {url} to {path}...")
        await run(f"cd /tmp; git clone \"{url}\" {path}")
        print(chalk.green("  Done."))
Exemplo n.º 37
0
def copy_dir_contents(src, dst, ignore=IGNORE):
    "Copies all folders and files under src directory to dst"
    for f in os.listdir(src):
        if f in ignore:
            chalk.yellow("Ignoring {0}".format(f))
            continue

        fpath = os.path.join(src, f)
        dst_path = os.path.join(dst, f)

        if os.path.isdir(fpath):
            if not os.path.exists(dst_path):
                os.mkdir(dst_path)
            chalk.green("Copying '{0}' and its contents to '{1}'".format(f, dst))
            copy_dir_contents(fpath, dst_path, ignore)
        else:
            chalk.green("Copying file '{0}' to '{1}'".format(f, dst))
            shutil.copy(fpath, dst)
Exemplo n.º 38
0
def launch(*args, **options):
    """
    launch acts on the user specified action and options by executing
    Hedrix.run
    """
    action = args[0]
    if options["reload"]:
        event_handler = Reload(options)
        observer = Observer()
        observer.schedule(event_handler, path=".", recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
            pid = os.getpid()
            chalk.eraser()
            chalk.green("\nHendrix successfully closed.")
            os.kill(pid, 15)
        observer.join()
        exit("\n")
    else:
        try:
            if options["key"] and options["cert"] and options["cache"]:
                from hendrix.deploy import hybrid

                HendrixDeploy = hybrid.HendrixDeployHybrid
            elif options["key"] and options["cert"]:
                from hendrix.deploy import ssl

                HendrixDeploy = ssl.HendrixDeploySSL
            elif options["cache"]:
                HendrixDeploy = cache.HendrixDeployCache
            else:
                HendrixDeploy = base.HendrixDeploy
            deploy = HendrixDeploy(action, options)
            deploy.run()
        except Exception, e:
            tb = sys.exc_info()[2]
            msg = traceback.format_exc(tb)
            chalk.red(msg, pipe=chalk.stderr)
            os._exit(1)
Exemplo n.º 39
0
def logReload(options):
    """
    encompasses all the logic for reloading observer.
    """
    event_handler = Reload(options)
    observer = Observer()
    observer.schedule(event_handler, path='.', recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        pid = os.getpid()
        chalk.eraser()
        chalk.green('\nHendrix successfully closed.')
        os.kill(pid, 15)
    observer.join()
    exit('\n')
Exemplo n.º 40
0
def main():
    "The function to execute when running hx"
    options, args = HendrixOptionParser.parse_args(sys.argv[1:])
    options = vars(options)

    try:
        action = args[0]
    except IndexError:
        HendrixOptionParser.print_help()
        return

    exposeProject(options)

    options = djangoVsWsgi(options)

    options = devFriendly(options)

    redirect = noiseControl(options)

    try:
        if action == "start" and not options["daemonize"]:
            chalk.eraser()
            chalk.blue("Starting Hendrix...")
        elif action == "stop":
            chalk.green("Stopping Hendrix...")
        if options["daemonize"]:
            daemonize, _reload, opts = cleanOptions(options)
            process = subprocess.Popen(["hx", action] + opts, stdout=redirect, stderr=redirect)
            time.sleep(2)
            if process.poll():
                raise RuntimeError
        else:
            launch(*args, **options)
            if action not in ["start_reload", "restart"]:
                chalk.eraser()
                chalk.green("\nHendrix successfully closed.")
    except Exception, Argument:
        print Argument
        chalk.red("\n Could not %s hendrix.\n" % action, pipe=chalk.stderr)
Exemplo n.º 41
0
def main():
    "The function to execute when running hx"
    options, args = HendrixOptionParser.parse_args(sys.argv[1:])
    options = vars(options)

    action = args[0]

    exposeProject(options)

    options = djangoVsWsgi(options)

    options = devFriendly(options)

    redirect = noiseControl(options)

    try:
        if action == "start" and not options["daemonize"]:
            chalk.eraser()
            chalk.blue("Starting Hendrix...")
        elif action == "stop":
            chalk.green("Stopping Hendrix...")
        if options["daemonize"]:
            daemonize, _reload, opts = cleanOptions(options)
            process = subprocess.Popen(["hx", action] + opts, stdout=redirect, stderr=redirect)
            time.sleep(2)
            if process.poll():
                raise RuntimeError
        else:
            launch(*args, **options)
            if action not in ["start_reload", "restart"]:
                chalk.eraser()
                chalk.green("\nHendrix successfully closed.")
    except Exception, e:
        msg = "ERROR: %s\nCould not %s hendrix. Try again using the --traceback " "flag for more information."
        chalk.red(msg % (str(e), action), pipe=chalk.stderr)
        if options["traceback"]:
            raise
        else:
            os._exit(1)
Exemplo n.º 42
0
Arquivo: lidard.py Projeto: sli/lidard
def lidard(config, name, serial, baud, bind, port, modules, verbose):
    '''`lidard` is a RPLidar data-serving daemon.'''
    if config is None:
        if not serial:
            print('A serial path must be specified.')
            sys.exit(1)

        modules = [m.strip() for m in modules.split(',')]

        cfg = {
            'serial': serial,
            'baud': baud,
            'bind': bind,
            'port': port,
            'modules': modules,
            'meta': {
                'name': name,
            }
        }
    else:
        cfg = read_config(config)

        if 'serial' not in cfg:
            print('A serial path must be specified in the configuration.')
            sys.exit(1)

        if 'baud' not in cfg:
            cfg['baud'] = baud
        if 'port' not in cfg:
            cfg['port'] = port
        if 'bind' not in cfg:
            cfg['bind'] = '0.0.0.0'
        if 'modules' not in cfg:
            cfg['modules'] = []
        if 'meta' in cfg and 'name' not in cfg['meta']:
            cfg['meta']['name'] = 'lidard'

    ser = _serial.Serial()
    ser.port = cfg['serial']
    ser.baudrate = cfg['baud']
    ser.open()

    server = socketserver.UDPServer((cfg['bind'], cfg['port']), LidardServer)
    server.config = cfg
    server.ser = ser
    server.verbose = verbose

    # Load the extensions and insert them into the request handler.
    ext = {}
    for module in cfg['modules']:
        chalk.green('loading {}...'.format(module))
        # Load and instantiate the extension module
        ext[module] = [importlib.import_module(module)]
        ext[module].append(ext[module][0].Extension())

    server.ext = ext

    chalk.green('lidard ready, protocol v2')

    @atexit.register
    def close():
        chalk.blue('shutting down')
        server.server_close()

    server.serve_forever()