def get_badge(handle, website): q = None or request.args.get('logo') display_logo = True if (q and q.lower() == 'true') else False logo = logos[website] link = None or request.args.get('link') display_link = True if (len(str(link)) > 4) else False x = get_info(handle, website) rating, color = str(x[0]), str(x[1]) text = website_text[website.lower()] if display_logo: if display_link: badge = pybadges.badge(left_text=text, right_text=rating, right_color=color, logo=logo, embed_logo=True, left_link=link) else: badge = pybadges.badge( left_text=text, right_text=rating, right_color=color, logo=logo, embed_logo=True) else: if display_link: badge = pybadges.badge( left_text=text, right_text=rating, right_color=color, left_link=link) else: badge = pybadges.badge( left_text=text, right_text=rating, right_color=color) response = flask.make_response(badge) response.content_type = 'image/svg+xml' return response
def generate_topic_badges(topic_counts): """ Generate topic badges with count :param topic_counts: :return: """ # Sort topic_counts topic_counts = { k: v for k, v in sorted( topic_counts.items(), key=lambda item: item[1], reverse=True) } html = "" mean_count = int(sum(topic_counts.values()) / len(topic_counts)) for topic, count in topic_counts.items(): # Generate badge color = "red" if count < mean_count else "blue" s = badge(left_text=topic, right_text="{}".format(count), right_color=color) # Save svg svg_name = "{}.svg".format(topic.replace(" ", "_")) svg_path = os.path.join("figures", "badges") os.makedirs(svg_path, exist_ok=True) svg_path = os.path.join(svg_path, svg_name) with open(svg_path, "w") as f: f.write(s) html += "<img src='figures/badges/{}'/> ".format(svg_name) return html
def generate(self, project_name: str, period: str, left_color: str, right_color: str, left_text: str, units: str) -> Badge: project = self._project_repository.get(project_name) if project is None: raise ProjectNotFoundException(project_name) badge_data = PersonalizedBadge( ProjectName(project_name), BadgePeriod[period], BadgeStyle( left_color=BadgeColor(left_color), right_color=BadgeColor(right_color), left_text=left_text, units=BadgeUnits[units], ), ) downloads = self._get_downloads(project, badge_data.period, badge_data.style.units) s = badge( left_text=badge_data.style.left_text, right_text=downloads, left_color=badge_data.style.left_color.value, right_color=badge_data.style.right_color.value, ) return Badge(badge_data.name.name, s)
def visitor_svg() -> Response: """ Return a svg badge with latest visitor count of 'Referer' header value :return: A svg badge with latest visitor count """ req_source = identity_request_source() if not req_source: return invalid_count_resp('Missing required param: page_id') latest_count = update_counter(req_source) if not latest_count: return invalid_count_resp("Count API Failed") svg = badge(left_text="visitors", right_text=str(latest_count)) expiry_time = datetime.datetime.utcnow() - datetime.timedelta(minutes=10) headers = { 'Cache-Control': 'no-cache,max-age=0,no-store,s-maxage=0,proxy-revalidate', 'Expires': expiry_time.strftime("%a, %d %b %Y %H:%M:%S GMT") } return Response(response=svg, content_type="image/svg+xml", headers=headers)
def one_badge_image(): """Generate a badge that captures all checks.""" package_name = flask.request.args.get('package') badge_name = flask.request.args.get('badge') commit_number = badge_utils._calculate_commit_number(package_name) self, google, dependency = _get_check_results(package_name) status = _get_badge_status(self, google, dependency) color = BADGE_STATUS_TO_COLOR[status] badge_name = _format_badge_name(package_name, badge_name, commit_number) details_link = '{}{}'.format( flask.request.url_root[:-1], flask.url_for('one_badge_target', package=package_name)) badge_args = dict(left_text=badge_name, right_text=_badge_status_to_text(status), right_color=color, whole_link=details_link) if flask.current_app.config['TESTING']: response = flask.json.jsonify(**badge_args) else: badge = pybadges.badge(**badge_args) response = flask.make_response(badge) response.content_type = badge_utils.SVG_CONTENT_TYPE # https://tools.ietf.org/html/rfc2616#section-13.4 allows success responses # to be cached if no `Cache-Control` header is set. Since the content of # the image is frequently updated, caching is explicitly disabled to force # the client/cache to refetch the content on every request. response.headers['Cache-Control'] = 'no-cache' return response
def snap_details_badge(snap_name): context = _get_context_snap_details(snap_name) snap_link = flask.request.url_root + context["package_name"] # channel with safest risk available in default track snap_channel = "".join( [context["default_track"], "/", context["lowest_risk_available"]]) svg = badge( left_text=context["snap_title"], right_text=snap_channel + " " + context["version"], right_color="#0e8420", # Vanilla $color-positive left_link=snap_link, right_link=snap_link, logo=( "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' " "viewBox='0 0 32 32'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23f" "ff%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M18.03 1" "8.03l5.95-5.95-5.95-2.65v8.6zM6.66 29.4l10.51-10.51-3.21-3.18" "-7.3 13.69zM2.5 3.6l15.02 14.94V9.03L2.5 3.6zM27.03 9.03h-8.6" "5l11.12 4.95-2.47-4.95z'/%3E%3C/svg%3E"), ) return svg, 200, {"Content-Type": "image/svg+xml"}
def current_day_visitor_count_svg() -> Response: """ Return a svg badge with latest visitor count of 'repo_id' in current day only, this will NOT increase the total count of the 'repo_id' :return: A svg badge with latest visitor count in current day """ repo_id = request.args.get('repo_id') if repo_id is None or repo_id == '': return invalid_count_resp() print("repo_id = ", repo_id) conn = psycopg2.connect(environ['DATABASE_URL']) cursor = conn.cursor() visit_date = datetime.datetime.now().strftime('%Y%m%d') print('visit date is ', visit_date) new_count = 1 cursor.execute( 'SELECT id, count FROM CURRENT_DAY_COUNT_RECORD WHERE repo_id = %s and visit_date = %s', (repo_id, visit_date)) doc = cursor.fetchone() try: if doc is not None: # 0: id, 1: count original_count = doc[1] new_count = original_count + 1 cursor.execute( 'UPDATE CURRENT_DAY_COUNT_RECORD SET count = %s WHERE id = %s', (new_count, doc[0])) conn.commit() else: cursor.execute( 'INSERT INTO CURRENT_DAY_COUNT_RECORD(repo_id, count, visit_date) VALUES(%s, %s, %s)', (repo_id, new_count, visit_date)) conn.commit() except Exception as e: print('execute sql error', e) finally: cursor.close() conn.close() svg = badge(left_text="Visitors in today", right_text=str(new_count)) expiry_time = datetime.datetime.utcnow() - datetime.timedelta(minutes=10) headers = { 'Cache-Control': 'no-cache,max-age=0,no-store,s-maxage=0,proxy-revalidate', 'Expires': expiry_time.strftime("%a, %d %b %Y %H:%M:%S GMT") } return Response(response=svg, content_type="image/svg+xml", headers=headers)
def serveBadges(): badge = pybadges.badge(left_text='build', right_text='passing', right_color='#008000') response = flask.make_response(badge) response.content_type = 'image/svg+xml' return response
def coin_dpow_badge(notarized_coins_list): try: coins_notarization_info = json.loads( requests.get( "https://komodostats.com/api/notary/summary.json").content) except Exception as e: print(e) print("Creating date badge") fetch_time = datetime.now(pytz.utc) fetch_time_string = fetch_time.strftime("%d/%m/%Y %H:%M:%S UTC") dpow_date_badge = badge(left_text='dPOW status', right_text="fetched at: " + fetch_time_string, right_color="black") with open("/var/www/html/svg/" + "date_badge.svg", 'w') as f: f.write(dpow_date_badge) for coin_data in notarized_coins_list: print("Creating badge for " + coin_data["name"]) for coin_fetched_data in coins_notarization_info: if coin_data["name"] == coin_fetched_data["ac_name"]: try: minutes_since_last_nota = ( int(time.time()) - coin_fetched_data["lastnotarization"]) / 60 coin_data["minutes_since_nota"] = round( minutes_since_last_nota) except Exception as e: print(e) print(coin_data) print(coin_fetched_data) else: if int(coin_data["minutes_since_nota"]) < 144: coin_dpow_status = "active" status_color = "green" elif int(coin_data["minutes_since_nota"]) < 1440: coin_dpow_status = "irregular" status_color = "yellow" else: coin_dpow_status = "inactive" status_color = "red" dpow_status_badge = badge(left_text='dPOW status', right_text=coin_dpow_status, right_color=status_color) with open( "/var/www/html/svg/" + coin_data["name"] + "_badge.svg", 'w') as f: f.write(dpow_status_badge)
def generate_images(source_json_path, target_directory): os.makedirs(target_directory, exist_ok=True) with open(source_json_path) as f: examples = json.load(f) for example in examples: filename = os.path.join(target_directory, example.pop('file_name')) with open(filename, 'w') as f: f.write(pybadges.badge(**example))
def one_badge_image(): """Generate the badge for all the checks.""" package_name = flask.request.args.get('package') badge_name = flask.request.args.get('badge_name') is_github = False if badge_name is None: badge_name = package_name if 'github.com' in badge_name: badge_name = badge_utils.GITHUB_HEAD_NAME is_github = True commit_number = badge_utils._calculate_commit_number(package_name) force_run_check = flask.request.args.get('force_run_check') # Remove the last '/' from the url root url_prefix = flask.request.url_root[:-1] # Call the url for each badge to run the checks. This will populate the # individual caches, which are used to calculate the final image state. # Self compatibility badge requests.get(url_prefix + flask.url_for('self_compatibility_badge_image', package=package_name, force_run_check=force_run_check, commit_number=commit_number)) # Google compatibility badge requests.get(url_prefix + flask.url_for('google_compatibility_badge_image', package=package_name, force_run_check=force_run_check, commit_number=commit_number)) # Self dependency badge requests.get(url_prefix + flask.url_for('self_dependency_badge_image', package=package_name, force_run_check=force_run_check, commit_number=commit_number)) status, timestamp, _, _, _ = _get_all_results_from_cache( package_name, commit_number=commit_number) color = badge_utils.STATUS_COLOR_MAPPING[status] details_link = url_prefix + flask.url_for('one_badge_target', package=package_name) # Include the check timestamp for github head if is_github and timestamp: badge_name = '{} {}'.format(badge_name, timestamp) response = flask.make_response( pybadges.badge(left_text=badge_name, right_text=status, right_color=color, whole_link=details_link)) response.content_type = badge_utils.SVG_CONTENT_TYPE response.headers['Cache-Control'] = 'no-cache' response.add_etag() return response
def yukicoder(user): x = get_yuki(user) level, colour = x[0], x[1] badge = pybadges.badge(left_text='YukiCoder', right_text=level, right_color=colour) response = flask.make_response(badge) response.content_type = 'image/svg+xml' return response
def generate_badge(self, project_name: str) -> Badge: project = self._project_repository.get(project_name) if project is None: raise ProjectNotFoundException(project_name) downloads = self._downloads_formatter.format(project.total_downloads) s = badge(left_text="downloads", right_text=downloads, right_color="blue") return Badge(project_name, s)
def atcoder(user): # logo='https://img.atcoder.jp/assets/atcoder.png' x = get_at(user) rating, colour = x[0], x[1] badge = pybadges.badge(left_text='Atcoder', right_text=rating, right_color=colour) response = flask.make_response(badge) response.content_type = 'image/svg+xml' return response
def codechef(user): # logo='https://i.pinimg.com/originals/c5/d9/fc/c5d9fc1e18bcf039f464c2ab6cfb3eb6.jpg' x = get_cc(user) rating, colour = x[0], x[1] badge = pybadges.badge(left_text='Codechef', right_text=rating, right_color=colour) response = flask.make_response(badge) response.content_type = 'image/svg+xml' return response
def codeforces(user): # logo='https://lh3.googleusercontent.com/WsR_f03nbqW3qZjCZeXUYmnmhSWXo3hQhLX9hgl9QHydCgbXQi_VJeAwnmtuIgTHKdQ' x = get_cf(user) rating, colour = x[0], x[1] badge = pybadges.badge(left_text='Codeforces', right_text=rating, right_color=colour) response = flask.make_response(badge) response.content_type = 'image/svg+xml' return response
def run_e2e_job(distro, driver, masters, workers, hypervisors, job_type, pipeline_id, repository, branch_name, pr_number, launch_from, job_name): """Run the e2e job.""" output = 0 badge_text = "%s-%s-%s-%s-%s-%s" % (distro, driver, masters, workers, hypervisors, launch_from) badge_code = badge(left_text=badge_text, right_text='passing', right_color='green') try: print( "'launch_e2e.py' ==> We call the downstream job configuring its parameters" ) # The first parameter of the command are the variables values we might append to # the deployment command deployment_command = "%s ./ci/launch_e2e.sh %s %s %s %s %s %s %s %s %s %s" % ( str(' '.join(GH_LABELS)), str(repository), str(branch_name), str(pr_number), str(distro), str(driver), str(masters), str(workers), str(hypervisors), str(job_type), str(launch_from)) print("'launch_e2e.py' ==> The deployment command is:") print(deployment_command) launch_output = subprocess.run(deployment_command, shell=True, check=True) print("'launch_e2e.py' ==> ./ci/launch_e2e.sh output") print(launch_output) except Exception as e: print( "'launch_e2e.py' ==> An exception hapened executing Ansible, the playbook failed" ) badge_code = badge(left_text=badge_text, right_text='failure', right_color='red') print(e) output = 1 with open("/tmp/badge_status.svg", "w+") as text_file: text_file.write(badge_code) return output
def serve_badge(): """Serve a badge image based on the request query string.""" badge = pybadges.badge(left_text=flask.request.args.get('left_text'), right_text=flask.request.args.get('right_text'), left_color=flask.request.args.get('left_color'), right_color=flask.request.args.get('right_color'), logo=flask.request.args.get('logo')) response = flask.make_response(badge) response.content_type = 'image/svg+xml' return response
def invalid_count_resp(err_msg) -> Response: """ Return a svg badge with error info when cannot process repo_id param from request :return: A response with invalid request badge """ svg = badge(left_text="Error", right_text=err_msg, whole_link="https://github.com/jwenjian/visitor-badge") expiry_time = datetime.datetime.utcnow() - datetime.timedelta(minutes=10) headers = {'Cache-Control': 'no-cache,max-age=0', 'Expires': expiry_time.strftime("%a, %d %b %Y %H:%M:%S GMT")} return Response(response=svg, content_type="image/svg+xml", headers=headers)
def test_changes(self): with open(os.path.join(TEST_DIR, 'test-badges.json'), 'r') as f: examples = json.load(f) for example in examples: file_name = example.pop('file_name') with self.subTest(example=file_name): filepath = os.path.join(TEST_DIR, 'golden-images', file_name) with open(filepath, 'r') as f: golden_image = f.read() pybadge_image = pybadges.badge(**example) self.assertEqual(golden_image, pybadge_image)
def entity_badge(entity_name): package = app.store_api.get_item_details(entity_name, fields=FIELDS) if not package["default-release"]: abort(404) entity_link = request.url_root + entity_name right_text = "".join( [ package["default-release"]["channel"]["track"], "/", package["default-release"]["channel"]["risk"], " ", package["default-release"]["revision"]["version"], ] ) svg = badge( left_text=package["name"], right_text=right_text, right_color="#0e8420", left_link=entity_link, right_link=entity_link, logo=( "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' " "viewBox='0 0 64 64'%3E%3Cg fill-rule='evenodd' " "fill='none'%3E%3Cg fill-rule='nonzero'%3E%3Ccircle cy='32' " "cx='32' r='32' fill='%23fff'/%3E%3Cg transform='translate(13.622" " 5.6546)' fill='%23585858'%3E%3Ccircle cy='24.614' cx='20.307' " "r='1.9732'/%3E%3Cpath d='m22.129 20.971h-3.643v-14.571c0-3.5154" " 2.86-6.3753 6.375-6.3753 3.515-0.000025 6.375 2.8599 6.375 6." "375v3.6433h-3.643v-3.6433c0-0.7297-0.284-1.4159-0.8-1.932-0.51" "6-0.5159-1.202-0.8002-1.932-0.8002-1.506 0-2.732 1.2255-2.732 " "2.7322v14.571z'/%3E%3Cpath d='m33.968 27.346c-3.515 0-6.375-2." "859-6.375-6.375v-9.107h3.643v9.107c0 1.507 1.226 2.732 2.732 2." "732 1.507 0 2.733-1.225 2.733-2.732v-9.107h3.642v9.107c0 1.703" "-0.663 3.304-1.867 4.508s-2.805 1.867-4.508 1.867z'/%3E%3Ccircle" " cy='46.471' cx='2.093' r='1.9732'/%3E%3Cpath d='m3.9143 42.829" "h-3.6429l0.00002-20.036c0-3.515 2.86-6.375 6.3751-6.375 3.5155 0" " 6.3755 2.86 6.3755 6.375v3.643h-3.6433v-3.643c0-0.73-0.284-1." "416-0.8001-1.932-0.5159-0.516-1.2022-0.8-1.9319-0.8-1.5064 0-2." "7322 1.225-2.7322 2.732l-0.0002 20.036z'/%3E%3Cpath d='m15.754 " "43.74c-3.516 0-6.3753-2.86-6.3753-6.376v-9.107h3.6433v9.107c0 " "1.506 1.225 2.732 2.732 2.732 1.506 0 2.732-1.226 2.732-2.732v-" "9.107h3.643v9.107c0 1.703-0.663 3.304-1.867 4.508-1.205 1.204-2" ".805 1.868-4.508 1.868z'/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E" ), ) return svg, 200, {"Content-Type": "image/svg+xml"}
def main(event, context): body = json.loads(event['body']) total_coverage = body['total_coverage'] project = body['project'] branch = body['branch'] # anonymize project and branch _hash = hashlib.sha3_256((project + branch).encode()).hexdigest() # generate coverage badge if total_coverage >= 90: color = 'green' elif total_coverage >= 60: color = 'yellow' elif total_coverage >= 40: color = 'orange' else: color = 'red' svg_file_string = badge( left_text='coverage', right_text=f'{total_coverage}%', right_color=color, logo= 'https://coverage.readthedocs.io/en/coverage-5.1/_static/sleepy-snake-circle-150.png', embed_logo=True) # upload s3_client.upload_fileobj(Fileobj=BytesIO(svg_file_string.encode()), ExtraArgs={ 'ContentType': ' image/svg+xml', 'CacheControl': 'max-age=300' }, Bucket=BADGE_UPLOADER_BUCKET, Key=f"{_hash}.svg") # output return { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": json.dumps({ "url": f"https://s3.amazonaws.com/{BADGE_UPLOADER_BUCKET}/{_hash}.svg" }) }
def make_badge(self, repo_data, file_type): """ Function to make a badge for file_type using repo_data :param dict repo_data: Repo data for the user :param str file_type: File type (i.e. .py) :rtype img: :return: Badge """ # Round our number first rounded_number = float(repo_data[file_type] / 1000) rounded_number = repr(round(rounded_number, 2)) return badge(left_text=file_type[1:], right_text=f"{rounded_number}K", right_color=FILE_TYPES[file_type])
def test_changes(self): with open(os.path.join(TEST_DIR, 'test-badges.json'), 'r') as f: examples = json.load(f) for example in examples: file_name = example.pop('file_name') with self.subTest(example=file_name): filepath = os.path.join(TEST_DIR, 'golden-images', file_name) with open(filepath, mode="r", encoding="utf-8") as f: golden_image = f.read() pybadge_image = pybadges.badge(**example) diff = xmldiff.main.diff_texts(golden_image, pybadge_image) self.assertFalse(diff)
def create_badge(robotfile, file): error_count = RfLint().run(robotfile) if error_count > 0 and error_count < 5: badge_svg = badge(left_text='RFLINT', right_text='Errors count:' + str(error_count), right_color='green', logo=LOGO, embed_logo=False) convert_svg(badge_svg, file) elif error_count > 5 and error_count < 9: badge_svg = badge(left_text='RFLINT', right_text='Errors count:' + str(error_count), right_color='yellow', logo=LOGO, embed_logo=False) convert_svg(badge_svg, file) elif error_count >= 9: badge_svg = badge(left_text='RFLINT', right_text='Errors count:' + str(error_count), right_color='red', logo=LOGO, embed_logo=False) convert_svg(badge_svg, file)
def get(self, id): """ Returns the Badge with the given ID """ badgen = SQLService(id) logging.info("Get badge with ID: %s" % badgen.badgeId) if not badgen.getBadge(): api.abort(404) svg = badge(left_text=badgen.name, right_text=badgen.value, left_color=badgen.name_color, right_color=badgen.value_color) return Response(svg, mimetype='image/svg+xml')
def get(self, request, *args, **kwargs): workspace = get_object_or_404( Workspace, project__org__slug=self.kwargs["org_slug"], project__slug=self.kwargs["project_slug"], name=self.kwargs["workspace_slug"], ) published_snapshots = workspace.snapshots.exclude( published_at=None).count() s = badge( left_text="Published outputs", right_text=str(published_snapshots), right_color="#0058be", ) return HttpResponse(s, headers={"Content-Type": "image/svg+xml"})
def write_badge(self, filename, right, color): """ writes a badge to the given `filename` with `right` content and `color` background """ print("making badge: %s - %s - %s" % (filename, right, color)) outfile = os.path.join(settings.PROJECT_DIR, 'static', 'img', 'badges', filename) f = open(outfile, 'w') b = badge(left_text=LEFT_TEXT, right_text=right, right_color=color) # logo = LOGO) f.write(b) f.close()
def get_badge_svg(snap_name, left_text, right_text, color="#0e8420"): show_name = flask.request.args.get("name", default=1, type=int) snap_link = flask.request.url_root + snap_name svg = badge( left_text=left_text if show_name else "", right_text=right_text, right_color=color, left_link=snap_link, right_link=snap_link, logo=( "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' " "viewBox='0 0 32 32'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23f" "ff%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M18.03 1" "8.03l5.95-5.95-5.95-2.65v8.6zM6.66 29.4l10.51-10.51-3.21-3.18" "-7.3 13.69zM2.5 3.6l15.02 14.94V9.03L2.5 3.6zM27.03 9.03h-8.6" "5l11.12 4.95-2.47-4.95z'/%3E%3C/svg%3E"), ) return svg
def visitor_svg() -> Response: """ Return a svg badge with latest visitor count of 'Referer' header value :return: A svg badge with latest visitor count """ req_source = identity_request_source() if not req_source: return invalid_count_resp('Missing required param: page_id') latest_count = update_counter(req_source) if not latest_count: return invalid_count_resp("Count API Failed") title = request.args.get('title') if title is None or len(title) == 0: title = 'visitors' home = "https://visitor-badge.laobi.icu" svg = badge(left_text=title, right_text=str(latest_count), right_link=home, left_link=home) expiry_time = datetime.datetime.utcnow() - datetime.timedelta(minutes=10) headers = { 'Cache-Control': 'no-cache,max-age=0,no-store,s-maxage=0,proxy-revalidate', 'Expires': expiry_time.strftime("%a, %d %b %Y %H:%M:%S GMT") } return Response(response=svg, content_type="image/svg+xml", headers=headers)