Python colorama.Fore.GREEN Examples

The following are 30 code examples of colorama.Fore.GREEN(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module colorama.Fore , or try the search function .
Example #1
Source File: login.py    From maubot with GNU Affero General Public License v3.0 7 votes vote down vote up
def login(server, username, password, alias) -> None:
    data = {
        "username": username,
        "password": password,
    }
    try:
        with urlopen(f"{server}/_matrix/maubot/v1/auth/login",
                     data=json.dumps(data).encode("utf-8")) as resp_data:
            resp = json.load(resp_data)
            config["servers"][server] = resp["token"]
            if not config["default_server"]:
                print(Fore.CYAN, "Setting", server, "as the default server")
                config["default_server"] = server
            if alias:
                config["aliases"][alias] = server
            save_config()
            print(Fore.GREEN + "Logged in successfully")
    except HTTPError as e:
        try:
            err = json.load(e)
        except json.JSONDecodeError:
            err = {}
        print(Fore.RED + err.get("error", str(e)) + Fore.RESET) 
Example #2
Source File: cb_tools.py    From Forager with MIT License 7 votes vote down vote up
def run_feed_server():
    #stands up the feed server, points to the CB/json_feeds dir
    chdir('data/json_feeds/')
    port = 8000
    handler = http.server.SimpleHTTPRequestHandler
    httpd = socketserver.TCPServer(("", port), handler)

    try:
        print((Fore.GREEN + '\n[+]' + Fore.RESET), end=' ')
        print(('Feed Server listening at http://%s:8000' % gethostname()))
        httpd.serve_forever()
    except:
        print((Fore.RED + '\n[-]' + Fore.RESET), end=' ')
        print("Server exited")

    return 
Example #3
Source File: cloudfail.py    From CloudFail with MIT License 6 votes vote down vote up
def crimeflare(target):
    print_out(Fore.CYAN + "Scanning crimeflare database...")

    with open("data/ipout", "r") as ins:
        crimeFoundArray = []
        for line in ins:
            lineExploded = line.split(" ")
            if lineExploded[1] == args.target:
                crimeFoundArray.append(lineExploded[2])
            else:
                continue
    if (len(crimeFoundArray) != 0):
        for foundIp in crimeFoundArray:
            print_out(Style.BRIGHT + Fore.WHITE + "[FOUND:IP] " + Fore.GREEN + "" + foundIp.strip())
    else:
        print_out("Did not find anything.") 
Example #4
Source File: stock.py    From Jarvis with MIT License 6 votes vote down vote up
def get_profile(self, jarvis, symbol):
        ''' Given a stock symbol get the company profile '''
        url = 'https://financialmodelingprep.com/api/v3/company/profile/' + symbol
        resp = requests.get(url)

        if(resp.status_code == 200):
            data = resp.json()
            if(not data):
                jarvis.say("Cannot find details for " + symbol, Fore.RED)
            else:
                jarvis.say(" Symbol      : " + data['symbol'], Fore.GREEN)
                jarvis.say(" Company     : " + data['profile']['companyName'], Fore.GREEN)
                jarvis.say(" Industry    : " + data['profile']['industry'], Fore.GREEN)
                jarvis.say(" Sector      : " + data['profile']['sector'], Fore.GREEN)
                jarvis.say(" Website     : " + data['profile']['website'], Fore.GREEN)
                jarvis.say(" Exchange    : " + data['profile']['exchange'], Fore.GREEN)
                jarvis.say(" Description : " + data['profile']['description'], Fore.GREEN)

        else:
            jarvis.say("Cannot find details for " + symbol, Fore.RED) 
Example #5
Source File: stock.py    From Jarvis with MIT License 6 votes vote down vote up
def get_gainers(self, jarvis):
        ''' Get the most gainers of the day '''
        url = 'https://financialmodelingprep.com/api/v3/stock/gainers'
        resp = requests.get(url)

        if(resp.status_code == 200):
            data = resp.json()
            if(not data):
                jarvis.say("Cannot find details at this moment.", Fore.RED)
            else:
                for gainer in data['mostGainerStock']:
                    jarvis.say(gainer['ticker'] + " | " + gainer['companyName'], Fore.GREEN)
                    jarvis.say("Price: " + str(gainer['price']) + " | Change: " + str(gainer['changes']), Fore.GREEN)
                    jarvis.say("Percent gained: " + str(gainer['changesPercentage'])[1:-1] + "\n\n", Fore.GREEN)
        else:
            jarvis.say("Cannot get gainers list at the moment") 
Example #6
Source File: stock.py    From Jarvis with MIT License 6 votes vote down vote up
def get_losers(self, jarvis):
        ''' Get the most losers of the day '''
        url = 'https://financialmodelingprep.com/api/v3/stock/losers'
        resp = requests.get(url)

        if(resp.status_code == 200):
            data = resp.json()
            if(not data):
                jarvis.say("Cannot find details at the moment.", Fore.RED)
            else:
                for loser in data['mostLoserStock']:
                    jarvis.say(loser['ticker'] + " | " + loser['companyName'], Fore.GREEN)
                    jarvis.say("Price: " + str(loser['price']) + " | Change: " + str(loser['changes']), Fore.GREEN)
                    jarvis.say("Percent lost: " + str(loser['changesPercentage'])[1:-1] + "\n\n", Fore.GREEN)
        else:
            jarvis.say("Cannot get losers list at the moment") 
Example #7
Source File: workout.py    From Jarvis with MIT License 6 votes vote down vote up
def workout(jarvis, s):
    """Provides a workout programm according to user's abilities
    Formula to generate a relevant program is taken from:
    https://www.gbpersonaltraining.com/how-to-perform-100-push-ups/"""
    s = jarvis.input(
        "Choose an exercise. Write 'push' for pushups, 'pull' for pullups and 'q' for quit\n", Fore.GREEN)
    if (s == "'q'" or s == "q"):
        quit(jarvis)
    elif (s == "'push'" or s == "push"):
        s = jarvis.input(
            "How many times can you push up? Please enter an integer!\n", Fore.GREEN)
        pushups(jarvis, s)
    elif (s == "'pull'" or s == "pull"):
        s = jarvis.input(
            "How many times can you pull up? Please enter an integer!\n", Fore.GREEN)
        pullups(jarvis, s)
    else:
        jarvis.say(
            "Incorrect input, please write either 'push' or 'pull'", Fore.BLUE)
        quit(jarvis) 
Example #8
Source File: news.py    From Jarvis with MIT License 6 votes vote down vote up
def get_headlines(self, jarvis):
        """
            gets top headlines for a quick lookup of the world news, based on the news channel of the user (if it exists)
        """
        sources = self.get_news_sources(jarvis)

        if len(sources) == 0:
            jarvis.say(
                "You have not configured any source. Getting top headlines\n",
                Fore.GREEN)
            url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=" + \
                self.get_api_key(jarvis)
        else:
            url = "https://newsapi.org/v2/top-headlines?sources="
            for source in sources:
                url += source + ","
            url += "&apiKey=" + self.get_api_key(jarvis)
        return self._get(jarvis, url) 
Example #9
Source File: build.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def build(path: str, output: str, upload: bool, server: str) -> None:
    meta = read_meta(path)
    if not meta:
        return
    if output or not upload:
        output = read_output_path(output, meta)
        if not output:
            return
    else:
        output = BytesIO()
    os.chdir(path)
    write_plugin(meta, output)
    if isinstance(output, str):
        print(f"{Fore.GREEN}Plugin built to {Fore.CYAN}{output}{Fore.GREEN}.{Fore.RESET}")
    else:
        output.seek(0)
    if upload:
        upload_plugin(output, server) 
Example #10
Source File: stock.py    From Jarvis with MIT License 6 votes vote down vote up
def get_stock_id(self, jarvis, name):
        ''' Get the list of stock IDs given a company name or part of the company name '''
        url = 'https://financialmodelingprep.com/api/v3/company/stock/list'
        resp = requests.get(url)

        if(resp.status_code == 200):
            data = resp.json()
            found = False

            # Add try block. Somtimes the endpoint does not work or has unexcepted behaviour
            try:
                for stock in data['symbolsList']:
                    if(re.match(name.lower(), stock['name'].lower())):
                        found = True
                        jarvis.say(stock['symbol'] + "\t\t" + stock['name'], Fore.GREEN)

                if not found:
                    jarvis.say("The given name could not be found\n", Fore.RED)
            except KeyError:
                jarvis.say("The endpoint is not working at the moment. Try again later", Fore.RED)
        else:
            jarvis.say("Cannot find the name at this time. Try again later\n", Fore.RED) 
Example #11
Source File: cli.py    From Bast with MIT License 6 votes vote down vote up
def make_key(path):
    env_path = os.path.join(path, '.env')

    key = b64encode(os.urandom(32)).decode('utf-8')
    with open(env_path, 'r') as file:
        env_data = file.readlines()

    for line_number, line in enumerate(env_data):
        if line.startswith('APP_KEY='):
            env_data[line_number] = 'APP_KEY={0}\n'.format(key)
            break

    with open(env_path, 'w') as file:
        file.writelines(env_data)

    click.echo(Fore.GREEN + "Key Generated successfully: " + key) 
Example #12
Source File: tools.py    From Forager with MIT License 6 votes vote down vote up
def update_progress(progress):
    barLength = 20  # Modify this value to change the length of the progress bar
    status = ""
    if isinstance(progress, int):
        progress = float(progress)
    if not isinstance(progress, float):
        progress = 0
        status = "error: progress var must be float\r\n"
    if progress < 0:
        progress = 0
        status = Fore.RED + "Halt!\r\n"
    if progress >= .999:
        progress = 1
        status = Fore.GREEN + " Complete!\r\n"
    block = int(round(barLength*progress))
    text = "\r[*] Progress: [{0}] {1}% {2}".format("#"*block + "-"*(barLength-block), round(progress*100), status)
    sys.stdout.write(text)
    sys.stdout.flush() 
Example #13
Source File: core.py    From shellpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def exe(cmd, params):
    """This function runs after preprocessing of code. It actually executes commands with subprocess

    :param cmd: command to be executed with subprocess
    :param params: parameters passed before ` character, i.e. p`echo 1 which means print result of execution
    :return: result of execution. It may be either Result or InteractiveResult
    """

    global _colorama_intialized
    if _is_colorama_enabled() and not _colorama_intialized:
        _colorama_intialized = True
        colorama.init()

    if config.PRINT_ALL_COMMANDS:
        if _is_colorama_enabled():
            _print_stdout(Fore.GREEN + '>>> ' + cmd + Style.RESET_ALL)
        else:
            _print_stdout('>>> ' + cmd)

    if _is_param_set(params, _PARAM_INTERACTIVE):
        return _create_interactive_result(cmd, params)
    else:
        return _create_result(cmd, params) 
Example #14
Source File: ginnoptimizer.py    From galera_innoptimizer with GNU General Public License v2.0 6 votes vote down vote up
def print_color(mtype, message=''):
    """@todo: Docstring for print_text.

    :mtype: set if message is 'ok', 'updated', '+', 'fail' or 'sub'
    :type mtype: str
    :message: the message to be shown to the user
    :type message: str

    """

    init(autoreset=False)
    if (mtype == 'ok'):
        print(Fore.GREEN + 'OK' + Fore.RESET + message)
    elif (mtype == '+'):
        print('[+] ' + message + '...'),
    elif (mtype == 'fail'):
        print(Fore.RED + "\n[!]" + message)
    elif (mtype == 'sub'):
        print(('  -> ' + message).ljust(65, '.')),
    elif (mtype == 'subsub'):
        print("\n    -> " + message + '...'),
    elif (mtype == 'up'):
        print(Fore.CYAN + 'UPDATED') 
Example #15
Source File: output.py    From drydock with GNU General Public License v2.0 6 votes vote down vote up
def print_results(self,results):
    try:
      if results['status'] == 'Pass':
        print ("Status: " + Fore.GREEN + 'Pass' + Fore.RESET)
      elif results['status'] == 'Fail':
        print ("Status: " + Fore.RED + 'Fail' + Fore.RESET)
    except KeyError:
      pass
    except TypeError:
      pass
    print "Description: " + results['descr']
    try:
      res = str(results['output'])
      print "Output: "
      print(Style.DIM + res + Style.RESET_ALL)
    except KeyError:
      pass
    print "\n" 
Example #16
Source File: logs.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def watch(self, raw_args):
        def tail(_file):
            _file.seek(0, 2)      # Go to the end of the file
            while True:
                line = _file.readline()
                if not line:
                    time.sleep(0.1)
                    continue
                yield line

        _file = open(_log_path, 'r')
        print(Fore.GREEN + '[bitmask] ' +
              Fore.RESET + 'Watching log file %s' % _log_path)
        for line in _file.readlines():
            print line,
        for line in tail(_file):
            print line, 
Example #17
Source File: output.py    From h2t with MIT License 6 votes vote down vote up
def print_line(message, level=1, category = None, title = None, status=False):
    sts = get_status(category, status)

    if sts == 'applied':
        color = Fore.GREEN
        pre = '[+] '
    elif sts == 'touse':
        color = Fore.YELLOW
        pre = '[+] '
    elif sts == 'toremove':
        color = Fore.RED
        pre = '[-] '
    else:
        color = ''
        pre = ''

    if title:
        print(' '*4*level + Style.BRIGHT + title + ': ' + Style.RESET_ALL + message)
    else:
        print(' '*4*level + color + Style.BRIGHT + pre + Fore.RESET + message) 
Example #18
Source File: cli.py    From Bast with MIT License 6 votes vote down vote up
def controller_creatr(filename):
    """Name of the controller file to be created"""

    path = os.path.abspath('.') + '/controller'
    if not os.path.exists(path):
        os.makedirs(path)

    # if os.path.isfile(path + )

    file_name = str(filename + '.py')
    if os.path.isfile(path + "/" + file_name):
        click.echo(Fore.WHITE + Back.RED + "ERROR: Controller file exists")
        return
    controller_file = open(os.path.abspath('.') + '/controller/' + file_name, 'w+')
    compose = "from bast import Controller\n\nclass " + filename + "(Controller):\n    pass"
    controller_file.write(compose)
    controller_file.close()
    click.echo(Fore.GREEN + "Controller " + filename + " created successfully") 
Example #19
Source File: cli.py    From Bast with MIT License 6 votes vote down vote up
def create_model(model_file, migration):
    filename = snake_case(model_file) + ".py"

    directory_path = os.path.abspath('.') + '/models/'
    if not os.path.exists(directory_path):
        os.makedirs(directory_path)

    path = os.path.abspath('.') + '/models/' + filename
    file_open = open(path, 'w+')
    compose = 'from bast import Models\n\nclass %s(Models):\n    __table__ = \'%s\'' \
              % (model_file, snake_case(model_file))
    file_open.write(compose)
    file_open.close()
    if migration:
        migrate = CreateMigration()
        migrate.create_file(name=snake_case(model_file), table=snake_case(model_file), create=True)
    click.echo(Fore.GREEN + '%s has been created at /models' % filename) 
Example #20
Source File: output.py    From drydock with GNU General Public License v2.0 5 votes vote down vote up
def terminal_output(self):
    output = self.log
    tempdict = {}
    auditcats = {'host': '1.Host Configuration',
                 'dockerconf': '2.Docker Daemon Configuration',
                 'dockerfiles': '3.Docker daemon configuration files',
                 'container_imgs': '4.Container Images and Build File',
                 'container_runtime': '5.Container Runtime',
                 }

    print '''drydock v0.3 Audit Results\n==========================\n'''
    # Print results
    for cat, catdescr in auditcats.iteritems():
      cat_inst = self.audit_categories[cat]
      try:
        if output[cat]:
          audits = self.create_ordereddict(output[cat],cat)
          print(Style.BRIGHT + "\n" + catdescr + "\n" + \
                '-'*len(catdescr) + '\n'+ Style.RESET_ALL)
          for audit in audits.keys():
            results = output[cat][audit]
            descr = getattr(cat_inst,audit).__doc__
            print( descr + '\n' + '-'*len(descr) )
            self.print_results(results)
      except KeyError:
        logging.warn("No audit category %s" %auditcats[cat])
        continue

    # Print Overview info for the audit
    print(Style.BRIGHT + "Overview\n--------" +Style.RESET_ALL)
    print('Profile: ' + output['info']['profile'])
    print('Date: ' + output['info']['date'])
    success,total = output['info']['score'].split('/')
    success = float(success)
    total = float(total)
    if 0 <= success/total <= 0.5:
      print('Score: ' + Fore.RED + output['info']['score'] + Fore.RESET)
    elif 0.5 < success/total <= 0.8:
      print('Score: ' + Fore.YELLOW + output['info']['score'] + Fore.RESET)
    else:
      print('Score: ' + Fore.GREEN + output['info']['score'] + Fore.RESET) 
Example #21
Source File: model.py    From Bast with MIT License 5 votes vote down vote up
def check_packages(db_name):
        print(Fore.GREEN + 'Checking for required Database Driver')

        reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
        installed_packages = [r.decode().split('==')[0] for r in reqs.split()]

        if db_name.lower() == 'mysql':
            if 'PyMySQL' not in installed_packages:
                print(Fore.GREEN + 'Installing required Database Driver')
                subprocess.call(['pip', 'install', 'pymysql'])

        if db_name.lower() == 'postgresql':
            if 'psycopg2' not in installed_packages:
                print(Fore.GREEN + 'Installing required Database Driver')
                subprocess.call(['pip', 'install', 'psycopg2']) 
Example #22
Source File: diff.py    From dcos-deploy with Apache License 2.0 5 votes vote down vote up
def color_diff_line(line):
    if line.startswith('+') and not line.startswith('+++'):
        return Fore.GREEN + line + Fore.RESET
    elif line.startswith('-') and not line.startswith('---'):
        return Fore.RED + line + Fore.RESET
    elif line.startswith('@@'):
        return Fore.BLUE + line + Fore.RESET
    else:
        return line 
Example #23
Source File: workout.py    From Jarvis with MIT License 5 votes vote down vote up
def pushups(jarvis, s):
    try:
        maximum = int(s)
    except:
        jarvis.say("Please enter an integer only!", Fore.BLUE)
        quit(jarvis)
        return
    if(maximum < 15):
        jarvis.say(
            "Firstly, try to reach your maximum to at least 15, then call me again!", Fore.BLUE)
        quit(jarvis)
        return
    num = push_compute_num(maximum, jarvis)
    rest = push_compute_rest(maximum)
    jarvis.say("Your program for today is [" + str(num + 2) + ", " + str(num + 1) + ", " + str(num) + ", " + str(
        num - 1) + ", " + str(num - 2) + "] and " + str(rest) + " sec rest in between", Fore.BLUE)
    s = jarvis.input("Type 's' to start and 'q' for quit\n", Fore.GREEN)
    if (s == "'q'" or s == "q"):
        quit(jarvis)
    elif (s == "'s'" or s == "s"):
        for i in range(1, 6):
            notify("Start Set " + str(i), "Do " + str(num + 3 - i) +
                   " pushups", urgency=NOTIFY_NORMAL)
            jarvis.say("Start Set " + str(i) + " - Do " +
                       str(num + 3 - i) + " pushups", Fore.BLUE)
            jarvis.input("Press enter after finishing", Fore.GREEN)
            jarvis.say("Rest: " + str(rest) + " sec...", Fore.BLUE)
            jarvis.say(
                "I will notice you when to start the next set", Fore.BLUE)
            timer(rest)
        jarvis.say("Well done, you performed " +
                   str(num * 5) + " pushups", Fore.BLUE)
        quit(jarvis)
    else:
        jarvis.say(
            "Incorrect input, please write either 'push' or 'pull'", Fore.BLUE)
        quit(jarvis) 
Example #24
Source File: output.py    From h2t with MIT License 5 votes vote down vote up
def help():
    print('''Output explanation:
    {b}{g}[+]{reset} Good headers. Already used in your website. Good job!
    {b}{y}[+]{reset} Good headers. We recommend applying it
    {b}{r}[-]{reset} Bad headers. We recommend remove it\n'''.format(b=Style.BRIGHT, g=Fore.GREEN, y=Fore.YELLOW, r=Fore.RED, reset=Style.RESET_ALL)) 
Example #25
Source File: binarly_query.py    From binarly-query with MIT License 5 votes vote down vote up
def process_classify(options):
    if os.path.exists(options.files[0]):
        filelist = options.files
        if os.path.isdir(options.files[0]):
            filelist = get_filelist(filelist[0])

        result = BINOBJ.classify_files(
            filelist, upload_missing=options.u, status_callback=my_callback)
    else:
        result = BINOBJ.classify_hashes(options.files)

    if 'error' in result or result['status'] != 'done':
        print(Style.BRIGHT + Fore.RED + "Request failed")
    else:
        print("Classification Results:")

    reqid = result.get('results', None)
    if reqid is None:
        # the request failed before any files could be analyzed
        print(Style.BRIGHT + Fore.RED +
              "Fail reason: {0} (error code={1})".format(
                  result['error']['message'], result['error']['code']))
        return

    classify_data = []
    for key, value in result['results'].iteritems():
        status = Style.RESET_ALL + Fore.GREEN + "OK" + Style.RESET_ALL
        if 'error' in value:
            status = Fore.RED + value['error']['message'] + Style.RESET_ALL
        row = {'SHA1': key, 'label': value.get('label', '.'), 'family': value.get('family', '.'), 'Status': status}

        classify_data.append(row)

    if options.pretty_print:
        show_results(classify_data, pretty_print=options.pretty_print)
    else:
        print("-" * 100)
        for row in classify_data:
            show_row(row)
    return 
Example #26
Source File: stock.py    From Jarvis with MIT License 5 votes vote down vote up
def __call__(self, jarvis, s):
        if not s or 'help' in s:
            jarvis.say(cleandoc(self.__doc__), Fore.GREEN)
        else:
            ps = s.split()
            if ps[0] == 'getid':
                ps.pop(0)
                if ps:
                    name = ' '.join(ps)
                else:
                    name = jarvis.input("Enter the name of the stock: ")
                self.get_stock_id(jarvis, name)
            elif ps[0] == 'profile':
                if(len(ps) != 2):
                    jarvis.say("You forgot to mention the symbol", Fore.RED)
                else:
                    symbol = ps[1]
                    self.get_profile(jarvis, symbol)
            elif ps[0] == 'fstatement':
                if(len(ps) != 2):
                    jarvis.say("You forgot to mention the symbol", Fore.RED)
                else:
                    symbol = ps[1]
                    self.get_financial_stmt(jarvis, symbol)
            elif ps[0] == 'gainers':
                self.get_gainers(jarvis)
            elif ps[0] == 'losers':
                self.get_losers(jarvis)
            # anything else is treated as a stock symbol
            else:
                self.get_stock_data(jarvis, s) 
Example #27
Source File: basketball.py    From Jarvis with MIT License 5 votes vote down vote up
def get_api_key(self, jarvis):
        m = Memory("basketball.json")
        if m.get_data("API_KEY") is None:
            user_api_key = jarvis.input("Enter Api-BasketBall.com API_KEY: ", Fore.GREEN)
            m.add_data("API_KEY", user_api_key)
            m.save()
            self.key = user_api_key
        else:
            self.key = m.get_data("API_KEY") 
Example #28
Source File: news.py    From Jarvis with MIT License 5 votes vote down vote up
def remove_source(self, jarvis):
        """
            removes a new source from the news channel of the user
        """
        sources = self.get_news_sources(jarvis)

        dic = {}
        for source in sources:
            dic[str(sources.index(source) + 1)] = source

        for index in sorted([int(x) for x in dic.keys()]):
            jarvis.say(str(index) + " : " + dic[str(index)])
        index_list = jarvis.input(
            "Type the indexes of the sources you would like to remove from your channel separated by "
            "space: ")
        index_list = index_list.split(" ")
        if " " in index_list:
            index_list.remove(" ")
        if "" in index_list:
            index_list.remove("")
        for index in index_list:
            if str(index) in dic:
                source = dic[str(index)]
                sources.remove(source)
                jarvis.update_data("news-sources", sources)
                jarvis.say(
                    source
                    + " has been successfully removed from your news channel!",
                    Fore.GREEN)
            else:
                jarvis.say("Index not found!", Fore.RED)
        return self.get_news_sources(jarvis) 
Example #29
Source File: corona.py    From Jarvis with MIT License 5 votes vote down vote up
def __call__(self, jarvis, s):
        if 'help' in s:
            jarvis.say(cleandoc(self.__doc__), Fore.GREEN)
        else:
            corona_info = self.get_corona_info(s)
            if corona_info == "URLError":
                jarvis.say(f"Result was not available at the moment. Try again!!", Fore.RED)
            elif corona_info is None:
                jarvis.say(f"Cant find the country \"{s}\"", Fore.RED)
            else:
                location = corona_info["Country"]
                jarvis.say(f"\t+++++++++++++++++++++++++++++++++++++++", Fore.CYAN)
                jarvis.say(f"\tCorona status: \"{location}\"", Fore.CYAN)
                jarvis.say(f"\t+++++++++++++++++++++++++++++++++++++++", Fore.CYAN)

                new_confirmed = corona_info["NewConfirmed"]
                jarvis.say(f"\tNew confirmed cases	: {new_confirmed}", Fore.YELLOW)

                total_confirmed = corona_info["TotalConfirmed"]
                jarvis.say(f"\tTotal confirmed cases	: {total_confirmed}", Fore.YELLOW)

                new_deaths = corona_info["NewDeaths"]
                jarvis.say(f"\tNew deaths		: {new_deaths}", Fore.RED)

                total_deaths = corona_info["TotalDeaths"]
                jarvis.say(f"\tTotal deaths		: {total_deaths}", Fore.RED)

                new_recovered = corona_info["NewRecovered"]
                jarvis.say(f"\tNew recovered		: {new_recovered}", Fore.GREEN)

                total_recovered = corona_info["TotalRecovered"]
                jarvis.say(f"\tTotal recovered		: {total_recovered}", Fore.GREEN) 
Example #30
Source File: workout.py    From Jarvis with MIT License 5 votes vote down vote up
def pullups(jarvis, s):
    try:
        maximum = int(s)
    except:
        jarvis.say("Please enter an integer only!", Fore.BLUE)
        quit(jarvis)
        return
    if(maximum < 7):
        jarvis.say(
            "Firstly, try to reach your maximum to at least 7, then call me again!", Fore.BLUE)
        quit(jarvis)
        return
    num = pull_compute_num(maximum, jarvis)
    rest = pull_compute_rest(maximum)
    jarvis.say("Your program for today is [" + str(num + 2) + ", " + str(num + 1) + ", " + str(num) + ", " + str(
        num - 1) + ", " + str(num - 2) + "] and " + str(rest) + " sec rest in between", Fore.BLUE)
    s = jarvis.input("Type 's' to start and 'q' for quit\n", Fore.GREEN)
    if (s == "'q'" or s == "q"):
        quit(jarvis)
    elif (s == "'s'" or s == "s"):
        for i in range(1, 6):
            if (num + 3 - i == 0):
                break
            notify("Start Set " + str(i), "Do " + str(num + 3 - i) +
                   " pullups", urgency=NOTIFY_NORMAL)
            jarvis.say("Start Set " + str(i) + " - Do " +
                       str(num + 3 - i) + " pullups", Fore.BLUE)
            jarvis.input("Press enter after finishing", Fore.GREEN)
            jarvis.say("Rest: " + str(rest) + " sec...", Fore.BLUE)
            jarvis.say(
                "I will notice you when to start the next set", Fore.BLUE)
            timer(rest)
        jarvis.say("Well done, you performed " +
                   str(num * 5) + " pullups", Fore.BLUE)
        quit(jarvis)
    else:
        jarvis.say("Incorrect input, please write either 'push' or 'pull'")
        quit(jarvis)