Example #1
0
def print_stat(name, now_val, avg_val, num_f=3, color=cyan):
        
    format_str = '{:.%df}' % num_f

    now_str = cyan(format_str.format(now_val))
    avg_str = cyan(format_str.format(avg_val))

    return f'{name} {now_str} ({avg_str})\t'
Example #2
0
def show(limit, concurrency):
    click.echo(hue.bg(hue.cyan(
        f'Crawling {limit} city(ies) with concurrency {concurrency}')))
    cities_links = get_google_search_cities_links(limit=limit)

    google_climatempo_scraper = GoogleClimaTempoCityLinkScraper(driver_name='phantomjs')
    google_climatempo_crawler = Crawler(
        scraper=google_climatempo_scraper,
        concurrency=concurrency)
    google_climatempo_crawler.crawl(cities_links)

    climatempo_links = google_climatempo_crawler.iterdata()

    climatempo_metric_scraper = ClimaTempoMetricScraper(driver_name='phantomjs')
    climatempo_metric_crawler = Crawler(
        scraper=climatempo_metric_scraper,
        concurrency=concurrency)
    climatempo_metric_crawler.crawl(climatempo_links)

    climatempo_metrics = climatempo_metric_crawler.iterdata()

    table = beautifultable.BeautifulTable(max_width=120)
    table.column_headers = [
        'City', 'State', 'Month',
        'Min. Temp. (˚C)', 'Max. Temp. (˚C)',
        'Rain (mm)',
    ]
    for metric in climatempo_metrics:
        table.append_row([
            metric.city, metric.state,
            metric.month, metric.min_temp,
            metric.max_temp, metric.rain,
        ])
    print(table)
Example #3
0
 def __str__(self):
     unit_name = "Ship" if self.ship_health else "Crew"
     health = self.ship_health or self.crew_health
     return "{} #{} ({} {}, {} {}, {} {})".format(
         unit_name, self.id, yellow("Gold:"), self.gold, cyan("Health:"),
         health, lightpurple("Crew:"), self.crew
     )
Example #4
0
def youdao_api(words: str):
    print()
    url = ("http://fanyi.youdao.com/openapi.do?keyfrom={}&key={}&"
           "type=data&doctype=json&version=1.1&q={}")
    try:
        resp = requests.get(url.format(CONF.youdao_key_from, CONF.youdao_key,
                                       words),
                            headers=HEADERS).json()
        phonetic = ""
        basic = resp.get("basic", None)
        if basic and resp.get("basic").get("phonetic"):
            phonetic += huepy.purple("  [ " + basic.get("phonetic") + " ]")

        print(" " + words + phonetic + huepy.grey("  ~  fanyi.youdao.com"))
        print()

        translation = resp.get("translation", [])
        if len(translation) > 0:
            print(" - " + huepy.green(translation[0]))

        if basic and basic.get("explains", None):
            for item in basic.get("explains"):
                print(huepy.grey(" - ") + huepy.green(item))
        print()

        web = resp.get("web", None)
        if web and len(web):
            for i, item in enumerate(web):
                print(
                    huepy.grey(" " + str(i + 1) + ". " +
                               highlight(item.get("key"), words)))
                print("    " + huepy.cyan(", ".join(item.get("value"))))

    except Exception:
        print(" " + huepy.red(ERR_MSG))
Example #5
0
File: fy.py Project: coderMR/fy
def command_line_runner():
    parser = get_parser()
    args = vars(parser.parse_args())

    words = " ".join(args["words"])

    if args["version"]:
        print(huepy.cyan("fy " + __version__))
        return

    if args["reset"]:
        generate_config(True)
        return

    if args["shell"]:
        query_prompt_shell()
        return

    if args["records"]:
        records_prompt_shell()
        return

    if not args["words"]:
        parser.print_help()
        return

    run(words)
Example #6
0
def colorize_option(chave, valor):
	'''
	Based on index type format and print out menu options.
	'''
	if type(chave) == int:
		selector = cyan(' [') + bold(cyan('%s')) + cyan('] ')
		suffix = cyan('%s\n') 
		return selector % chave + suffix % valor
	if type(chave) == str:
		pos = valor.lower().find(chave)
		prefix, radical, suffix = valor.partition(valor[pos])
		if prefix:
			prefix = cyan('%s')
		radical = cyan('[') + bold(cyan('%s' % radical))+ cyan(']')
		return ' %s%s%s\n' % (prefix, radical, suffix)
Example #7
0
File: fy.py Project: coderMR/fy
def google_api(words: str):
    print()

    def switch_language():
        for w in words:
            if "\u4e00" <= w <= "\u9fff":
                return "en"
        return "zh-cn"

    translator = Translator(service_urls=["translate.google.cn"])
    text = pangu.spacing_text(translator.translate(words, dest=switch_language()).text)
    print(" " + words + huepy.grey("  ~  translate.google.cn"))
    print()
    print(" - " + huepy.cyan(text))
Example #8
0
def iciba_api(words: str):
    print()
    print(huepy.grey(" -------- "))
    print()
    url = "http://dict-co.iciba.com/api/dictionary.php?key={key}&w={w}&type={type}"
    try:
        resp = requests.get(url.format(key=CONF.iciba_key, w=words,
                                       type="xml"))
        resp.encoding = "utf8"

        dct = xmltodict.parse(resp.text).get("dict")
        ps = dct.get("ps") or ""
        print(" " + words + "  " + huepy.purple(ps) +
              huepy.grey("  ~  iciba.com"))
        print()

        pos = dct.get("pos")
        acceptation = dct.get("acceptation")
        if pos and acceptation:
            if not isinstance(pos, list) and not isinstance(acceptation, list):
                pos = [pos]
                acceptation = [acceptation]
            for p, a in zip([i for i in pos], [i for i in acceptation]):
                if a and p:
                    print(" - " + huepy.green(p + " " + a))
            print()

        index = 1
        sent = dct.get("sent")
        if not sent:
            return
        if not isinstance(sent, list):
            sent = [sent]
        for item in sent:
            for k, v in item.items():
                if k == "orig":
                    print(
                        highlight(huepy.grey(" {}. ".format(index) + v),
                                  words))
                    index += 1
                elif k == "trans":
                    print(highlight(huepy.cyan("    " + v), words))
        print()
    except Exception:
        print(" " + huepy.red(ERR_MSG))
Example #9
0
    def destruct_response(cls, response: ty.Dict[str, ty.Any]) -> VKAPIError:
        """Разбирает ответ от вк про некорректный API запрос
        на части и инициализирует сам объект исключения

        Args:
          response: ty.Dict[str:
          ty.Any]:
          response: ty.Dict[str:

        Returns:

        """
        status_code = response["error"].pop("error_code")
        description = response["error"].pop("error_msg")
        request_params = response["error"].pop("request_params")
        request_params = {
            item["key"]: item["value"]
            for item in request_params
        }

        pretty_exception_text = (huepy.red(f"\n[{status_code}]") +
                                 f" {description}\n\n" +
                                 huepy.grey("Request params:"))

        for key, value in request_params.items():
            key = huepy.yellow(key)
            value = huepy.cyan(value)
            pretty_exception_text += f"\n{key} = {value}"

        # Если остались дополнительные поля
        if response["error"]:
            pretty_exception_text += (
                "\n\n" + huepy.info("There are some extra fields:\n") +
                str(response["error"]))

        return cls(
            pretty_exception_text=pretty_exception_text,
            description=description,
            status_code=status_code,
            request_params=request_params,
            extra_fields=response["error"],
        )
Example #10
0
def main_menu():
	print(cyan('\n Select an option\n'))
	net_menu = build_menu(menu_sites, SF_PROMPT, False)
	return build_menu(menu_sites[net_menu], SF_PROMPT)	
Example #11
0
		"LinkedIn",
		"Twitter",
		"Instagram",
		"Snapchat",
		"FbRobotCaptcha",
		"VK",
		"Github",
	},
	"Others": {
		"StackOverflow",
		"Wordpress",
		"Steam",
	}
}

SF_PROMPT = cyan(" SF > ")

def colorize_option(chave, valor):
	'''
	Based on index type format and print out menu options.
	'''
	if type(chave) == int:
		selector = cyan(' [') + bold(cyan('%s')) + cyan('] ')
		suffix = cyan('%s\n') 
		return selector % chave + suffix % valor
	if type(chave) == str:
		pos = valor.lower().find(chave)
		prefix, radical, suffix = valor.partition(valor[pos])
		if prefix:
			prefix = cyan('%s')
		radical = cyan('[') + bold(cyan('%s' % radical))+ cyan(']')