id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
158,489
import hashlib import hmac as _hmac from flask import current_app from itsdangerous import Signer from itsdangerous.exc import ( # noqa: F401 BadSignature, BadTimeSignature, SignatureExpired, ) from itsdangerous.url_safe import URLSafeTimedSerializer from CTFd.utils import string_types string_types = (str,) def hmac(data, secret=None, digest=hashlib.sha1): if secret is None: secret = current_app.config["SECRET_KEY"] if isinstance(data, string_types): data = data.encode("utf-8") if isinstance(secret, string_types): secret = secret.encode("utf-8") return _hmac.new(key=secret, msg=data, digestmod=digest).hexdigest()
null
158,490
import sqlalchemy def build_model_filters(model, query, field, extra_columns=None): if extra_columns is None: extra_columns = {} filters = [] if query: # The field exists as an exposed column if model.__mapper__.has_property(field): column = getattr(model, field) if type(column.type) == sqlalchemy.sql.sqltypes.Integer: _filter = column.op("=")(query) else: _filter = column.like(f"%{query}%") filters.append(_filter) else: if field in extra_columns: column = extra_columns[field] _filter = column.op("=")(query) filters.append(_filter) return filters
null
158,491
from CTFd.utils import get_app_config, get_config def get_app_config(key, default=None): value = app.config.get(key, default) return value def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def mlc(): admin_config = get_config("oauth_client_id") and get_config("oauth_client_secret") main_config = get_app_config("OAUTH_CLIENT_ID") and get_app_config( "OAUTH_CLIENT_SECRET" ) return admin_config or main_config
null
158,492
from CTFd.utils import get_app_config, get_config def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def mlc_registration(): v = get_config("registration_visibility") return v == "mlc"
null
158,493
from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): CHALLENGE_VISIBILITY = "challenge_visibility" SCORE_VISIBILITY = "score_visibility" ACCOUNT_VISIBILITY = "account_visibility" REGISTRATION_VISIBILITY = "registration_visibility" class ChallengeVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" ADMINS = "admins" def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def authed(): return bool(session.get("id", False)) def is_admin(): if authed(): user = get_current_user_attrs() return user.type == "admin" else: return False def challenges_visible(): v = get_config(ConfigTypes.CHALLENGE_VISIBILITY) if v == ChallengeVisibilityTypes.PUBLIC: return True elif v == ChallengeVisibilityTypes.PRIVATE: return authed() elif v == ChallengeVisibilityTypes.ADMINS: return is_admin()
null
158,494
from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): CHALLENGE_VISIBILITY = "challenge_visibility" SCORE_VISIBILITY = "score_visibility" ACCOUNT_VISIBILITY = "account_visibility" REGISTRATION_VISIBILITY = "registration_visibility" class ScoreVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" HIDDEN = "hidden" ADMINS = "admins" def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def authed(): return bool(session.get("id", False)) def is_admin(): if authed(): user = get_current_user_attrs() return user.type == "admin" else: return False def scores_visible(): v = get_config(ConfigTypes.SCORE_VISIBILITY) if v == ScoreVisibilityTypes.PUBLIC: return True elif v == ScoreVisibilityTypes.PRIVATE: return authed() elif v == ScoreVisibilityTypes.HIDDEN: return False elif v == ScoreVisibilityTypes.ADMINS: return is_admin()
null
158,495
from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): class AccountVisibilityTypes(str, RawEnum): def get_config(key, default=None): def authed(): def is_admin(): def accounts_visible(): v = get_config(ConfigTypes.ACCOUNT_VISIBILITY) if v == AccountVisibilityTypes.PUBLIC: return True elif v == AccountVisibilityTypes.PRIVATE: return authed() elif v == AccountVisibilityTypes.ADMINS: return is_admin()
null
158,496
from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): class RegistrationVisibilityTypes(str, RawEnum): def get_config(key, default=None): def registration_visible(): v = get_config(ConfigTypes.REGISTRATION_VISIBILITY) if v == RegistrationVisibilityTypes.PUBLIC: return True elif v == RegistrationVisibilityTypes.PRIVATE: return False else: return False
null
158,497
from flask import current_app from CTFd.cache import cache from CTFd.models import Pages, db from CTFd.utils import get_config, markdown from CTFd.utils.dates import isoformat, unix_time_to_utc from CTFd.utils.formatters import safe_format from CTFd.utils.security.sanitize import sanitize_html def format_variables(content): def sanitize_html(html): def build_html(html, sanitize=False): html = format_variables(html) if current_app.config["HTML_SANITIZATION"] is True or sanitize is True: html = sanitize_html(html) return html
null
158,498
from flask import current_app from CTFd.cache import cache from CTFd.models import Pages, db from CTFd.utils import get_config, markdown from CTFd.utils.dates import isoformat, unix_time_to_utc from CTFd.utils.formatters import safe_format from CTFd.utils.security.sanitize import sanitize_html def format_variables(content): def markdown(md): def sanitize_html(html): def build_markdown(md, sanitize=False): html = markdown(md) html = format_variables(html) if current_app.config["HTML_SANITIZATION"] is True or sanitize is True: html = sanitize_html(html) return html
null
158,499
from flask import current_app from CTFd.cache import cache from CTFd.models import Pages, db from CTFd.utils import get_config, markdown from CTFd.utils.dates import isoformat, unix_time_to_utc from CTFd.utils.formatters import safe_format from CTFd.utils.security.sanitize import sanitize_html class Pages(db.Model): def html(self): def __init__(self, *args, **kwargs): def __repr__(self): def get_pages(): db_pages = Pages.query.filter( Pages.route != "index", Pages.draft.isnot(True), Pages.hidden.isnot(True) ).all() return db_pages
null
158,500
from flask import current_app from CTFd.cache import cache from CTFd.models import Pages, db from CTFd.utils import get_config, markdown from CTFd.utils.dates import isoformat, unix_time_to_utc from CTFd.utils.formatters import safe_format from CTFd.utils.security.sanitize import sanitize_html db = SQLAlchemy() class Pages(db.Model): __tablename__ = "pages" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80)) route = db.Column(db.String(128), unique=True) content = db.Column(db.Text) draft = db.Column(db.Boolean) hidden = db.Column(db.Boolean) auth_required = db.Column(db.Boolean) format = db.Column(db.String(80), default="markdown") # TODO: Use hidden attribute files = db.relationship("PageFiles", backref="page") def html(self): from CTFd.utils.config.pages import build_html, build_markdown if self.format == "markdown": return build_markdown(self.content) elif self.format == "html": return build_html(self.content) else: return build_markdown(self.content) def __init__(self, *args, **kwargs): super(Pages, self).__init__(**kwargs) def __repr__(self): return "<Pages {0}>".format(self.route) def get_page(route): page = db.session.execute( Pages.__table__.select() .where(Pages.route == route) .where(Pages.draft.isnot(True)) ).fetchone() if page: # Convert the row into a transient ORM object so this change isn't commited accidentally p = Pages(**page) return p return None
null
158,501
import smtplib from email.message import EmailMessage from email.utils import formataddr from socket import timeout from CTFd.utils import get_app_config, get_config def get_smtp(host, port, username=None, password=None, TLS=None, SSL=None, auth=None): if SSL is None: smtp = smtplib.SMTP(host, port, timeout=3) else: smtp = smtplib.SMTP_SSL(host, port, timeout=3) if TLS: smtp.starttls() if auth: smtp.login(username, password) return smtp def get_app_config(key, default=None): value = app.config.get(key, default) return value def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def sendmail(addr, text, subject): ctf_name = get_config("ctf_name") mailfrom_addr = get_config("mailfrom_addr") or get_app_config("MAILFROM_ADDR") mailfrom_addr = formataddr((ctf_name, mailfrom_addr)) data = { "host": get_config("mail_server") or get_app_config("MAIL_SERVER"), "port": int(get_config("mail_port") or get_app_config("MAIL_PORT")), } username = get_config("mail_username") or get_app_config("MAIL_USERNAME") password = get_config("mail_password") or get_app_config("MAIL_PASSWORD") TLS = get_config("mail_tls") or get_app_config("MAIL_TLS") SSL = get_config("mail_ssl") or get_app_config("MAIL_SSL") auth = get_config("mail_useauth") or get_app_config("MAIL_USEAUTH") if username: data["username"] = username if password: data["password"] = password if TLS: data["TLS"] = TLS if SSL: data["SSL"] = SSL if auth: data["auth"] = auth try: smtp = get_smtp(**data) msg = EmailMessage() msg.set_content(text) msg["Subject"] = subject msg["From"] = mailfrom_addr msg["To"] = addr # Check whether we are using an admin-defined SMTP server custom_smtp = bool(get_config("mail_server")) # We should only consider the MAILSENDER_ADDR value on servers defined in config if custom_smtp: smtp.send_message(msg) else: mailsender_addr = get_app_config("MAILSENDER_ADDR") smtp.send_message(msg, from_addr=mailsender_addr) smtp.quit() return True, "Email sent" except smtplib.SMTPException as e: return False, str(e) except timeout: return False, "SMTP server connection timed out" except Exception as e: return False, str(e)
null
158,502
from email.utils import formataddr import requests from CTFd.utils import get_app_config, get_config def get_app_config(key, default=None): value = app.config.get(key, default) return value def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def sendmail(addr, text, subject): ctf_name = get_config("ctf_name") mailfrom_addr = get_config("mailfrom_addr") or get_app_config("MAILFROM_ADDR") mailfrom_addr = formataddr((ctf_name, mailfrom_addr)) mailgun_base_url = get_config("mailgun_base_url") or get_app_config( "MAILGUN_BASE_URL" ) mailgun_api_key = get_config("mailgun_api_key") or get_app_config("MAILGUN_API_KEY") try: r = requests.post( mailgun_base_url + "/messages", auth=("api", mailgun_api_key), data={ "from": mailfrom_addr, "to": [addr], "subject": subject, "text": text, }, timeout=1.0, ) except requests.RequestException as e: return ( False, "{error} exception occured while handling your request".format( error=type(e).__name__ ), ) if r.status_code == 200: return True, "Email sent" else: return False, "Mailgun settings are incorrect"
null
158,503
import geoacumen_city import maxminddb from flask import current_app IP_ADDR_LOOKUP = maxminddb.open_database( current_app.config.get("GEOIP_DATABASE_PATH", geoacumen_city.db_path) ) def lookup_ip_address(addr): try: response = IP_ADDR_LOOKUP.get(addr) return response["country"]["iso_code"] except (KeyError, ValueError, TypeError): return None
null
158,504
import geoacumen_city import maxminddb from flask import current_app IP_ADDR_LOOKUP = maxminddb.open_database( current_app.config.get("GEOIP_DATABASE_PATH", geoacumen_city.db_path) ) def lookup_ip_address_city(addr): try: response = IP_ADDR_LOOKUP.get(addr) return response["city"]["names"]["en"] except (KeyError, ValueError, TypeError): return None
null
158,505
import datetime import shutil from flask_migrate import MigrateCommand from flask_script import Manager from CTFd import create_app from CTFd.utils import get_config as get_config_util from CTFd.utils import set_config as set_config_util from CTFd.utils.config import ctf_name from CTFd.utils.exports import export_ctf as export_ctf_util from CTFd.utils.exports import import_ctf as import_ctf_util app = create_app() JS_ENUMS = {} def jsenums(): from CTFd.constants import JS_ENUMS import json import os path = os.path.join(app.root_path, "themes/core/assets/js/constants.js") with open(path, "w+") as f: for k, v in JS_ENUMS.items(): f.write("const {} = Object.freeze({});".format(k, json.dumps(v)))
null
158,506
import datetime import shutil from flask_migrate import MigrateCommand from flask_script import Manager from CTFd import create_app from CTFd.utils import get_config as get_config_util from CTFd.utils import set_config as set_config_util from CTFd.utils.config import ctf_name from CTFd.utils.exports import export_ctf as export_ctf_util from CTFd.utils.exports import import_ctf as import_ctf_util app = create_app() def get_config(key): with app.app_context(): print(get_config_util(key))
null
158,507
import datetime import shutil from flask_migrate import MigrateCommand from flask_script import Manager from CTFd import create_app from CTFd.utils import get_config as get_config_util from CTFd.utils import set_config as set_config_util from CTFd.utils.config import ctf_name from CTFd.utils.exports import export_ctf as export_ctf_util from CTFd.utils.exports import import_ctf as import_ctf_util app = create_app() def set_config(key, value): with app.app_context(): print(set_config_util(key, value).value)
null
158,508
import datetime import shutil from flask_migrate import MigrateCommand from flask_script import Manager from CTFd import create_app from CTFd.utils import get_config as get_config_util from CTFd.utils import set_config as set_config_util from CTFd.utils.config import ctf_name from CTFd.utils.exports import export_ctf as export_ctf_util from CTFd.utils.exports import import_ctf as import_ctf_util app = create_app() BUILD_COMMANDS = {"jsenums": jsenums} def build(cmd): with app.app_context(): cmd = BUILD_COMMANDS.get(cmd) cmd()
null
158,509
import datetime import shutil from flask_migrate import MigrateCommand from flask_script import Manager from CTFd import create_app from CTFd.utils import get_config as get_config_util from CTFd.utils import set_config as set_config_util from CTFd.utils.config import ctf_name from CTFd.utils.exports import export_ctf as export_ctf_util from CTFd.utils.exports import import_ctf as import_ctf_util app = create_app() def ctf_name(): name = get_config("ctf_name") return name if name else "CTFd" def export_ctf(path=None): with app.app_context(): backup = export_ctf_util() if path: with open(path, "wb") as target: shutil.copyfileobj(backup, target) else: name = ctf_name() day = datetime.datetime.now().strftime("%Y-%m-%d_%T") full_name = f"{name}.{day}.zip" with open(full_name, "wb") as target: shutil.copyfileobj(backup, target) print(f"Exported {full_name}")
null
158,510
import datetime import shutil from flask_migrate import MigrateCommand from flask_script import Manager from CTFd import create_app from CTFd.utils import get_config as get_config_util from CTFd.utils import set_config as set_config_util from CTFd.utils.config import ctf_name from CTFd.utils.exports import export_ctf as export_ctf_util from CTFd.utils.exports import import_ctf as import_ctf_util app = create_app() def import_ctf(path): with app.app_context(): import_ctf_util(path)
null
158,513
import base64 import requests from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, session, url_for from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired from CTFd.cache import clear_team_session, clear_user_session from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db from CTFd.utils import config, email, get_app_config, get_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_teams_mode from CTFd.utils.config.integrations import mlc_registration from CTFd.utils.config.visibility import registration_visible from CTFd.utils.crypto import verify_password from CTFd.utils.decorators import ratelimit from CTFd.utils.decorators.visibility import check_registration_visibility from CTFd.utils.helpers import error_for, get_errors, markup from CTFd.utils.logging import log from CTFd.utils.modes import TEAMS_MODE from CTFd.utils.security.auth import login_user, logout_user from CTFd.utils.security.signing import unserialize from CTFd.utils.validators import ValidationError db = SQLAlchemy() class Users(db.Model): def __init__(self, **kwargs): def validate_password(self, key, plaintext): def account_id(self): def account(self): def fields(self): def solves(self): def fails(self): def awards(self): def score(self): def place(self): def get_fields(self, admin=False): def get_solves(self, admin=False): def get_fails(self, admin=False): def get_awards(self, admin=False): def get_score(self, admin=False): def get_place(self, admin=False, numeric=False): class UserFields(Fields): class UserFieldEntries(FieldEntries): def get_config(key, default=None): def is_teams_mode(): def get_errors(): def log(logger, format, **kwargs): def login_user(user): def register(): errors = get_errors() if current_user.authed(): return redirect(url_for("challenges.listing")) if request.method == "POST": name = request.form.get("name", "").strip() email_address = request.form.get("email", "").strip().lower() password = request.form.get("password", "").strip() website = request.form.get("website") affiliation = request.form.get("affiliation") country = request.form.get("country") registration_code = request.form.get("registration_code", "") name_len = len(name) == 0 names = Users.query.add_columns("name", "id").filter_by(name=name).first() emails = ( Users.query.add_columns("email", "id") .filter_by(email=email_address) .first() ) pass_short = len(password) == 0 pass_long = len(password) > 128 valid_email = validators.validate_email(email_address) team_name_email_check = validators.validate_email(name) if get_config("registration_code"): if ( registration_code.lower() != get_config("registration_code", default="").lower() ): errors.append("The registration code you entered was incorrect") # Process additional user fields fields = {} for field in UserFields.query.all(): fields[field.id] = field entries = {} for field_id, field in fields.items(): value = request.form.get(f"fields[{field_id}]", "").strip() if field.required is True and (value is None or value == ""): errors.append("Please provide all required fields") break # Handle special casing of existing profile fields if field.name.lower() == "affiliation": affiliation = value break elif field.name.lower() == "website": website = value break if field.field_type == "boolean": entries[field_id] = bool(value) else: entries[field_id] = value if country: try: validators.validate_country_code(country) valid_country = True except ValidationError: valid_country = False else: valid_country = True if website: valid_website = validators.validate_url(website) else: valid_website = True if affiliation: valid_affiliation = len(affiliation) < 128 else: valid_affiliation = True if not valid_email: errors.append("Please enter a valid email address") if email.check_email_is_whitelisted(email_address) is False: errors.append( "Only email addresses under {domains} may register".format( domains=get_config("domain_whitelist") ) ) if names: errors.append("That user name is already taken") if team_name_email_check is True: errors.append("Your user name cannot be an email address") if emails: errors.append("That email has already been used") if pass_short: errors.append("Pick a longer password") if pass_long: errors.append("Pick a shorter password") if name_len: errors.append("Pick a longer user name") if valid_website is False: errors.append("Websites must be a proper URL starting with http or https") if valid_country is False: errors.append("Invalid country") if valid_affiliation is False: errors.append("Please provide a shorter affiliation") if len(errors) > 0: return render_template( "register.html", errors=errors, name=request.form["name"], email=request.form["email"], password=request.form["password"], ) else: with app.app_context(): user = Users(name=name, email=email_address, password=password) if website: user.website = website if affiliation: user.affiliation = affiliation if country: user.country = country db.session.add(user) db.session.commit() db.session.flush() for field_id, value in entries.items(): entry = UserFieldEntries( field_id=field_id, value=value, user_id=user.id ) db.session.add(entry) db.session.commit() login_user(user) if request.args.get("next") and validators.is_safe_url( request.args.get("next") ): return redirect(request.args.get("next")) if config.can_send_mail() and get_config( "verify_emails" ): # Confirming users is enabled and we can send email. log( "registrations", format="[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}", name=user.name, email=user.email, ) email.verify_email_address(user.email) db.session.close() return redirect(url_for("auth.confirm")) else: # Don't care about confirming users if ( config.can_send_mail() ): # We want to notify the user that they have registered. email.successful_registration_notification(user.email) log( "registrations", format="[{date}] {ip} - {name} registered with {email}", name=user.name, email=user.email, ) db.session.close() if is_teams_mode(): return redirect(url_for("teams.private")) return redirect(url_for("challenges.listing")) else: return render_template("register.html", errors=errors)
null
158,516
import base64 import requests from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, session, url_for from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired from CTFd.cache import clear_team_session, clear_user_session from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db from CTFd.utils import config, email, get_app_config, get_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_teams_mode from CTFd.utils.config.integrations import mlc_registration from CTFd.utils.config.visibility import registration_visible from CTFd.utils.crypto import verify_password from CTFd.utils.decorators import ratelimit from CTFd.utils.decorators.visibility import check_registration_visibility from CTFd.utils.helpers import error_for, get_errors, markup from CTFd.utils.logging import log from CTFd.utils.modes import TEAMS_MODE from CTFd.utils.security.auth import login_user, logout_user from CTFd.utils.security.signing import unserialize from CTFd.utils.validators import ValidationError def clear_user_session(user_id): from CTFd.utils.user import get_user_attrs cache.delete_memoized(get_user_attrs, user_id=user_id) def clear_team_session(team_id): from CTFd.utils.user import get_team_attrs cache.delete_memoized(get_team_attrs, team_id=team_id) db = SQLAlchemy() class Users(db.Model): __tablename__ = "users" __table_args__ = (db.UniqueConstraint("id", "oauth_id"), {}) # Core attributes id = db.Column(db.Integer, primary_key=True) oauth_id = db.Column(db.Integer, unique=True) # User names are not constrained to be unique to allow for official/unofficial teams. name = db.Column(db.String(128)) password = db.Column(db.String(128)) email = db.Column(db.String(128), unique=True) type = db.Column(db.String(80)) secret = db.Column(db.String(128)) # Supplementary attributes website = db.Column(db.String(128)) affiliation = db.Column(db.String(128)) country = db.Column(db.String(32)) bracket = db.Column(db.String(32)) hidden = db.Column(db.Boolean, default=False) banned = db.Column(db.Boolean, default=False) verified = db.Column(db.Boolean, default=False) # Relationship for Teams team_id = db.Column(db.Integer, db.ForeignKey("teams.id")) field_entries = db.relationship( "UserFieldEntries", foreign_keys="UserFieldEntries.user_id", lazy="joined" ) created = db.Column(db.DateTime, default=datetime.datetime.utcnow) __mapper_args__ = {"polymorphic_identity": "user", "polymorphic_on": type} def __init__(self, **kwargs): super(Users, self).__init__(**kwargs) def validate_password(self, key, plaintext): from CTFd.utils.crypto import hash_password return hash_password(str(plaintext)) def account_id(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team_id elif user_mode == "users": return self.id def account(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team elif user_mode == "users": return self def fields(self): return self.get_fields(admin=False) def solves(self): return self.get_solves(admin=False) def fails(self): return self.get_fails(admin=False) def awards(self): return self.get_awards(admin=False) def score(self): return self.get_score(admin=False) def place(self): from CTFd.utils.config.visibility import scores_visible if scores_visible(): return self.get_place(admin=False) else: return None def get_fields(self, admin=False): if admin: return self.field_entries return [ entry for entry in self.field_entries if entry.field.public and entry.value ] def get_solves(self, admin=False): from CTFd.utils import get_config solves = Solves.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) solves = solves.filter(Solves.date < dt) return solves.all() def get_fails(self, admin=False): from CTFd.utils import get_config fails = Fails.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) fails = fails.filter(Fails.date < dt) return fails.all() def get_awards(self, admin=False): from CTFd.utils import get_config awards = Awards.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) awards = awards.filter(Awards.date < dt) return awards.all() def get_score(self, admin=False): score = db.func.sum(Challenges.value).label("score") user = ( db.session.query(Solves.user_id, score) .join(Users, Solves.user_id == Users.id) .join(Challenges, Solves.challenge_id == Challenges.id) .filter(Users.id == self.id) ) award_score = db.func.sum(Awards.value).label("award_score") award = db.session.query(award_score).filter_by(user_id=self.id) if not admin: freeze = Configs.query.filter_by(key="freeze").first() if freeze and freeze.value: freeze = int(freeze.value) freeze = datetime.datetime.utcfromtimestamp(freeze) user = user.filter(Solves.date < freeze) award = award.filter(Awards.date < freeze) user = user.group_by(Solves.user_id).first() award = award.first() if user and award: return int(user.score or 0) + int(award.award_score or 0) elif user: return int(user.score or 0) elif award: return int(award.award_score or 0) else: return 0 def get_place(self, admin=False, numeric=False): """ This method is generally a clone of CTFd.scoreboard.get_standings. The point being that models.py must be self-reliant and have little to no imports within the CTFd application as importing from the application itself will result in a circular import. """ from CTFd.utils.scores import get_user_standings from CTFd.utils.humanize.numbers import ordinalize standings = get_user_standings(admin=admin) for i, user in enumerate(standings): if user.user_id == self.id: n = i + 1 if numeric: return n return ordinalize(n) else: return None class Teams(db.Model): __tablename__ = "teams" __table_args__ = (db.UniqueConstraint("id", "oauth_id"), {}) # Core attributes id = db.Column(db.Integer, primary_key=True) oauth_id = db.Column(db.Integer, unique=True) # Team names are not constrained to be unique to allow for official/unofficial teams. name = db.Column(db.String(128)) email = db.Column(db.String(128), unique=True) password = db.Column(db.String(128)) secret = db.Column(db.String(128)) members = db.relationship( "Users", backref="team", foreign_keys="Users.team_id", lazy="joined" ) # Supplementary attributes website = db.Column(db.String(128)) affiliation = db.Column(db.String(128)) country = db.Column(db.String(32)) bracket = db.Column(db.String(32)) hidden = db.Column(db.Boolean, default=False) banned = db.Column(db.Boolean, default=False) # Relationship for Users captain_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="SET NULL")) captain = db.relationship("Users", foreign_keys=[captain_id]) field_entries = db.relationship( "TeamFieldEntries", foreign_keys="TeamFieldEntries.team_id", lazy="joined" ) created = db.Column(db.DateTime, default=datetime.datetime.utcnow) def __init__(self, **kwargs): super(Teams, self).__init__(**kwargs) def validate_password(self, key, plaintext): from CTFd.utils.crypto import hash_password return hash_password(str(plaintext)) def fields(self): return self.get_fields(admin=False) def solves(self): return self.get_solves(admin=False) def fails(self): return self.get_fails(admin=False) def awards(self): return self.get_awards(admin=False) def score(self): return self.get_score(admin=False) def place(self): from CTFd.utils.config.visibility import scores_visible if scores_visible(): return self.get_place(admin=False) else: return None def get_fields(self, admin=False): if admin: return self.field_entries return [ entry for entry in self.field_entries if entry.field.public and entry.value ] def get_invite_code(self): from flask import current_app from CTFd.utils.security.signing import serialize, hmac secret_key = current_app.config["SECRET_KEY"] if isinstance(secret_key, str): secret_key = secret_key.encode("utf-8") team_password_key = self.password.encode("utf-8") verification_secret = secret_key + team_password_key invite_object = { "id": self.id, "v": hmac(str(self.id), secret=verification_secret), } code = serialize(data=invite_object, secret=secret_key) return code def load_invite_code(cls, code): from flask import current_app from CTFd.utils.security.signing import ( unserialize, hmac, BadTimeSignature, BadSignature, ) from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException secret_key = current_app.config["SECRET_KEY"] if isinstance(secret_key, str): secret_key = secret_key.encode("utf-8") # Unserialize the invite code try: # Links expire after 1 day invite_object = unserialize(code, max_age=86400) except BadTimeSignature: raise TeamTokenExpiredException except BadSignature: raise TeamTokenInvalidException # Load the team by the ID in the invite team_id = invite_object["id"] team = cls.query.filter_by(id=team_id).first_or_404() # Create the team specific secret team_password_key = team.password.encode("utf-8") verification_secret = secret_key + team_password_key # Verify the team verficiation code verified = hmac(str(team.id), secret=verification_secret) == invite_object["v"] if verified is False: raise TeamTokenInvalidException return team def get_solves(self, admin=False): from CTFd.utils import get_config member_ids = [member.id for member in self.members] solves = Solves.query.filter(Solves.user_id.in_(member_ids)).order_by( Solves.date.asc() ) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) solves = solves.filter(Solves.date < dt) return solves.all() def get_fails(self, admin=False): from CTFd.utils import get_config member_ids = [member.id for member in self.members] fails = Fails.query.filter(Fails.user_id.in_(member_ids)).order_by( Fails.date.asc() ) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) fails = fails.filter(Fails.date < dt) return fails.all() def get_awards(self, admin=False): from CTFd.utils import get_config member_ids = [member.id for member in self.members] awards = Awards.query.filter(Awards.user_id.in_(member_ids)).order_by( Awards.date.asc() ) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) awards = awards.filter(Awards.date < dt) return awards.all() def get_score(self, admin=False): score = 0 for member in self.members: score += member.get_score(admin=admin) return score def get_place(self, admin=False, numeric=False): """ This method is generally a clone of CTFd.scoreboard.get_standings. The point being that models.py must be self-reliant and have little to no imports within the CTFd application as importing from the application itself will result in a circular import. """ from CTFd.utils.scores import get_team_standings from CTFd.utils.humanize.numbers import ordinalize standings = get_team_standings(admin=admin) for i, team in enumerate(standings): if team.team_id == self.id: n = i + 1 if numeric: return n return ordinalize(n) else: return None def get_app_config(key, default=None): value = app.config.get(key, default) return value def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def mlc_registration(): v = get_config("registration_visibility") return v == "mlc" def registration_visible(): v = get_config(ConfigTypes.REGISTRATION_VISIBILITY) if v == RegistrationVisibilityTypes.PUBLIC: return True elif v == RegistrationVisibilityTypes.PRIVATE: return False else: return False def error_for(endpoint, message): flash(message=message, category=endpoint + ".errors") def log(logger, format, **kwargs): logger = logging.getLogger(logger) props = { "id": session.get("id"), "date": time.strftime("%m/%d/%Y %X"), "ip": get_ip(), } props.update(kwargs) msg = format.format(**props) print(msg) logger.info(msg) TEAMS_MODE = "teams" def login_user(user): session["id"] = user.id session["nonce"] = generate_nonce() session["hash"] = hmac(user.password) # Clear out any currently cached user attributes clear_user_session(user_id=user.id) def oauth_redirect(): oauth_code = request.args.get("code") state = request.args.get("state") if session["nonce"] != state: log("logins", "[{date}] {ip} - OAuth State validation mismatch") error_for(endpoint="auth.login", message="OAuth State validation mismatch.") return redirect(url_for("auth.login")) if oauth_code: url = ( get_app_config("OAUTH_TOKEN_ENDPOINT") or get_config("oauth_token_endpoint") or "https://auth.majorleaguecyber.org/oauth/token" ) client_id = get_app_config("OAUTH_CLIENT_ID") or get_config("oauth_client_id") client_secret = get_app_config("OAUTH_CLIENT_SECRET") or get_config( "oauth_client_secret" ) headers = {"content-type": "application/x-www-form-urlencoded"} data = { "code": oauth_code, "client_id": client_id, "client_secret": client_secret, "grant_type": "authorization_code", } token_request = requests.post(url, data=data, headers=headers) if token_request.status_code == requests.codes.ok: token = token_request.json()["access_token"] user_url = ( get_app_config("OAUTH_API_ENDPOINT") or get_config("oauth_api_endpoint") or "https://api.majorleaguecyber.org/user" ) headers = { "Authorization": "Bearer " + str(token), "Content-type": "application/json", } api_data = requests.get(url=user_url, headers=headers).json() user_id = api_data["id"] user_name = api_data["name"] user_email = api_data["email"] user = Users.query.filter_by(email=user_email).first() if user is None: # Check if we are allowing registration before creating users if registration_visible() or mlc_registration(): user = Users( name=user_name, email=user_email, oauth_id=user_id, verified=True, ) db.session.add(user) db.session.commit() else: log("logins", "[{date}] {ip} - Public registration via MLC blocked") error_for( endpoint="auth.login", message="Public registration is disabled. Please try again later.", ) return redirect(url_for("auth.login")) if get_config("user_mode") == TEAMS_MODE: team_id = api_data["team"]["id"] team_name = api_data["team"]["name"] team = Teams.query.filter_by(oauth_id=team_id).first() if team is None: num_teams_limit = int(get_config("num_teams", default=0)) num_teams = Teams.query.filter_by( banned=False, hidden=False ).count() if num_teams_limit and num_teams >= num_teams_limit: abort( 403, description=f"Reached the maximum number of teams ({num_teams_limit}). Please join an existing team.", ) team = Teams(name=team_name, oauth_id=team_id, captain_id=user.id) db.session.add(team) db.session.commit() clear_team_session(team_id=team.id) team_size_limit = get_config("team_size", default=0) if team_size_limit and len(team.members) >= team_size_limit: plural = "" if team_size_limit == 1 else "s" size_error = "Teams are limited to {limit} member{plural}.".format( limit=team_size_limit, plural=plural ) error_for(endpoint="auth.login", message=size_error) return redirect(url_for("auth.login")) team.members.append(user) db.session.commit() if user.oauth_id is None: user.oauth_id = user_id user.verified = True db.session.commit() clear_user_session(user_id=user.id) login_user(user) return redirect(url_for("challenges.listing")) else: log("logins", "[{date}] {ip} - OAuth token retrieval failure") error_for(endpoint="auth.login", message="OAuth token retrieval failure.") return redirect(url_for("auth.login")) else: log("logins", "[{date}] {ip} - Received redirect without OAuth code") error_for( endpoint="auth.login", message="Received redirect without OAuth code." ) return redirect(url_for("auth.login"))
null
158,519
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin def set_config(key, value): def is_setup(): def unserialize(data, secret=None, max_age=432000): def is_admin(): def integrations(): if is_admin() or is_setup() is False: name = request.values.get("name") state = request.values.get("state") try: state = unserialize(state, max_age=3600) except (BadSignature, BadTimeSignature): state = False except Exception: state = False if state: if name == "mlc": mlc_client_id = request.values.get("mlc_client_id") mlc_client_secret = request.values.get("mlc_client_secret") set_config("oauth_client_id", mlc_client_id) set_config("oauth_client_secret", mlc_client_secret) return render_template("admin/integrations.html") else: abort(404) else: abort(403) else: abort(403)
null
158,520
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin class Notifications(db.Model): def html(self): def __init__(self, *args, **kwargs): def notifications(): notifications = Notifications.query.order_by(Notifications.id.desc()).all() return render_template("notifications.html", notifications=notifications)
null
158,523
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin def get_config(key, default=None): def build_markdown(md, sanitize=False): def tos(): tos_url = get_config("tos_url") tos_text = get_config("tos_text") if tos_url: return redirect(tos_url) elif tos_text: return render_template("page.html", content=build_markdown(tos_text)) else: abort(404)
null
158,524
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def build_markdown(md, sanitize=False): html = markdown(md) html = format_variables(html) if current_app.config["HTML_SANITIZATION"] is True or sanitize is True: html = sanitize_html(html) return html def privacy(): privacy_url = get_config("privacy_url") privacy_text = get_config("privacy_text") if privacy_url: return redirect(privacy_url) elif privacy_text: return render_template("page.html", content=build_markdown(privacy_text)) else: abort(404)
null
158,526
import inspect import os from alembic.config import Config from alembic.migration import MigrationContext from alembic.operations import Operations from alembic.script import ScriptDirectory from flask import current_app from sqlalchemy import create_engine, pool from CTFd.utils import get_config, set_config def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def current(plugin_name=None): if plugin_name is None: # Get the directory name of the plugin if unspecified # Doing it this way doesn't waste the rest of the inspect.stack call frame = inspect.currentframe() caller_info = inspect.getframeinfo(frame.f_back) caller_path = caller_info[0] plugin_name = os.path.basename(os.path.dirname(caller_path)) return get_config(plugin_name + "_alembic_version")
null
158,527
import inspect import os from alembic.config import Config from alembic.migration import MigrationContext from alembic.operations import Operations from alembic.script import ScriptDirectory from flask import current_app from sqlalchemy import create_engine, pool from CTFd.utils import get_config, set_config def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def set_config(key, value): config = Configs.query.filter_by(key=key).first() if config: config.value = value else: config = Configs(key=key, value=value) db.session.add(config) db.session.commit() # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) cache.delete_memoized(_get_config, key) return config def upgrade(plugin_name=None, revision=None, lower="current"): database_url = current_app.config.get("SQLALCHEMY_DATABASE_URI") if database_url.startswith("sqlite"): current_app.db.create_all() return if plugin_name is None: # Get the directory name of the plugin if unspecified # Doing it this way doesn't waste the rest of the inspect.stack call frame = inspect.currentframe() caller_info = inspect.getframeinfo(frame.f_back) caller_path = caller_info[0] plugin_name = os.path.basename(os.path.dirname(caller_path)) # Check if the plugin has migraitons migrations_path = os.path.join(current_app.plugins_dir, plugin_name, "migrations") if os.path.isdir(migrations_path) is False: return engine = create_engine(database_url, poolclass=pool.NullPool) conn = engine.connect() context = MigrationContext.configure(conn) op = Operations(context) # Find the list of migrations to run config = Config() config.set_main_option("script_location", migrations_path) config.set_main_option("version_locations", migrations_path) script = ScriptDirectory.from_config(config) # Choose base revision for plugin upgrade # "current" points to the current plugin version stored in config # None represents the absolute base layer (e.g. first installation) if lower == "current": lower = get_config(plugin_name + "_alembic_version") # Do we upgrade to head or to a specific revision if revision is None: upper = script.get_current_head() else: upper = revision # Apply from lower to upper revs = list(script.iterate_revisions(lower=lower, upper=upper)) revs.reverse() try: for r in revs: with context.begin_transaction(): r.module.upgrade(op=op) # Set revision that succeeded so we don't need # to start from the beginning on failure set_config(plugin_name + "_alembic_version", r.revision) finally: conn.close() # Set the new latest revision set_config(plugin_name + "_alembic_version", upper)
null
158,532
import functools from flask import abort from CTFd.utils import get_config from CTFd.utils.modes import TEAMS_MODE, USERS_MODE def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value USERS_MODE = "users" def require_team_mode(f): @functools.wraps(f) def _require_team_mode(*args, **kwargs): if get_config("user_mode") == USERS_MODE: abort(404) return f(*args, **kwargs) return _require_team_mode
null
158,535
import functools from flask import abort, redirect, render_template, request, url_for from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): class ChallengeVisibilityTypes(str, RawEnum): def get_config(key, default=None): def authed(): def is_admin(): def check_challenge_visibility(f): @functools.wraps(f) def _check_challenge_visibility(*args, **kwargs): v = get_config(ConfigTypes.CHALLENGE_VISIBILITY) if v == ChallengeVisibilityTypes.PUBLIC: return f(*args, **kwargs) elif v == ChallengeVisibilityTypes.PRIVATE: if authed(): return f(*args, **kwargs) else: if request.content_type == "application/json": abort(403) else: return redirect(url_for("auth.login", next=request.full_path)) elif v == ChallengeVisibilityTypes.ADMINS: if is_admin(): return f(*args, **kwargs) else: if authed(): abort(403) else: return redirect(url_for("auth.login", next=request.full_path)) return _check_challenge_visibility
null
158,537
import functools from flask import abort, redirect, render_template, request, url_for from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): class RegistrationVisibilityTypes(str, RawEnum): def get_config(key, default=None): def check_registration_visibility(f): @functools.wraps(f) def _check_registration_visibility(*args, **kwargs): v = get_config(ConfigTypes.REGISTRATION_VISIBILITY) if v == RegistrationVisibilityTypes.PUBLIC: return f(*args, **kwargs) elif v == RegistrationVisibilityTypes.PRIVATE: abort(404) return _check_registration_visibility
null
158,541
import datetime import os from flask import session from CTFd.cache import clear_user_session from CTFd.exceptions import UserNotFoundException, UserTokenExpiredException from CTFd.models import UserTokens, db from CTFd.utils.encoding import hexencode from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import hmac def clear_user_session(user_id): from CTFd.utils.user import get_user_attrs cache.delete_memoized(get_user_attrs, user_id=user_id) import hmac as _hmac def hmac(data, secret=None, digest=hashlib.sha1): if secret is None: secret = current_app.config["SECRET_KEY"] if isinstance(data, string_types): data = data.encode("utf-8") if isinstance(secret, string_types): secret = secret.encode("utf-8") return _hmac.new(key=secret, msg=data, digestmod=digest).hexdigest() def update_user(user): session["id"] = user.id session["hash"] = hmac(user.password) # Clear out any currently cached user attributes clear_user_session(user_id=user.id)
null
158,542
import datetime import os from flask import session from CTFd.cache import clear_user_session from CTFd.exceptions import UserNotFoundException, UserTokenExpiredException from CTFd.models import UserTokens, db from CTFd.utils.encoding import hexencode from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import hmac db = SQLAlchemy() class UserTokens(Tokens): __mapper_args__ = {"polymorphic_identity": "user"} def hexencode(s): if isinstance(s, string_types): s = s.encode("utf-8") encoded = codecs.encode(s, "hex") try: encoded = encoded.decode("utf-8") except UnicodeDecodeError: pass return encoded def generate_user_token(user, expiration=None): temp_token = True while temp_token is not None: value = hexencode(os.urandom(32)) temp_token = UserTokens.query.filter_by(value=value).first() token = UserTokens(user_id=user.id, expiration=expiration, value=value) db.session.add(token) db.session.commit() return token
null
158,547
from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): CHALLENGE_VISIBILITY = "challenge_visibility" SCORE_VISIBILITY = "score_visibility" ACCOUNT_VISIBILITY = "account_visibility" REGISTRATION_VISIBILITY = "registration_visibility" class AccountVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" ADMINS = "admins" def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def authed(): return bool(session.get("id", False)) def is_admin(): if authed(): user = get_current_user_attrs() return user.type == "admin" else: return False def accounts_visible(): v = get_config(ConfigTypes.ACCOUNT_VISIBILITY) if v == AccountVisibilityTypes.PUBLIC: return True elif v == AccountVisibilityTypes.PRIVATE: return authed() elif v == AccountVisibilityTypes.ADMINS: return is_admin()
null
158,548
from flask import current_app from CTFd.cache import cache from CTFd.models import Pages, db from CTFd.utils import get_config, markdown from CTFd.utils.dates import isoformat, unix_time_to_utc from CTFd.utils.formatters import safe_format from CTFd.utils.security.sanitize import sanitize_html def format_variables(content): ctf_name = get_config("ctf_name") ctf_description = get_config("ctf_description") ctf_start = get_config("start") if ctf_start: ctf_start = isoformat(unix_time_to_utc(int(ctf_start))) ctf_end = get_config("end") if ctf_end: ctf_end = isoformat(unix_time_to_utc(int(ctf_end))) ctf_freeze = get_config("freeze") if ctf_freeze: ctf_freeze = isoformat(unix_time_to_utc(int(ctf_freeze))) content = safe_format( content, ctf_name=ctf_name, ctf_description=ctf_description, ctf_start=ctf_start, ctf_end=ctf_end, ctf_freeze=ctf_freeze, ) return content def sanitize_html(html): return SANITIZER.sanitize(html) def build_html(html, sanitize=False): html = format_variables(html) if current_app.config["HTML_SANITIZATION"] is True or sanitize is True: html = sanitize_html(html) return html
null
158,549
from flask import current_app from CTFd.cache import cache from CTFd.models import Pages, db from CTFd.utils import get_config, markdown from CTFd.utils.dates import isoformat, unix_time_to_utc from CTFd.utils.formatters import safe_format from CTFd.utils.security.sanitize import sanitize_html class Pages(db.Model): __tablename__ = "pages" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80)) route = db.Column(db.String(128), unique=True) content = db.Column(db.Text) draft = db.Column(db.Boolean) hidden = db.Column(db.Boolean) auth_required = db.Column(db.Boolean) format = db.Column(db.String(80), default="markdown") # TODO: Use hidden attribute files = db.relationship("PageFiles", backref="page") def html(self): from CTFd.utils.config.pages import build_html, build_markdown if self.format == "markdown": return build_markdown(self.content) elif self.format == "html": return build_html(self.content) else: return build_markdown(self.content) def __init__(self, *args, **kwargs): super(Pages, self).__init__(**kwargs) def __repr__(self): return "<Pages {0}>".format(self.route) def get_pages(): db_pages = Pages.query.filter( Pages.route != "index", Pages.draft.isnot(True), Pages.hidden.isnot(True) ).all() return db_pages
null
158,554
import datetime import platform import random import json import os import colorama from colorama import Fore def show_header(): print(Fore.LIGHTMAGENTA_EX) print("---------------------------") print(" Rock Paper Scissors") print(" Error Handling Edition") print("---------------------------") print(Fore.LIGHTWHITE_EX)
null
158,555
import datetime import platform import random import json import os import colorama from colorama import Fore def load_leaders(): def show_leaderboard(): leaders = load_leaders() sorted_leaders = list(leaders.items()) sorted_leaders.sort(key=lambda l: l[1], reverse=True) print() print("---------------------------") print("LEADERS:") for name, wins in sorted_leaders[0:5]: print(f"{wins:,} -- {name}") print("---------------------------") print()
null
158,556
import datetime import platform import random import json import os import colorama from colorama import Fore def get_players(): p1 = input("Player 1, what is your name? ") p2 = "Computer" return p1, p2
null
158,557
import datetime import platform import random import json import os import colorama from colorama import Fore rolls = {} def find_winner(wins, names): best_of = 3 for name in names: if wins.get(name, 0) >= best_of: return name return None def check_for_winning_throw(player_1, player_2, roll1, roll2): winner = None if roll1 == roll2: print("The play was tied!") outcome = rolls.get(roll1, {}) if roll2 in outcome.get('defeats'): return player_1 elif roll2 in outcome.get('defeated_by'): return player_2 return winner def get_roll(player_name, roll_names): try: print("Available rolls:") for index, r in enumerate(roll_names, start=1): print(f"{index}. {r}") text = input(f"{player_name}, what is your roll? ") if text is None or not text.strip(): print("You must enter response") return None selected_index = int(text) - 1 if selected_index < 0 or selected_index >= len(roll_names): print(f"Sorry {player_name}, {text} is out of bounds!") return None return roll_names[selected_index] except ValueError as ve: print(Fore.RED + f"Could not convert to integer: {ve}" + Fore.LIGHTWHITE_EX) return None def record_win(winner_name): leaders = load_leaders() if winner_name in leaders: leaders[winner_name] += 1 else: leaders[winner_name] = 1 directory = os.path.dirname(__file__) filename = os.path.join(directory, 'leaderboard.json') with open(filename, 'w', encoding='utf-8') as fout: json.dump(leaders, fout) def log(msg): directory = os.path.dirname(__file__) filename = os.path.join(directory, 'rps.log') with open(filename, 'a', encoding='utf-8') as fout: fout.write(f"[{datetime.datetime.now().date().isoformat()}] ") fout.write(msg) fout.write('\n') def play_game(player_1, player_2): log(Fore.CYAN + f"New game starting between {player_1} and {player_2}.") wins = {player_1: 0, player_2: 0} roll_names = list(rolls.keys()) while not find_winner(wins, wins.keys()): roll1 = get_roll(player_1, roll_names) roll2 = random.choice(roll_names) if not roll1: print(Fore.LIGHTRED_EX + "Try again!") print(Fore.LIGHTWHITE_EX) continue log(f"Round: {player_1} roll {roll1} and {player_2} rolls {roll2}") print(Fore.YELLOW + f"{player_1} rolls {roll1}") print(Fore.LIGHTBLUE_EX + f"{player_2} rolls {roll2}") print(Fore.LIGHTWHITE_EX) winner = check_for_winning_throw(player_1, player_2, roll1, roll2) if winner is None: msg = "This round was a tie!" print(msg) log(msg) else: msg = f'{winner} takes the round!' fore = Fore.GREEN if winner == player_1 else Fore.LIGHTRED_EX print(fore + msg + Fore.LIGHTWHITE_EX) log(msg) wins[winner] += 1 msg = f"Score is {player_1}: {wins[player_1]} and {player_2}: {wins[player_2]}." print(msg) log(msg) print() overall_winner = find_winner(wins, wins.keys()) fore = Fore.GREEN if overall_winner == player_1 else Fore.LIGHTRED_EX msg = f"{overall_winner} wins the game!" print(fore + msg + Fore.LIGHTWHITE_EX) log(msg) record_win(overall_winner)
null
158,558
import datetime import platform import random import json import os import colorama from colorama import Fore rolls = {} def log(msg): directory = os.path.dirname(__file__) filename = os.path.join(directory, 'rps.log') with open(filename, 'a', encoding='utf-8') as fout: fout.write(f"[{datetime.datetime.now().date().isoformat()}] ") fout.write(msg) fout.write('\n') def load_rolls(): global rolls directory = os.path.dirname(__file__) filename = os.path.join(directory, 'rolls.json') with open(filename, 'r', encoding='utf-8') as fin: rolls = json.load(fin) log(f"Loaded rolls: {list(rolls.keys())} from {os.path.basename(filename)}.")
null
158,559
import datetime import random import json import os def show_header(): print("---------------------------") print(" Rock Paper Scissors") print(" File I/O Edition") print("---------------------------")
null
158,560
import datetime import random import json import os def load_leaders(): directory = os.path.dirname(__file__) filename = os.path.join(directory, 'leaderboard.json') if not os.path.exists(filename): return {} with open(filename, 'r', encoding='utf-8') as fin: return json.load(fin) def show_leaderboard(): leaders = load_leaders() sorted_leaders = list(leaders.items()) sorted_leaders.sort(key=lambda l: l[1], reverse=True) print() print("---------------------------") print("LEADERS:") for name, wins in sorted_leaders[0:5]: print(f"{wins:,} -- {name}") print("---------------------------") print()
null
158,561
import datetime import random import json import os def get_players(): p1 = input("Player 1, what is your name? ") p2 = "Computer" return p1, p2
null
158,562
import datetime import random import json import os rolls = {} def find_winner(wins, names): best_of = 3 for name in names: if wins.get(name, 0) >= best_of: return name return None def check_for_winning_throw(player_1, player_2, roll1, roll2): winner = None if roll1 == roll2: print("The play was tied!") outcome = rolls.get(roll1, {}) if roll2 in outcome.get('defeats'): return player_1 elif roll2 in outcome.get('defeated_by'): return player_2 return winner def get_roll(player_name, roll_names): print("Available rolls:") for index, r in enumerate(roll_names, start=1): print(f"{index}. {r}") text = input(f"{player_name}, what is your roll? ") selected_index = int(text) - 1 if selected_index < 0 or selected_index >= len(rolls): print(f"Sorry {player_name}, {text} is out of bounds!") return None return roll_names[selected_index] def record_win(winner_name): leaders = load_leaders() if winner_name in leaders: leaders[winner_name] += 1 else: leaders[winner_name] = 1 directory = os.path.dirname(__file__) filename = os.path.join(directory, 'leaderboard.json') with open(filename, 'w', encoding='utf-8') as fout: json.dump(leaders, fout) def log(msg): directory = os.path.dirname(__file__) filename = os.path.join(directory, 'rps.log') with open(filename, 'a', encoding='utf-8') as fout: fout.write(f"[{datetime.datetime.now().date().isoformat()}] ") fout.write(msg) fout.write('\n') def play_game(player_1, player_2): log(f"New game starting between {player_1} and {player_2}.") wins = {player_1: 0, player_2: 0} roll_names = list(rolls.keys()) while not find_winner(wins, wins.keys()): roll1 = get_roll(player_1, roll_names) roll2 = random.choice(roll_names) if not roll1: print("Try again!") continue log(f"Round: {player_1} roll {roll1} and {player_2} rolls {roll2}") print(f"{player_1} roll {roll1}") print(f"{player_2} rolls {roll2}") winner = check_for_winning_throw(player_1, player_2, roll1, roll2) if winner is None: msg = "This round was a tie!" print(msg) log(msg) else: msg = f'{winner} takes the round!' print(msg) log(msg) wins[winner] += 1 msg = f"Score is {player_1}: {wins[player_1]} and {player_2}: {wins[player_2]}." print(msg) log(msg) print() overall_winner = find_winner(wins, wins.keys()) msg = f"{overall_winner} wins the game!" print(msg) log(msg) record_win(overall_winner)
null
158,563
import datetime import random import json import os rolls = {} def log(msg): directory = os.path.dirname(__file__) filename = os.path.join(directory, 'rps.log') with open(filename, 'a', encoding='utf-8') as fout: fout.write(f"[{datetime.datetime.now().date().isoformat()}] ") fout.write(msg) fout.write('\n') def load_rolls(): global rolls directory = os.path.dirname(__file__) filename = os.path.join(directory, 'rolls.json') with open(filename, 'r', encoding='utf-8') as fin: rolls = json.load(fin) log(f"Loaded rolls: {list(rolls.keys())} from {os.path.basename(filename)}.")
null
158,564
import random def show_header(): print("---------------------------") print(" Rock Paper Scissors") print(" Data Structures Edition") print("---------------------------")
null
158,565
import random rolls = { 'rock': { 'defeats': ['scissors'], 'defeated_by': ['paper'] }, 'paper': { 'defeats': ['rock'], 'defeated_by': ['scissors'] }, 'scissors': { 'defeats': ['paper'], 'defeated_by': ['rock'] }, } def find_winner(wins, names): best_of = 3 for name in names: if wins.get(name, 0) >= best_of: return name return None def check_for_winning_throw(player_1, player_2, roll1, roll2): winner = None if roll1 == roll2: print("The play was tied!") outcome = rolls.get(roll1, {}) if roll2 in outcome.get('defeats'): return player_1 elif roll2 in outcome.get('defeated_by'): return player_2 return winner def get_roll(player_name, roll_names): print("Available rolls:") for index, r in enumerate(roll_names, start=1): print(f"{index}. {r}") text = input(f"{player_name}, what is your roll? ") selected_index = int(text) - 1 if selected_index < 0 or selected_index >= len(rolls): print(f"Sorry {player_name}, {text} is out of bounds!") return None return roll_names[selected_index] def play_game(player_1, player_2): wins = {player_1: 0, player_2: 0} roll_names = list(rolls.keys()) while not find_winner(wins, wins.keys()): roll1 = get_roll(player_1, roll_names) roll2 = random.choice(roll_names) if not roll1: print("Try again!") continue print(f"{player_1} roll {roll1}") print(f"{player_2} rolls {roll2}") winner = check_for_winning_throw(player_1, player_2, roll1, roll2) if winner is None: print("This round was a tie!") else: print(f'{winner} takes the round!') wins[winner] += 1 # print(f"Current win status: {wins}") print(f"Score is {player_1}: {wins[player_1]} and {player_2}: {wins[player_2]}.") print() overall_winner = find_winner(wins, wins.keys()) print(f"{overall_winner} wins the game!")
null
158,566
import random def show_header(): print("---------------------------") print(" Rock Paper Scissors") print(" Function Edition") print("---------------------------")
null
158,567
import random def check_for_winning_throw(player_1, player_2, roll1, roll2): # Rock # Rock -> tie # Paper -> lose # Scissors -> win # Paper # Rock -> win # Paper -> tie # Scissors -> lose # Scissors # Rock -> lose # Paper -> win # Scissors -> tie winner = None if roll1 == roll2: print("The play was tied!") elif roll1 == 'rock': if roll2 == 'paper': winner = player_2 elif roll2 == 'scissors': winner = player_1 elif roll1 == 'paper': if roll2 == 'scissors': winner = player_2 elif roll2 == 'rock': winner = player_1 elif roll1 == 'scissors': if roll2 == 'rock': winner = player_2 elif roll2 == 'paper': winner = player_1 return winner def get_roll(player_name, rolls): print("Available rolls:") for index, r in enumerate(rolls, start=1): print(f"{index}. {r}") text = input(f"{player_name}, what is your roll? ") selected_index = int(text) - 1 if selected_index < 0 or selected_index >= len(rolls): print(f"Sorry {player_name}, {text} is out of bounds!") return None return rolls[selected_index] def play_game(player_1, player_2): rounds = 3 wins_p1 = 0 wins_p2 = 0 rolls = ['rock', 'paper', 'scissors'] while wins_p1 < rounds and wins_p2 < rounds: roll1 = get_roll(player_1, rolls) roll2 = random.choice(rolls) if not roll1: print("Try again!") continue print(f"{player_1} roll {roll1}") print(f"{player_2} rolls {roll2}") winner = check_for_winning_throw(player_1, player_2, roll1, roll2) if winner is None: print("This round was a tie!") else: print(f'{winner} takes the round!') if winner == player_1: wins_p1 += 1 elif winner == player_2: wins_p2 += 1 print(f"Score is {player_1}: {wins_p1} and {player_2}: {wins_p2}.") print() if wins_p1 >= rounds: overall_winner = player_1 else: overall_winner = player_2 print(f"{overall_winner} wins the game!")
null
158,568
def choose_location(board, symbol): row = int(input("Choose which row: ")) column = int(input("Choose which column: ")) row -= 1 column -= 1 if row < 0 or row >= len(board): return False if column < 0 or column >= len(board[0]): return False cell = board[row][column] if cell is not None: return False board[row][column] = symbol return True
null
158,569
def show_board(board): for row in board: print("| ", end='') for cell in row: symbol = cell if cell is not None else "_" print(symbol, end=" | ") print()
null
158,570
def announce_turn(player): print() print(f"It's {player}'s turn. Here's the board:") print()
null
158,571
def get_winning_sequences(board): sequences = [] # Win by rows rows = board sequences.extend(rows) # Win by columns for col_idx in range(0, 3): col = [ board[0][col_idx], board[1][col_idx], board[2][col_idx], ] sequences.append(col) # Win by diagonals diagonals = [ [board[0][0], board[1][1], board[2][2]], [board[0][2], board[1][1], board[2][0]], ] sequences.extend(diagonals) return sequences def find_winner(board): sequences = get_winning_sequences(board) for cells in sequences: symbol1 = cells[0] if symbol1 and all(symbol1 == cell for cell in cells): return True return False
null
158,572
import datetime import random import json import os import platform import colorama from colorama import Fore from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter, Completer, Completion def show_header(): print(Fore.LIGHTMAGENTA_EX) print("---------------------------") print(" Rock Paper Scissors") print(" External Libraries Edition") print("---------------------------") print(Fore.WHITE)
null
158,573
import datetime import random import json import os import platform import colorama from colorama import Fore from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter, Completer, Completion def load_leaders(): directory = os.path.dirname(__file__) filename = os.path.join(directory, 'leaderboard.json') if not os.path.exists(filename): return {} with open(filename, 'r', encoding='utf-8') as fin: return json.load(fin) def show_leaderboard(): leaders = load_leaders() sorted_leaders = list(leaders.items()) sorted_leaders.sort(key=lambda l: l[1], reverse=True) print() print("---------------------------") print("LEADERS:") for name, wins in sorted_leaders[0:5]: print(f"{wins:,} -- {name}") print("---------------------------") print()
null
158,574
import datetime import random import json import os import platform import colorama from colorama import Fore from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter, Completer, Completion def get_players(): p1 = input("Player 1, what is your name? ") p2 = "Computer" return p1, p2
null
158,575
import datetime import random import json import os import platform import colorama from colorama import Fore from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter, Completer, Completion rolls = {} def find_winner(wins, names): best_of = 3 for name in names: if wins.get(name, 0) >= best_of: return name return None def check_for_winning_throw(player_1, player_2, roll1, roll2): winner = None if roll1 == roll2: print("The play was tied!") outcome = rolls.get(roll1, {}) if roll2 in outcome.get('defeats'): return player_1 elif roll2 in outcome.get('defeated_by'): return player_2 return winner def get_roll(player_name, roll_names): if os.environ.get('PYCHARM_HOSTED') == "1": print(Fore.LIGHTRED_EX + "Warning: Cannot use fancy prompt dialog in PyCharm.") print(Fore.LIGHTRED_EX + "Run this app outside of PyCharm to see it in action.") val = input(Fore.LIGHTYELLOW_EX + "What is your roll: ") print(Fore.WHITE) return val print(f"Available rolls: {', '.join(roll_names)}.") # word_comp = WordCompleter(roll_names) word_comp = PlayComplete() roll = prompt(f"{player_name}, what is your roll: ", completer=word_comp) if not roll or roll not in roll_names: print(f"Sorry {player_name}, {roll} not valid!") return None return roll def record_win(winner_name): leaders = load_leaders() if winner_name in leaders: leaders[winner_name] += 1 else: leaders[winner_name] = 1 directory = os.path.dirname(__file__) filename = os.path.join(directory, 'leaderboard.json') with open(filename, 'w', encoding='utf-8') as fout: json.dump(leaders, fout) def log(msg): directory = os.path.dirname(__file__) filename = os.path.join(directory, 'rps.log') with open(filename, 'a', encoding='utf-8') as fout: fout.write(f"[{datetime.datetime.now().date().isoformat()}] ") fout.write(msg) fout.write('\n') def play_game(player_1, player_2): log(Fore.CYAN + f"New game starting between {player_1} and {player_2}.") wins = {player_1: 0, player_2: 0} roll_names = list(rolls.keys()) while not find_winner(wins, wins.keys()): roll1 = get_roll(player_1, roll_names) roll2 = random.choice(roll_names) if not roll1: print(Fore.LIGHTRED_EX + "Try again!") print(Fore.WHITE) continue log(f"Round: {player_1} roll {roll1} and {player_2} rolls {roll2}") print(Fore.YELLOW + f"{player_1} rolls {roll1}") print(Fore.LIGHTBLUE_EX + f"{player_2} rolls {roll2}") print(Fore.WHITE) winner = check_for_winning_throw(player_1, player_2, roll1, roll2) if winner is None: msg = "This round was a tie!" print(msg) log(msg) else: msg = f'{winner} takes the round!' fore = Fore.GREEN if winner == player_1 else Fore.LIGHTRED_EX print(fore + msg + Fore.WHITE) log(msg) wins[winner] += 1 msg = f"Score is {player_1}: {wins[player_1]} and {player_2}: {wins[player_2]}." print(msg) log(msg) print() overall_winner = find_winner(wins, wins.keys()) fore = Fore.GREEN if overall_winner == player_1 else Fore.LIGHTRED_EX msg = f"{overall_winner} wins the game!" print(fore + msg + Fore.WHITE) log(msg) record_win(overall_winner)
null
158,576
import datetime import random import json import os import platform import colorama from colorama import Fore from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter, Completer, Completion rolls = {} def log(msg): def load_rolls(): global rolls directory = os.path.dirname(__file__) filename = os.path.join(directory, 'rolls.json') with open(filename, 'r', encoding='utf-8') as fin: rolls = json.load(fin) log(f"Loaded rolls: {list(rolls.keys())} from {os.path.basename(filename)}.")
null
158,577
from os import path import subprocess from livereload import Server from livereload import watcher docsdir = path.dirname(path.abspath(__file__)) build_cmd = [ 'sphinx-build', '-q', '-j', 'auto', '-b', 'html', '-d', path.join(builddir, 'doctrees'), docsdir, path.join(builddir, 'html'), ] def cmd() -> None: print('=== Sphinx Build Start ===') subprocess.run(build_cmd, cwd=docsdir) print('=== Sphinx Build done ===')
null
158,578
from os import path import subprocess from livereload import Server from livereload import watcher docsdir = path.dirname(path.abspath(__file__)) def docs(p: str) -> str: return path.join(docsdir, p)
null
158,579
import asyncio import base64 from collections import OrderedDict import copy import json import logging from types import SimpleNamespace from typing import Awaitable, Dict, List, Optional, Union, TYPE_CHECKING from urllib.parse import unquote from pyee import EventEmitter from pyppeteer.connection import CDPSession from pyppeteer.errors import NetworkError from pyppeteer.frame_manager import FrameManager, Frame from pyppeteer.helper import debugError from pyppeteer.multimap import Multimap The provided code snippet includes necessary dependencies for implementing the `generateRequestHash` function. Write a Python function `def generateRequestHash(request: dict) -> str` to solve the following problem: Generate request hash. Here is the function: def generateRequestHash(request: dict) -> str: """Generate request hash.""" normalizedURL = request.get('url', '') try: normalizedURL = unquote(normalizedURL) except Exception: pass _hash = { 'url': normalizedURL, 'method': request.get('method'), 'postData': request.get('postData'), 'headers': {}, } if not normalizedURL.startswith('data:'): headers = list(request['headers'].keys()) headers.sort() for header in headers: headerValue = request['headers'][header] header = header.lower() if header in [ 'accept', 'referer', 'x-devtools-emulate-network-conditions-client-id', 'cookie', ]: continue _hash['headers'][header] = headerValue return json.dumps(_hash)
Generate request hash.
158,580
import gc import socket from typing import Dict, Optional from pyppeteer.chromium_downloader import check_chromium, chromium_executable from pyppeteer.chromium_downloader import download_chromium The provided code snippet includes necessary dependencies for implementing the `get_free_port` function. Write a Python function `def get_free_port() -> int` to solve the following problem: Get free port. Here is the function: def get_free_port() -> int: """Get free port.""" sock = socket.socket() sock.bind(('localhost', 0)) port = sock.getsockname()[1] sock.close() del sock gc.collect() return port
Get free port.
158,581
import logging from pyppeteer.chromium_downloader import check_chromium, download_chromium def download_chromium() -> None: """Download and extract chromium.""" extract_zip(download_zip(get_url()), DOWNLOADS_FOLDER / REVISION) def check_chromium() -> bool: """Check if chromium is placed at correct path.""" return chromium_executable().exists() The provided code snippet includes necessary dependencies for implementing the `install` function. Write a Python function `def install() -> None` to solve the following problem: Download chromium if not install. Here is the function: def install() -> None: """Download chromium if not install.""" if not check_chromium(): download_chromium() else: logging.getLogger(__name__).warning('chromium is already installed.')
Download chromium if not install.
158,582
import copy import logging import math import os.path from typing import Any, Dict, List, Optional, TYPE_CHECKING from pyppeteer.connection import CDPSession from pyppeteer.execution_context import ExecutionContext, JSHandle from pyppeteer.errors import ElementHandleError, NetworkError from pyppeteer.helper import debugError from pyppeteer.util import merge_dict def _computeQuadArea(quad: List[Dict]) -> float: area = 0 for i, _ in enumerate(quad): p1 = quad[i] p2 = quad[(i + 1) % len(quad)] area += (p1['x'] * p2['y'] - p2['x'] * p1['y']) / 2 return area
null
158,583
import asyncio import atexit from copy import copy import json from urllib.request import urlopen from urllib.error import URLError from http.client import HTTPException import logging import os import os.path from pathlib import Path import shutil import signal import subprocess import sys import tempfile import time from typing import Any, Dict, List, TYPE_CHECKING from pyppeteer import __pyppeteer_home__ from pyppeteer.browser import Browser from pyppeteer.connection import Connection from pyppeteer.chromium_downloader import current_platform from pyppeteer.errors import BrowserError from pyppeteer.helper import addEventListener, debugError, removeEventListeners from pyppeteer.target import Target from pyppeteer.util import check_chromium, chromium_executable from pyppeteer.util import download_chromium, merge_dict, get_free_port class Launcher(object): """Chrome process launcher class.""" def __init__(self, options: Dict[str, Any] = None, # noqa: C901 **kwargs: Any) -> None: """Make new launcher.""" options = merge_dict(options, kwargs) self.port = get_free_port() self.url = f'http://127.0.0.1:{self.port}' self._loop = options.get('loop', asyncio.get_event_loop()) self.chromeClosed = True ignoreDefaultArgs = options.get('ignoreDefaultArgs', False) args: List[str] = options.get('args', list()) self.dumpio = options.get('dumpio', False) executablePath = options.get('executablePath') self.env = options.get('env') self.handleSIGINT = options.get('handleSIGINT', True) self.handleSIGTERM = options.get('handleSIGTERM', True) self.handleSIGHUP = options.get('handleSIGHUP', True) self.ignoreHTTPSErrors = options.get('ignoreHTTPSErrors', False) self.defaultViewport = options.get('defaultViewport', {'width': 800, 'height': 600}) # noqa: E501 self.slowMo = options.get('slowMo', 0) self.timeout = options.get('timeout', 30000) self.autoClose = options.get('autoClose', True) logLevel = options.get('logLevel') if logLevel: logging.getLogger('pyppeteer').setLevel(logLevel) self.chromeArguments: List[str] = list() if not ignoreDefaultArgs: self.chromeArguments.extend(defaultArgs(options)) elif isinstance(ignoreDefaultArgs, list): self.chromeArguments.extend(filter(lambda arg: arg not in ignoreDefaultArgs, defaultArgs(options), )) else: self.chromeArguments.extend(args) self.temporaryUserDataDir: Optional[str] = None if not any(arg for arg in self.chromeArguments if arg.startswith('--remote-debugging-')): self.chromeArguments.append(f'--remote-debugging-port={self.port}') if not any(arg for arg in self.chromeArguments if arg.startswith('--user-data-dir')): if not CHROME_PROFILE_PATH.exists(): CHROME_PROFILE_PATH.mkdir(parents=True) self.temporaryUserDataDir = tempfile.mkdtemp(dir=str(CHROME_PROFILE_PATH)) # noqa: E501 self.chromeArguments.append(f'--user-data-dir={self.temporaryUserDataDir}') # noqa: E501 self.chromeExecutable = executablePath if not self.chromeExecutable: if not check_chromium(): download_chromium() self.chromeExecutable = str(chromium_executable()) self.cmd = [self.chromeExecutable] + self.chromeArguments def _cleanup_tmp_user_data_dir(self) -> None: for retry in range(100): if self.temporaryUserDataDir and os.path.exists(self.temporaryUserDataDir): shutil.rmtree(self.temporaryUserDataDir, ignore_errors=True) if os.path.exists(self.temporaryUserDataDir): time.sleep(0.01) else: break else: raise IOError('Unable to remove Temporary User Data') async def launch(self) -> Browser: # noqa: C901 """Start chrome process and return `Browser` object.""" self.chromeClosed = False self.connection: Optional[Connection] = None options = dict() options['env'] = self.env if not self.dumpio: # discard stdout, it's never read in any case. options['stdout'] = subprocess.DEVNULL options['stderr'] = subprocess.STDOUT self.proc = subprocess.Popen( # type: ignore self.cmd, **options, ) def _close_process(*args: Any, **kwargs: Any) -> None: if not self.chromeClosed: self._loop.run_until_complete(self.killChrome()) # don't forget to close browser process if self.autoClose: atexit.register(_close_process) if self.handleSIGINT: signal.signal(signal.SIGINT, _close_process) if self.handleSIGTERM: signal.signal(signal.SIGTERM, _close_process) if not sys.platform.startswith('win'): # SIGHUP is not defined on windows if self.handleSIGHUP: signal.signal(signal.SIGHUP, _close_process) connectionDelay = self.slowMo self.browserWSEndpoint = get_ws_endpoint(self.url) logger.info(f'Browser listening on: {self.browserWSEndpoint}') self.connection = Connection(self.browserWSEndpoint, self._loop, connectionDelay, ) browser = await Browser.create(self.connection, [], self.ignoreHTTPSErrors, self.defaultViewport, self.proc, self.killChrome) await self.ensureInitialPage(browser) return browser async def ensureInitialPage(self, browser: Browser) -> None: """Wait for initial page target to be created.""" for target in browser.targets(): if target.type == 'page': return initialPagePromise = self._loop.create_future() def initialPageCallback() -> None: initialPagePromise.set_result(True) def check_target(target: Target) -> None: if target.type == 'page': initialPageCallback() listeners = [addEventListener(browser, 'targetcreated', check_target)] await initialPagePromise removeEventListeners(listeners) def waitForChromeToClose(self) -> None: """Terminate chrome.""" if self.proc.poll() is None and not self.chromeClosed: self.chromeClosed = True try: self.proc.terminate() self.proc.wait() except Exception: # browser process may be already closed pass async def killChrome(self) -> None: """Terminate chromium process.""" logger.info('terminate chrome process...') if self.connection and self.connection._connected: try: await self.connection.send('Browser.close') await self.connection.dispose() except Exception as e: # ignore errors on browser termination process debugError(logger, e) if self.temporaryUserDataDir and os.path.exists(self.temporaryUserDataDir): # noqa: E501 # Force kill chrome only when using temporary userDataDir self.waitForChromeToClose() self._cleanup_tmp_user_data_dir() class Browser(EventEmitter): """Browser class. A Browser object is created when pyppeteer connects to chrome, either through :func:`~pyppeteer.launcher.launch` or :func:`~pyppeteer.launcher.connect`. """ Events = SimpleNamespace( TargetCreated='targetcreated', TargetDestroyed='targetdestroyed', TargetChanged='targetchanged', Disconnected='disconnected', ) def __init__(self, connection: Connection, contextIds: List[str], ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], process: Optional[Popen] = None, closeCallback: Callable[[], Awaitable[None]] = None, **kwargs: Any) -> None: super().__init__() self._ignoreHTTPSErrors = ignoreHTTPSErrors self._defaultViewport = defaultViewport self._process = process self._screenshotTaskQueue: List = [] self._connection = connection loop = self._connection._loop def _dummy_callback() -> Awaitable[None]: fut = loop.create_future() fut.set_result(None) return fut if closeCallback: self._closeCallback = closeCallback else: self._closeCallback = _dummy_callback self._defaultContext = BrowserContext(self, None) self._contexts: Dict[str, BrowserContext] = dict() for contextId in contextIds: self._contexts[contextId] = BrowserContext(self, contextId) self._targets: Dict[str, Target] = dict() self._connection.setClosedCallback( lambda: self.emit(Browser.Events.Disconnected) ) self._connection.on( 'Target.targetCreated', lambda event: loop.create_task(self._targetCreated(event)), ) self._connection.on( 'Target.targetDestroyed', lambda event: loop.create_task(self._targetDestroyed(event)), ) self._connection.on( 'Target.targetInfoChanged', lambda event: loop.create_task(self._targetInfoChanged(event)), ) def process(self) -> Optional[Popen]: """Return process of this browser. If browser instance is created by :func:`pyppeteer.launcher.connect`, return ``None``. """ return self._process async def createIncogniteBrowserContext(self) -> 'BrowserContext': """[Deprecated] Miss spelled method. Use :meth:`createIncognitoBrowserContext` method instead. """ logger.warning( 'createIncogniteBrowserContext is deprecated. ' 'Use createIncognitoBrowserContext instead.' ) return await self.createIncognitoBrowserContext() async def createIncognitoBrowserContext(self) -> 'BrowserContext': """Create a new incognito browser context. This won't share cookies/cache with other browser contexts. .. code:: browser = await launch() # Create a new incognito browser context. context = await browser.createIncognitoBrowserContext() # Create a new page in a pristine context. page = await context.newPage() # Do stuff await page.goto('https://example.com') ... """ obj = await self._connection.send('Target.createBrowserContext') browserContextId = obj['browserContextId'] context = BrowserContext(self, browserContextId) # noqa: E501 self._contexts[browserContextId] = context return context def browserContexts(self) -> List['BrowserContext']: """Return a list of all open browser contexts. In a newly created browser, this will return a single instance of ``[BrowserContext]`` """ return [self._defaultContext] + [context for context in self._contexts.values()] # noqa: E501 async def _disposeContext(self, contextId: str) -> None: await self._connection.send('Target.disposeBrowserContext', { 'browserContextId': contextId, }) self._contexts.pop(contextId, None) async def create(connection: Connection, contextIds: List[str], ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], process: Optional[Popen] = None, closeCallback: Callable[[], Awaitable[None]] = None, **kwargs: Any) -> 'Browser': """Create browser object.""" browser = Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process, closeCallback) await connection.send('Target.setDiscoverTargets', {'discover': True}) return browser async def _targetCreated(self, event: Dict) -> None: targetInfo = event['targetInfo'] browserContextId = targetInfo.get('browserContextId') if browserContextId and browserContextId in self._contexts: context = self._contexts[browserContextId] else: context = self._defaultContext target = Target( targetInfo, context, lambda: self._connection.createSession(targetInfo), self._ignoreHTTPSErrors, self._defaultViewport, self._screenshotTaskQueue, self._connection._loop, ) if targetInfo['targetId'] in self._targets: raise BrowserError('target should not exist before create.') self._targets[targetInfo['targetId']] = target if await target._initializedPromise: self.emit(Browser.Events.TargetCreated, target) context.emit(BrowserContext.Events.TargetCreated, target) async def _targetDestroyed(self, event: Dict) -> None: target = self._targets[event['targetId']] del self._targets[event['targetId']] target._closedCallback() if await target._initializedPromise: self.emit(Browser.Events.TargetDestroyed, target) target.browserContext.emit(BrowserContext.Events.TargetDestroyed, target) # noqa: E501 target._initializedCallback(False) async def _targetInfoChanged(self, event: Dict) -> None: target = self._targets.get(event['targetInfo']['targetId']) if not target: raise BrowserError('target should exist before targetInfoChanged') previousURL = target.url wasInitialized = target._isInitialized target._targetInfoChanged(event['targetInfo']) if wasInitialized and previousURL != target.url: self.emit(Browser.Events.TargetChanged, target) target.browserContext.emit(BrowserContext.Events.TargetChanged, target) # noqa: E501 def wsEndpoint(self) -> str: """Return websocket end point url.""" return self._connection.url async def newPage(self) -> Page: """Make new page on this browser and return its object.""" return await self._defaultContext.newPage() async def _createPageInContext(self, contextId: Optional[str]) -> Page: options = {'url': 'about:blank'} if contextId: options['browserContextId'] = contextId targetId = (await self._connection.send( 'Target.createTarget', options)).get('targetId') target = self._targets.get(targetId) if target is None: raise BrowserError('Failed to create target for page.') if not await target._initializedPromise: raise BrowserError('Failed to create target for page.') page = await target.page() if page is None: raise BrowserError('Failed to create page.') return page def targets(self) -> List[Target]: """Get a list of all active targets inside the browser. In case of multiple browser contexts, the method will return a list with all the targets in all browser contexts. """ return [target for target in self._targets.values() if target._isInitialized] async def pages(self) -> List[Page]: """Get all pages of this browser. Non visible pages, such as ``"background_page"``, will not be listed here. You can find then using :meth:`pyppeteer.target.Target.page`. In case of multiple browser contexts, this method will return a list with all the pages in all browser contexts. """ # Using asyncio.gather is better for performance pages: List[Page] = list() for context in self.browserContexts: pages.extend(await context.pages()) return pages async def version(self) -> str: """Get version of the browser.""" version = await self._getVersion() return version['product'] async def userAgent(self) -> str: """Return browser's original user agent. .. note:: Pages can override browser user agent with :meth:`pyppeteer.page.Page.setUserAgent`. """ version = await self._getVersion() return version.get('userAgent', '') async def close(self) -> None: """Close connections and terminate browser process.""" await self._closeCallback() # Launcher.killChrome() async def disconnect(self) -> None: """Disconnect browser.""" await self._connection.dispose() for target in self._targets.values(): if not target._isInitialized: target._initializedCallback(False) def _getVersion(self) -> Awaitable: return self._connection.send('Browser.getVersion') The provided code snippet includes necessary dependencies for implementing the `launch` function. Write a Python function `async def launch(options: dict = None, **kwargs: Any) -> Browser` to solve the following problem: Start chrome process and return :class:`~pyppeteer.browser.Browser`. This function is a shortcut to :meth:`Launcher(options, **kwargs).launch`. Available options are: * ``ignoreHTTPSErrors`` (bool): Whether to ignore HTTPS errors. Defaults to ``False``. * ``headless`` (bool): Whether to run browser in headless mode. Defaults to ``True`` unless ``appMode`` or ``devtools`` options is ``True``. * ``executablePath`` (str): Path to a Chromium or Chrome executable to run instead of default bundled Chromium. * ``slowMo`` (int|float): Slow down pyppeteer operations by the specified amount of milliseconds. * ``defaultViewport`` (dict): Set a consistent viewport for each page. Defaults to an 800x600 viewport. ``None`` disables default viewport. * ``width`` (int): page width in pixels. * ``height`` (int): page height in pixels. * ``deviceScaleFactor`` (int|float): Specify device scale factor (can be thought as dpr). Defaults to ``1``. * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken into account. Defaults to ``False``. * ``hasTouch`` (bool): Specify if viewport supports touch events. Defaults to ``False``. * ``isLandscape`` (bool): Specify if viewport is in landscape mode. Defaults to ``False``. * ``args`` (List[str]): Additional arguments (flags) to pass to the browser process. * ``ignoreDefaultArgs`` (bool or List[str]): If ``True``, do not use :func:`~pyppeteer.defaultArgs`. If list is given, then filter out given default arguments. Dangerous option; use with care. Defaults to ``False``. * ``handleSIGINT`` (bool): Close the browser process on Ctrl+C. Defaults to ``True``. * ``handleSIGTERM`` (bool): Close the browser process on SIGTERM. Defaults to ``True``. * ``handleSIGHUP`` (bool): Close the browser process on SIGHUP. Defaults to ``True``. * ``dumpio`` (bool): Whether to pipe the browser process stdout and stderr into ``process.stdout`` and ``process.stderr``. Defaults to ``False``. * ``userDataDir`` (str): Path to a user data directory. * ``env`` (dict): Specify environment variables that will be visible to the browser. Defaults to same as python process. * ``devtools`` (bool): Whether to auto-open a DevTools panel for each tab. If this option is ``True``, the ``headless`` option will be set ``False``. * ``logLevel`` (int|str): Log level to print logs. Defaults to same as the root logger. * ``autoClose`` (bool): Automatically close browser process when script completed. Defaults to ``True``. * ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**). * ``appMode`` (bool): Deprecated. This function combines 3 steps: 1. Infer a set of flags to launch chromium with using :func:`~pyppeteer.defaultArgs`. 2. Launch browser and start managing its process according to the ``executablePath``, ``handleSIGINT``, ``dumpio``, and other options. 3. Create an instance of :class:`~pyppeteer.browser.Browser` class and initialize it with ``defaultViewport``, ``slowMo``, and ``ignoreHTTPSErrors``. ``ignoreDefaultArgs`` option can be used to customize behavior on the (1) step. For example, to filter out ``--mute-audio`` from default arguments: .. code:: browser = await launch(ignoreDefaultArgs=['--mute-audio']) .. note:: Pyppeteer can also be used to control the Chrome browser, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use ``executablePath`` option with extreme caution. Here is the function: async def launch(options: dict = None, **kwargs: Any) -> Browser: """Start chrome process and return :class:`~pyppeteer.browser.Browser`. This function is a shortcut to :meth:`Launcher(options, **kwargs).launch`. Available options are: * ``ignoreHTTPSErrors`` (bool): Whether to ignore HTTPS errors. Defaults to ``False``. * ``headless`` (bool): Whether to run browser in headless mode. Defaults to ``True`` unless ``appMode`` or ``devtools`` options is ``True``. * ``executablePath`` (str): Path to a Chromium or Chrome executable to run instead of default bundled Chromium. * ``slowMo`` (int|float): Slow down pyppeteer operations by the specified amount of milliseconds. * ``defaultViewport`` (dict): Set a consistent viewport for each page. Defaults to an 800x600 viewport. ``None`` disables default viewport. * ``width`` (int): page width in pixels. * ``height`` (int): page height in pixels. * ``deviceScaleFactor`` (int|float): Specify device scale factor (can be thought as dpr). Defaults to ``1``. * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken into account. Defaults to ``False``. * ``hasTouch`` (bool): Specify if viewport supports touch events. Defaults to ``False``. * ``isLandscape`` (bool): Specify if viewport is in landscape mode. Defaults to ``False``. * ``args`` (List[str]): Additional arguments (flags) to pass to the browser process. * ``ignoreDefaultArgs`` (bool or List[str]): If ``True``, do not use :func:`~pyppeteer.defaultArgs`. If list is given, then filter out given default arguments. Dangerous option; use with care. Defaults to ``False``. * ``handleSIGINT`` (bool): Close the browser process on Ctrl+C. Defaults to ``True``. * ``handleSIGTERM`` (bool): Close the browser process on SIGTERM. Defaults to ``True``. * ``handleSIGHUP`` (bool): Close the browser process on SIGHUP. Defaults to ``True``. * ``dumpio`` (bool): Whether to pipe the browser process stdout and stderr into ``process.stdout`` and ``process.stderr``. Defaults to ``False``. * ``userDataDir`` (str): Path to a user data directory. * ``env`` (dict): Specify environment variables that will be visible to the browser. Defaults to same as python process. * ``devtools`` (bool): Whether to auto-open a DevTools panel for each tab. If this option is ``True``, the ``headless`` option will be set ``False``. * ``logLevel`` (int|str): Log level to print logs. Defaults to same as the root logger. * ``autoClose`` (bool): Automatically close browser process when script completed. Defaults to ``True``. * ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**). * ``appMode`` (bool): Deprecated. This function combines 3 steps: 1. Infer a set of flags to launch chromium with using :func:`~pyppeteer.defaultArgs`. 2. Launch browser and start managing its process according to the ``executablePath``, ``handleSIGINT``, ``dumpio``, and other options. 3. Create an instance of :class:`~pyppeteer.browser.Browser` class and initialize it with ``defaultViewport``, ``slowMo``, and ``ignoreHTTPSErrors``. ``ignoreDefaultArgs`` option can be used to customize behavior on the (1) step. For example, to filter out ``--mute-audio`` from default arguments: .. code:: browser = await launch(ignoreDefaultArgs=['--mute-audio']) .. note:: Pyppeteer can also be used to control the Chrome browser, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use ``executablePath`` option with extreme caution. """ return await Launcher(options, **kwargs).launch()
Start chrome process and return :class:`~pyppeteer.browser.Browser`. This function is a shortcut to :meth:`Launcher(options, **kwargs).launch`. Available options are: * ``ignoreHTTPSErrors`` (bool): Whether to ignore HTTPS errors. Defaults to ``False``. * ``headless`` (bool): Whether to run browser in headless mode. Defaults to ``True`` unless ``appMode`` or ``devtools`` options is ``True``. * ``executablePath`` (str): Path to a Chromium or Chrome executable to run instead of default bundled Chromium. * ``slowMo`` (int|float): Slow down pyppeteer operations by the specified amount of milliseconds. * ``defaultViewport`` (dict): Set a consistent viewport for each page. Defaults to an 800x600 viewport. ``None`` disables default viewport. * ``width`` (int): page width in pixels. * ``height`` (int): page height in pixels. * ``deviceScaleFactor`` (int|float): Specify device scale factor (can be thought as dpr). Defaults to ``1``. * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken into account. Defaults to ``False``. * ``hasTouch`` (bool): Specify if viewport supports touch events. Defaults to ``False``. * ``isLandscape`` (bool): Specify if viewport is in landscape mode. Defaults to ``False``. * ``args`` (List[str]): Additional arguments (flags) to pass to the browser process. * ``ignoreDefaultArgs`` (bool or List[str]): If ``True``, do not use :func:`~pyppeteer.defaultArgs`. If list is given, then filter out given default arguments. Dangerous option; use with care. Defaults to ``False``. * ``handleSIGINT`` (bool): Close the browser process on Ctrl+C. Defaults to ``True``. * ``handleSIGTERM`` (bool): Close the browser process on SIGTERM. Defaults to ``True``. * ``handleSIGHUP`` (bool): Close the browser process on SIGHUP. Defaults to ``True``. * ``dumpio`` (bool): Whether to pipe the browser process stdout and stderr into ``process.stdout`` and ``process.stderr``. Defaults to ``False``. * ``userDataDir`` (str): Path to a user data directory. * ``env`` (dict): Specify environment variables that will be visible to the browser. Defaults to same as python process. * ``devtools`` (bool): Whether to auto-open a DevTools panel for each tab. If this option is ``True``, the ``headless`` option will be set ``False``. * ``logLevel`` (int|str): Log level to print logs. Defaults to same as the root logger. * ``autoClose`` (bool): Automatically close browser process when script completed. Defaults to ``True``. * ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**). * ``appMode`` (bool): Deprecated. This function combines 3 steps: 1. Infer a set of flags to launch chromium with using :func:`~pyppeteer.defaultArgs`. 2. Launch browser and start managing its process according to the ``executablePath``, ``handleSIGINT``, ``dumpio``, and other options. 3. Create an instance of :class:`~pyppeteer.browser.Browser` class and initialize it with ``defaultViewport``, ``slowMo``, and ``ignoreHTTPSErrors``. ``ignoreDefaultArgs`` option can be used to customize behavior on the (1) step. For example, to filter out ``--mute-audio`` from default arguments: .. code:: browser = await launch(ignoreDefaultArgs=['--mute-audio']) .. note:: Pyppeteer can also be used to control the Chrome browser, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use ``executablePath`` option with extreme caution.
158,584
import asyncio import atexit from copy import copy import json from urllib.request import urlopen from urllib.error import URLError from http.client import HTTPException import logging import os import os.path from pathlib import Path import shutil import signal import subprocess import sys import tempfile import time from typing import Any, Dict, List, TYPE_CHECKING from pyppeteer import __pyppeteer_home__ from pyppeteer.browser import Browser from pyppeteer.connection import Connection from pyppeteer.chromium_downloader import current_platform from pyppeteer.errors import BrowserError from pyppeteer.helper import addEventListener, debugError, removeEventListeners from pyppeteer.target import Target from pyppeteer.util import check_chromium, chromium_executable from pyppeteer.util import download_chromium, merge_dict, get_free_port def get_ws_endpoint(url) -> str: url = url + '/json/version' timeout = time.time() + 30 while (True): if time.time() > timeout: raise BrowserError('Browser closed unexpectedly:\n') try: with urlopen(url) as f: data = json.loads(f.read().decode()) break except (URLError, HTTPException): pass time.sleep(0.1) return data['webSocketDebuggerUrl'] class Browser(EventEmitter): """Browser class. A Browser object is created when pyppeteer connects to chrome, either through :func:`~pyppeteer.launcher.launch` or :func:`~pyppeteer.launcher.connect`. """ Events = SimpleNamespace( TargetCreated='targetcreated', TargetDestroyed='targetdestroyed', TargetChanged='targetchanged', Disconnected='disconnected', ) def __init__(self, connection: Connection, contextIds: List[str], ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], process: Optional[Popen] = None, closeCallback: Callable[[], Awaitable[None]] = None, **kwargs: Any) -> None: super().__init__() self._ignoreHTTPSErrors = ignoreHTTPSErrors self._defaultViewport = defaultViewport self._process = process self._screenshotTaskQueue: List = [] self._connection = connection loop = self._connection._loop def _dummy_callback() -> Awaitable[None]: fut = loop.create_future() fut.set_result(None) return fut if closeCallback: self._closeCallback = closeCallback else: self._closeCallback = _dummy_callback self._defaultContext = BrowserContext(self, None) self._contexts: Dict[str, BrowserContext] = dict() for contextId in contextIds: self._contexts[contextId] = BrowserContext(self, contextId) self._targets: Dict[str, Target] = dict() self._connection.setClosedCallback( lambda: self.emit(Browser.Events.Disconnected) ) self._connection.on( 'Target.targetCreated', lambda event: loop.create_task(self._targetCreated(event)), ) self._connection.on( 'Target.targetDestroyed', lambda event: loop.create_task(self._targetDestroyed(event)), ) self._connection.on( 'Target.targetInfoChanged', lambda event: loop.create_task(self._targetInfoChanged(event)), ) def process(self) -> Optional[Popen]: """Return process of this browser. If browser instance is created by :func:`pyppeteer.launcher.connect`, return ``None``. """ return self._process async def createIncogniteBrowserContext(self) -> 'BrowserContext': """[Deprecated] Miss spelled method. Use :meth:`createIncognitoBrowserContext` method instead. """ logger.warning( 'createIncogniteBrowserContext is deprecated. ' 'Use createIncognitoBrowserContext instead.' ) return await self.createIncognitoBrowserContext() async def createIncognitoBrowserContext(self) -> 'BrowserContext': """Create a new incognito browser context. This won't share cookies/cache with other browser contexts. .. code:: browser = await launch() # Create a new incognito browser context. context = await browser.createIncognitoBrowserContext() # Create a new page in a pristine context. page = await context.newPage() # Do stuff await page.goto('https://example.com') ... """ obj = await self._connection.send('Target.createBrowserContext') browserContextId = obj['browserContextId'] context = BrowserContext(self, browserContextId) # noqa: E501 self._contexts[browserContextId] = context return context def browserContexts(self) -> List['BrowserContext']: """Return a list of all open browser contexts. In a newly created browser, this will return a single instance of ``[BrowserContext]`` """ return [self._defaultContext] + [context for context in self._contexts.values()] # noqa: E501 async def _disposeContext(self, contextId: str) -> None: await self._connection.send('Target.disposeBrowserContext', { 'browserContextId': contextId, }) self._contexts.pop(contextId, None) async def create(connection: Connection, contextIds: List[str], ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], process: Optional[Popen] = None, closeCallback: Callable[[], Awaitable[None]] = None, **kwargs: Any) -> 'Browser': """Create browser object.""" browser = Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process, closeCallback) await connection.send('Target.setDiscoverTargets', {'discover': True}) return browser async def _targetCreated(self, event: Dict) -> None: targetInfo = event['targetInfo'] browserContextId = targetInfo.get('browserContextId') if browserContextId and browserContextId in self._contexts: context = self._contexts[browserContextId] else: context = self._defaultContext target = Target( targetInfo, context, lambda: self._connection.createSession(targetInfo), self._ignoreHTTPSErrors, self._defaultViewport, self._screenshotTaskQueue, self._connection._loop, ) if targetInfo['targetId'] in self._targets: raise BrowserError('target should not exist before create.') self._targets[targetInfo['targetId']] = target if await target._initializedPromise: self.emit(Browser.Events.TargetCreated, target) context.emit(BrowserContext.Events.TargetCreated, target) async def _targetDestroyed(self, event: Dict) -> None: target = self._targets[event['targetId']] del self._targets[event['targetId']] target._closedCallback() if await target._initializedPromise: self.emit(Browser.Events.TargetDestroyed, target) target.browserContext.emit(BrowserContext.Events.TargetDestroyed, target) # noqa: E501 target._initializedCallback(False) async def _targetInfoChanged(self, event: Dict) -> None: target = self._targets.get(event['targetInfo']['targetId']) if not target: raise BrowserError('target should exist before targetInfoChanged') previousURL = target.url wasInitialized = target._isInitialized target._targetInfoChanged(event['targetInfo']) if wasInitialized and previousURL != target.url: self.emit(Browser.Events.TargetChanged, target) target.browserContext.emit(BrowserContext.Events.TargetChanged, target) # noqa: E501 def wsEndpoint(self) -> str: """Return websocket end point url.""" return self._connection.url async def newPage(self) -> Page: """Make new page on this browser and return its object.""" return await self._defaultContext.newPage() async def _createPageInContext(self, contextId: Optional[str]) -> Page: options = {'url': 'about:blank'} if contextId: options['browserContextId'] = contextId targetId = (await self._connection.send( 'Target.createTarget', options)).get('targetId') target = self._targets.get(targetId) if target is None: raise BrowserError('Failed to create target for page.') if not await target._initializedPromise: raise BrowserError('Failed to create target for page.') page = await target.page() if page is None: raise BrowserError('Failed to create page.') return page def targets(self) -> List[Target]: """Get a list of all active targets inside the browser. In case of multiple browser contexts, the method will return a list with all the targets in all browser contexts. """ return [target for target in self._targets.values() if target._isInitialized] async def pages(self) -> List[Page]: """Get all pages of this browser. Non visible pages, such as ``"background_page"``, will not be listed here. You can find then using :meth:`pyppeteer.target.Target.page`. In case of multiple browser contexts, this method will return a list with all the pages in all browser contexts. """ # Using asyncio.gather is better for performance pages: List[Page] = list() for context in self.browserContexts: pages.extend(await context.pages()) return pages async def version(self) -> str: """Get version of the browser.""" version = await self._getVersion() return version['product'] async def userAgent(self) -> str: """Return browser's original user agent. .. note:: Pages can override browser user agent with :meth:`pyppeteer.page.Page.setUserAgent`. """ version = await self._getVersion() return version.get('userAgent', '') async def close(self) -> None: """Close connections and terminate browser process.""" await self._closeCallback() # Launcher.killChrome() async def disconnect(self) -> None: """Disconnect browser.""" await self._connection.dispose() for target in self._targets.values(): if not target._isInitialized: target._initializedCallback(False) def _getVersion(self) -> Awaitable: return self._connection.send('Browser.getVersion') class Connection(EventEmitter): """Connection management class.""" def __init__(self, url: str, loop: asyncio.AbstractEventLoop, delay: int = 0) -> None: """Make connection. :arg str url: WebSocket url to connect devtool. :arg int delay: delay to wait before processing received messages. """ super().__init__() self._url = url self._lastId = 0 self._callbacks: Dict[int, asyncio.Future] = dict() self._delay = delay / 1000 self._loop = loop self._sessions: Dict[str, CDPSession] = dict() self.connection: CDPSession self._connected = False self._ws = ws_connect(self._url, max_size=None, loop=self._loop, ping_interval=None, ping_timeout=None) self._recv_fut = self._loop.create_task(self._recv_loop()) self._closeCallback: Optional[Callable[[], None]] = None def url(self) -> str: """Get connected WebSocket url.""" return self._url async def _recv_loop(self) -> None: async with self._ws as connection: self._connected = True self.connection = connection while self._connected: try: resp = await self.connection.recv() if resp: await self._on_message(resp) except (websockets.ConnectionClosed, ConnectionResetError): logger.info('connection closed') break await asyncio.sleep(0) if self._connected: self._loop.create_task(self.dispose()) async def _async_send(self, msg: str, callback_id: int) -> None: while not self._connected: await asyncio.sleep(self._delay) try: await self.connection.send(msg) except websockets.ConnectionClosed: logger.error('connection unexpectedly closed') callback = self._callbacks.get(callback_id, None) if callback and not callback.done(): callback.set_result(None) await self.dispose() def send(self, method: str, params: dict = None) -> Awaitable: """Send message via the connection.""" # Detect connection availability from the second transmission if self._lastId and not self._connected: raise ConnectionError('Connection is closed') if params is None: params = dict() self._lastId += 1 _id = self._lastId msg = json.dumps(dict( id=_id, method=method, params=params, )) logger_connection.debug(f'SEND: {msg}') self._loop.create_task(self._async_send(msg, _id)) callback = self._loop.create_future() self._callbacks[_id] = callback callback.error: Exception = NetworkError() # type: ignore callback.method: str = method # type: ignore return callback def _on_response(self, msg: dict) -> None: callback = self._callbacks.pop(msg.get('id', -1)) if msg.get('error'): callback.set_exception( _createProtocolError( callback.error, # type: ignore callback.method, # type: ignore msg ) ) else: callback.set_result(msg.get('result')) def _on_query(self, msg: dict) -> None: params = msg.get('params', {}) method = msg.get('method', '') sessionId = params.get('sessionId') if method == 'Target.receivedMessageFromTarget': session = self._sessions.get(sessionId) if session: session._on_message(params.get('message')) elif method == 'Target.detachedFromTarget': session = self._sessions.get(sessionId) if session: session._on_closed() del self._sessions[sessionId] else: self.emit(method, params) def setClosedCallback(self, callback: Callable[[], None]) -> None: """Set closed callback.""" self._closeCallback = callback async def _on_message(self, message: str) -> None: await asyncio.sleep(self._delay) logger_connection.debug(f'RECV: {message}') msg = json.loads(message) if msg.get('id') in self._callbacks: self._on_response(msg) else: self._on_query(msg) async def _on_close(self) -> None: if self._closeCallback: self._closeCallback() self._closeCallback = None for cb in self._callbacks.values(): cb.set_exception(_rewriteError( cb.error, # type: ignore f'Protocol error {cb.method}: Target closed.', # type: ignore )) self._callbacks.clear() for session in self._sessions.values(): session._on_closed() self._sessions.clear() # close connection if hasattr(self, 'connection'): # may not have connection await self.connection.close() if not self._recv_fut.done(): self._recv_fut.cancel() async def dispose(self) -> None: """Close all connection.""" self._connected = False await self._on_close() async def createSession(self, targetInfo: Dict) -> 'CDPSession': """Create new session.""" resp = await self.send( 'Target.attachToTarget', {'targetId': targetInfo['targetId']} ) sessionId = resp.get('sessionId') session = CDPSession(self, targetInfo['type'], sessionId, self._loop) self._sessions[sessionId] = session return session class BrowserError(PyppeteerError): # noqa: D204 """Exception raised from browser.""" pass def merge_dict(dict1: Optional[Dict], dict2: Optional[Dict]) -> Dict: """Merge two dictionaries into new one.""" new_dict = {} if dict1: new_dict.update(dict1) if dict2: new_dict.update(dict2) return new_dict The provided code snippet includes necessary dependencies for implementing the `connect` function. Write a Python function `async def connect(options: dict = None, **kwargs: Any) -> Browser` to solve the following problem: Connect to the existing chrome. ``browserWSEndpoint`` or ``browserURL`` option is necessary to connect to the chrome. The format of ``browserWSEndpoint`` is ``ws://${host}:${port}/devtools/browser/<id>`` and format of ``browserURL`` is ``http://127.0.0.1:9222```. The value of ``browserWSEndpoint`` can get by :attr:`~pyppeteer.browser.Browser.wsEndpoint`. Available options are: * ``browserWSEndpoint`` (str): A browser websocket endpoint to connect to. * ``browserURL`` (str): A browser URL to connect to. * ``ignoreHTTPSErrors`` (bool): Whether to ignore HTTPS errors. Defaults to ``False``. * ``defaultViewport`` (dict): Set a consistent viewport for each page. Defaults to an 800x600 viewport. ``None`` disables default viewport. * ``width`` (int): page width in pixels. * ``height`` (int): page height in pixels. * ``deviceScaleFactor`` (int|float): Specify device scale factor (can be thought as dpr). Defaults to ``1``. * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken into account. Defaults to ``False``. * ``hasTouch`` (bool): Specify if viewport supports touch events. Defaults to ``False``. * ``isLandscape`` (bool): Specify if viewport is in landscape mode. Defaults to ``False``. * ``slowMo`` (int|float): Slow down pyppeteer's by the specified amount of milliseconds. * ``logLevel`` (int|str): Log level to print logs. Defaults to same as the root logger. * ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**). Here is the function: async def connect(options: dict = None, **kwargs: Any) -> Browser: """Connect to the existing chrome. ``browserWSEndpoint`` or ``browserURL`` option is necessary to connect to the chrome. The format of ``browserWSEndpoint`` is ``ws://${host}:${port}/devtools/browser/<id>`` and format of ``browserURL`` is ``http://127.0.0.1:9222```. The value of ``browserWSEndpoint`` can get by :attr:`~pyppeteer.browser.Browser.wsEndpoint`. Available options are: * ``browserWSEndpoint`` (str): A browser websocket endpoint to connect to. * ``browserURL`` (str): A browser URL to connect to. * ``ignoreHTTPSErrors`` (bool): Whether to ignore HTTPS errors. Defaults to ``False``. * ``defaultViewport`` (dict): Set a consistent viewport for each page. Defaults to an 800x600 viewport. ``None`` disables default viewport. * ``width`` (int): page width in pixels. * ``height`` (int): page height in pixels. * ``deviceScaleFactor`` (int|float): Specify device scale factor (can be thought as dpr). Defaults to ``1``. * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken into account. Defaults to ``False``. * ``hasTouch`` (bool): Specify if viewport supports touch events. Defaults to ``False``. * ``isLandscape`` (bool): Specify if viewport is in landscape mode. Defaults to ``False``. * ``slowMo`` (int|float): Slow down pyppeteer's by the specified amount of milliseconds. * ``logLevel`` (int|str): Log level to print logs. Defaults to same as the root logger. * ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**). """ options = merge_dict(options, kwargs) logLevel = options.get('logLevel') if logLevel: logging.getLogger('pyppeteer').setLevel(logLevel) browserWSEndpoint = options.get('browserWSEndpoint') if not browserWSEndpoint: browserURL = options.get('browserURL') if not browserURL: raise BrowserError('Need `browserWSEndpoint` or `browserURL` option.') browserWSEndpoint = get_ws_endpoint(browserURL) connectionDelay = options.get('slowMo', 0) connection = Connection(browserWSEndpoint, options.get('loop', asyncio.get_event_loop()), connectionDelay) browserContextIds = (await connection.send('Target.getBrowserContexts')).get('browserContextIds', []) ignoreHTTPSErrors = bool(options.get('ignoreHTTPSErrors', False)) defaultViewport = options.get('defaultViewport', {'width': 800, 'height': 600}) return await Browser.create(connection, browserContextIds, ignoreHTTPSErrors, defaultViewport, None, lambda: connection.send('Browser.close'))
Connect to the existing chrome. ``browserWSEndpoint`` or ``browserURL`` option is necessary to connect to the chrome. The format of ``browserWSEndpoint`` is ``ws://${host}:${port}/devtools/browser/<id>`` and format of ``browserURL`` is ``http://127.0.0.1:9222```. The value of ``browserWSEndpoint`` can get by :attr:`~pyppeteer.browser.Browser.wsEndpoint`. Available options are: * ``browserWSEndpoint`` (str): A browser websocket endpoint to connect to. * ``browserURL`` (str): A browser URL to connect to. * ``ignoreHTTPSErrors`` (bool): Whether to ignore HTTPS errors. Defaults to ``False``. * ``defaultViewport`` (dict): Set a consistent viewport for each page. Defaults to an 800x600 viewport. ``None`` disables default viewport. * ``width`` (int): page width in pixels. * ``height`` (int): page height in pixels. * ``deviceScaleFactor`` (int|float): Specify device scale factor (can be thought as dpr). Defaults to ``1``. * ``isMobile`` (bool): Whether the ``meta viewport`` tag is taken into account. Defaults to ``False``. * ``hasTouch`` (bool): Specify if viewport supports touch events. Defaults to ``False``. * ``isLandscape`` (bool): Specify if viewport is in landscape mode. Defaults to ``False``. * ``slowMo`` (int|float): Slow down pyppeteer's by the specified amount of milliseconds. * ``logLevel`` (int|str): Log level to print logs. Defaults to same as the root logger. * ``loop`` (asyncio.AbstractEventLoop): Event loop (**experimental**).
158,585
import asyncio import atexit from copy import copy import json from urllib.request import urlopen from urllib.error import URLError from http.client import HTTPException import logging import os import os.path from pathlib import Path import shutil import signal import subprocess import sys import tempfile import time from typing import Any, Dict, List, TYPE_CHECKING from pyppeteer import __pyppeteer_home__ from pyppeteer.browser import Browser from pyppeteer.connection import Connection from pyppeteer.chromium_downloader import current_platform from pyppeteer.errors import BrowserError from pyppeteer.helper import addEventListener, debugError, removeEventListeners from pyppeteer.target import Target from pyppeteer.util import check_chromium, chromium_executable from pyppeteer.util import download_chromium, merge_dict, get_free_port The provided code snippet includes necessary dependencies for implementing the `executablePath` function. Write a Python function `def executablePath() -> str` to solve the following problem: Get executable path of default chromium. Here is the function: def executablePath() -> str: """Get executable path of default chromium.""" return str(chromium_executable())
Get executable path of default chromium.
158,586
import asyncio import atexit from copy import copy import json from urllib.request import urlopen from urllib.error import URLError from http.client import HTTPException import logging import os import os.path from pathlib import Path import shutil import signal import subprocess import sys import tempfile import time from typing import Any, Dict, List, TYPE_CHECKING from pyppeteer import __pyppeteer_home__ from pyppeteer.browser import Browser from pyppeteer.connection import Connection from pyppeteer.chromium_downloader import current_platform from pyppeteer.errors import BrowserError from pyppeteer.helper import addEventListener, debugError, removeEventListeners from pyppeteer.target import Target from pyppeteer.util import check_chromium, chromium_executable from pyppeteer.util import download_chromium, merge_dict, get_free_port DEFAULT_ARGS = [ '--disable-background-networking', '--disable-background-timer-throttling', '--disable-breakpad', '--disable-browser-side-navigation', '--disable-client-side-phishing-detection', '--disable-default-apps', '--disable-dev-shm-usage', '--disable-extensions', '--disable-features=site-per-process', '--disable-hang-monitor', '--disable-popup-blocking', '--disable-prompt-on-repost', '--disable-sync', '--disable-translate', '--metrics-recording-only', '--no-first-run', '--safebrowsing-disable-auto-update', '--enable-automation', '--password-store=basic', '--use-mock-keychain', ] def current_platform() -> str: """Get current platform name by short string.""" if sys.platform.startswith('linux'): return 'linux' elif sys.platform.startswith('darwin'): return 'mac' elif sys.platform.startswith('win') or sys.platform.startswith('msys') or sys.platform.startswith('cyg'): if sys.maxsize > 2 ** 31 - 1: return 'win64' return 'win32' raise OSError('Unsupported platform: ' + sys.platform) def merge_dict(dict1: Optional[Dict], dict2: Optional[Dict]) -> Dict: """Merge two dictionaries into new one.""" new_dict = {} if dict1: new_dict.update(dict1) if dict2: new_dict.update(dict2) return new_dict The provided code snippet includes necessary dependencies for implementing the `defaultArgs` function. Write a Python function `def defaultArgs(options: Dict = None, **kwargs: Any) -> List[str]` to solve the following problem: Get the default flags the chromium will be launched with. ``options`` or keyword arguments are set of configurable options to set on the browser. Can have the following fields: * ``headless`` (bool): Whether to run browser in headless mode. Defaults to ``True`` unless the ``devtools`` option is ``True``. * ``args`` (List[str]): Additional arguments to pass to the browser instance. The list of chromium flags can be found `here <http://peter.sh/experiments/chromium-command-line-switches/>`__. * ``userDataDir`` (str): Path to a User Data Directory. * ``devtools`` (bool): Whether to auto-open DevTools panel for each tab. If this option is ``True``, the ``headless`` option will be set ``False``. Here is the function: def defaultArgs(options: Dict = None, **kwargs: Any) -> List[str]: # noqa: C901,E501 """Get the default flags the chromium will be launched with. ``options`` or keyword arguments are set of configurable options to set on the browser. Can have the following fields: * ``headless`` (bool): Whether to run browser in headless mode. Defaults to ``True`` unless the ``devtools`` option is ``True``. * ``args`` (List[str]): Additional arguments to pass to the browser instance. The list of chromium flags can be found `here <http://peter.sh/experiments/chromium-command-line-switches/>`__. * ``userDataDir`` (str): Path to a User Data Directory. * ``devtools`` (bool): Whether to auto-open DevTools panel for each tab. If this option is ``True``, the ``headless`` option will be set ``False``. """ options = merge_dict(options, kwargs) devtools = options.get('devtools', False) headless = options.get('headless', not devtools) args = options.get('args', list()) userDataDir = options.get('userDataDir') chromeArguments = copy(DEFAULT_ARGS) if userDataDir: chromeArguments.append(f'--user-data-dir={userDataDir}') if devtools: chromeArguments.append('--auto-open-devtools-for-tabs') if headless: chromeArguments.extend(('--headless', '--hide-scrollbars', '--mute-audio',)) if current_platform().startswith('win'): chromeArguments.append('--disable-gpu') if all(map(lambda arg: arg.startswith('-'), args)): # type: ignore chromeArguments.append('about:blank') chromeArguments.extend(args) return chromeArguments
Get the default flags the chromium will be launched with. ``options`` or keyword arguments are set of configurable options to set on the browser. Can have the following fields: * ``headless`` (bool): Whether to run browser in headless mode. Defaults to ``True`` unless the ``devtools`` option is ``True``. * ``args`` (List[str]): Additional arguments to pass to the browser instance. The list of chromium flags can be found `here <http://peter.sh/experiments/chromium-command-line-switches/>`__. * ``userDataDir`` (str): Path to a User Data Directory. * ``devtools`` (bool): Whether to auto-open DevTools panel for each tab. If this option is ``True``, the ``headless`` option will be set ``False``.
158,587
from functools import cmp_to_key import logging from typing import Any, Dict, List from pyppeteer import helper from pyppeteer.connection import CDPSession from pyppeteer.errors import PageError from pyppeteer.execution_context import EVALUATION_SCRIPT_URL from pyppeteer.helper import debugError from pyppeteer.util import merge_dict The provided code snippet includes necessary dependencies for implementing the `convertToDisjointRanges` function. Write a Python function `def convertToDisjointRanges(nestedRanges: List[Any] # noqa: C901 ) -> List[Any]` to solve the following problem: Convert ranges. Here is the function: def convertToDisjointRanges(nestedRanges: List[Any] # noqa: C901 ) -> List[Any]: """Convert ranges.""" points: List = [] for nested_range in nestedRanges: points.append({'offset': nested_range['startOffset'], 'type': 0, 'range': nested_range}) points.append({'offset': nested_range['endOffset'], 'type': 1, 'range': nested_range}) # Sort points to form a valid parenthesis sequence. def _sort_func(a: Dict, b: Dict) -> int: # Sort with increasing offsets. if a['offset'] != b['offset']: return a['offset'] - b['offset'] # All "end" points should go before "start" points. if a['type'] != b['type']: return b['type'] - a['type'] aLength = a['range']['endOffset'] - a['range']['startOffset'] bLength = b['range']['endOffset'] - b['range']['startOffset'] # For two "start" points, the one with longer range goes first. if a['type'] == 0: return bLength - aLength # For two "end" points, the one with shorter range goes first. return aLength - bLength points.sort(key=cmp_to_key(_sort_func)) hitCountStack: List[int] = [] results: List[Dict] = [] lastOffset = 0 # Run scanning line to intersect all ranges. for point in points: if (hitCountStack and lastOffset < point['offset'] and hitCountStack[len(hitCountStack) - 1] > 0): lastResult = results[-1] if results else None if lastResult and lastResult['end'] == lastOffset: lastResult['end'] = point['offset'] else: results.append({'start': lastOffset, 'end': point['offset']}) lastOffset = point['offset'] if point['type'] == 0: hitCountStack.append(point['range']['count']) else: hitCountStack.pop() # Filter out empty ranges. return [range for range in results if range['end'] - range['start'] > 1]
Convert ranges.
158,588
import asyncio import json import logging import math from typing import Any, Awaitable, Callable, Dict, List from pyee import EventEmitter import pyppeteer from pyppeteer.connection import CDPSession from pyppeteer.errors import ElementHandleError, TimeoutError The provided code snippet includes necessary dependencies for implementing the `evaluationString` function. Write a Python function `def evaluationString(fun: str, *args: Any) -> str` to solve the following problem: Convert function and arguments to str. Here is the function: def evaluationString(fun: str, *args: Any) -> str: """Convert function and arguments to str.""" _args = ', '.join([ json.dumps('undefined' if arg is None else arg) for arg in args ]) expr = f'({fun})({_args})' return expr
Convert function and arguments to str.
158,589
import asyncio import json import logging import math from typing import Any, Awaitable, Callable, Dict, List from pyee import EventEmitter import pyppeteer from pyppeteer.connection import CDPSession from pyppeteer.errors import ElementHandleError, TimeoutError The provided code snippet includes necessary dependencies for implementing the `getExceptionMessage` function. Write a Python function `def getExceptionMessage(exceptionDetails: dict) -> str` to solve the following problem: Get exception message from `exceptionDetails` object. Here is the function: def getExceptionMessage(exceptionDetails: dict) -> str: """Get exception message from `exceptionDetails` object.""" exception = exceptionDetails.get('exception') if exception: return exception.get('description') or exception.get('value') message = exceptionDetails.get('text', '') stackTrace = exceptionDetails.get('stackTrace', dict()) if stackTrace: for callframe in stackTrace.get('callFrames'): location = ( str(callframe.get('url', '')) + ':' + str(callframe.get('lineNumber', '')) + ':' + str(callframe.get('columnNumber')) ) functionName = callframe.get('functionName', '<anonymous>') message = message + f'\n at {functionName} ({location})' return message
Get exception message from `exceptionDetails` object.
158,590
import asyncio import json import logging import math from typing import Any, Awaitable, Callable, Dict, List from pyee import EventEmitter import pyppeteer from pyppeteer.connection import CDPSession from pyppeteer.errors import ElementHandleError, TimeoutError class ElementHandleError(PyppeteerError): # noqa: D204 """ElementHandle related exception.""" pass The provided code snippet includes necessary dependencies for implementing the `valueFromRemoteObject` function. Write a Python function `def valueFromRemoteObject(remoteObject: Dict) -> Any` to solve the following problem: Serialize value of remote object. Here is the function: def valueFromRemoteObject(remoteObject: Dict) -> Any: """Serialize value of remote object.""" if remoteObject.get('objectId'): raise ElementHandleError('Cannot extract value when objectId is given') value = remoteObject.get('unserializableValue') if value: if value == '-0': return -0 elif value == 'NaN': return None elif value == 'Infinity': return math.inf elif value == '-Infinity': return -math.inf else: raise ElementHandleError( 'Unsupported unserializable value: {}'.format(value)) return remoteObject.get('value')
Serialize value of remote object.
158,591
import asyncio import json import logging import math from typing import Any, Awaitable, Callable, Dict, List from pyee import EventEmitter import pyppeteer from pyppeteer.connection import CDPSession from pyppeteer.errors import ElementHandleError, TimeoutError logger = logging.getLogger(__name__) def debugError(_logger: logging.Logger, msg: Any) -> None: """Log error messages.""" if pyppeteer.DEBUG: _logger.error(msg) else: _logger.debug(msg) class CDPSession(EventEmitter): """Chrome Devtools Protocol Session. The :class:`CDPSession` instances are used to talk raw Chrome Devtools Protocol: * protocol methods can be called with :meth:`send` method. * protocol events can be subscribed to with :meth:`on` method. Documentation on DevTools Protocol can be found `here <https://chromedevtools.github.io/devtools-protocol/>`__. """ def __init__(self, connection: Union[Connection, 'CDPSession'], targetType: str, sessionId: str, loop: asyncio.AbstractEventLoop) -> None: """Make new session.""" super().__init__() self._lastId = 0 self._callbacks: Dict[int, asyncio.Future] = {} self._connection: Optional[Connection] = connection self._targetType = targetType self._sessionId = sessionId self._sessions: Dict[str, CDPSession] = dict() self._loop = loop def send(self, method: str, params: dict = None) -> Awaitable: """Send message to the connected session. :arg str method: Protocol method name. :arg dict params: Optional method parameters. """ if not self._connection: raise NetworkError( f'Protocol Error ({method}): Session closed. Most likely the ' f'{self._targetType} has been closed.' ) self._lastId += 1 _id = self._lastId msg = json.dumps(dict(id=_id, method=method, params=params)) logger_session.debug(f'SEND: {msg}') callback = self._loop.create_future() self._callbacks[_id] = callback callback.error: Exception = NetworkError() # type: ignore callback.method: str = method # type: ignore try: self._connection.send('Target.sendMessageToTarget', { 'sessionId': self._sessionId, 'message': msg, }) except Exception as e: # The response from target might have been already dispatched if _id in self._callbacks: _callback = self._callbacks[_id] del self._callbacks[_id] _callback.set_exception(_rewriteError( _callback.error, # type: ignore e.args[0], )) return callback def _on_message(self, msg: str) -> None: # noqa: C901 logger_session.debug(f'RECV: {msg}') obj = json.loads(msg) _id = obj.get('id') if _id: callback = self._callbacks.get(_id) if callback: del self._callbacks[_id] if obj.get('error'): callback.set_exception(_createProtocolError( callback.error, # type: ignore callback.method, # type: ignore obj, )) else: result = obj.get('result') if callback and not callback.done(): callback.set_result(result) else: params = obj.get('params', {}) if obj.get('method') == 'Target.receivedMessageFromTarget': session = self._sessions.get(params.get('sessionId')) if session: session._on_message(params.get('message')) elif obj.get('method') == 'Target.detachFromTarget': sessionId = params.get('sessionId') session = self._sessions.get(sessionId) if session: session._on_closed() del self._sessions[sessionId] self.emit(obj.get('method'), obj.get('params')) async def detach(self) -> None: """Detach session from target. Once detached, session won't emit any events and can't be used to send messages. """ if not self._connection: raise NetworkError('Connection already closed.') await self._connection.send('Target.detachFromTarget', {'sessionId': self._sessionId}) def _on_closed(self) -> None: for cb in self._callbacks.values(): cb.set_exception(_rewriteError( cb.error, # type: ignore f'Protocol error {cb.method}: Target closed.', # type: ignore )) self._callbacks.clear() self._connection = None def _createSession(self, targetType: str, sessionId: str) -> 'CDPSession': session = CDPSession(self, targetType, sessionId, self._loop) self._sessions[sessionId] = session return session The provided code snippet includes necessary dependencies for implementing the `releaseObject` function. Write a Python function `def releaseObject(client: CDPSession, remoteObject: dict ) -> Awaitable` to solve the following problem: Release remote object. Here is the function: def releaseObject(client: CDPSession, remoteObject: dict ) -> Awaitable: """Release remote object.""" objectId = remoteObject.get('objectId') fut_none = client._loop.create_future() fut_none.set_result(None) if not objectId: return fut_none try: return client.send('Runtime.releaseObject', { 'objectId': objectId }) except Exception as e: # Exceptions might happen in case of a page been navigated or closed. # Swallow these since they are harmless and we don't leak anything in this case. # noqa debugError(logger, e) return fut_none
Release remote object.
158,592
import asyncio import json import logging import math from typing import Any, Awaitable, Callable, Dict, List from pyee import EventEmitter import pyppeteer from pyppeteer.connection import CDPSession from pyppeteer.errors import ElementHandleError, TimeoutError def addEventListener(emitter: EventEmitter, eventName: str, handler: Callable ) -> Dict[str, Any]: """Add handler to the emitter and return emitter/handler.""" emitter.on(eventName, handler) return {'emitter': emitter, 'eventName': eventName, 'handler': handler} def removeEventListeners(listeners: List[dict]) -> None: """Remove listeners from emitter.""" for listener in listeners: emitter = listener['emitter'] eventName = listener['eventName'] handler = listener['handler'] emitter.remove_listener(eventName, handler) listeners.clear() class TimeoutError(asyncio.TimeoutError): # noqa: D204 """Timeout Error class.""" pass The provided code snippet includes necessary dependencies for implementing the `waitForEvent` function. Write a Python function `def waitForEvent(emitter: EventEmitter, eventName: str, # noqa: C901 predicate: Callable[[Any], bool], timeout: float, loop: asyncio.AbstractEventLoop) -> Awaitable` to solve the following problem: Wait for an event emitted from the emitter. Here is the function: def waitForEvent(emitter: EventEmitter, eventName: str, # noqa: C901 predicate: Callable[[Any], bool], timeout: float, loop: asyncio.AbstractEventLoop) -> Awaitable: """Wait for an event emitted from the emitter.""" promise = loop.create_future() def resolveCallback(target: Any) -> None: promise.set_result(target) def rejectCallback(exception: Exception) -> None: promise.set_exception(exception) async def timeoutTimer() -> None: await asyncio.sleep(timeout / 1000) rejectCallback( TimeoutError('Timeout exceeded while waiting for event')) def _listener(target: Any) -> None: if not predicate(target): return cleanup() resolveCallback(target) listener = addEventListener(emitter, eventName, _listener) if timeout: eventTimeout = loop.create_task(timeoutTimer()) def cleanup() -> None: removeEventListeners([listener]) if timeout: eventTimeout.cancel() return promise
Wait for an event emitted from the emitter.
158,593
import asyncio import json import logging import math from typing import Any, Awaitable, Callable, Dict, List from pyee import EventEmitter import pyppeteer from pyppeteer.connection import CDPSession from pyppeteer.errors import ElementHandleError, TimeoutError The provided code snippet includes necessary dependencies for implementing the `get_positive_int` function. Write a Python function `def get_positive_int(obj: dict, name: str) -> int` to solve the following problem: Get and check the value of name in obj is positive integer. Here is the function: def get_positive_int(obj: dict, name: str) -> int: """Get and check the value of name in obj is positive integer.""" value = obj[name] if not isinstance(value, int): raise TypeError( f'{name} must be integer: {type(value)}') elif value < 0: raise ValueError( f'{name} must be positive integer: {value}') return value
Get and check the value of name in obj is positive integer.
158,594
import asyncio import json import logging import math from typing import Any, Awaitable, Callable, Dict, List from pyee import EventEmitter import pyppeteer from pyppeteer.connection import CDPSession from pyppeteer.errors import ElementHandleError, TimeoutError The provided code snippet includes necessary dependencies for implementing the `is_jsfunc` function. Write a Python function `def is_jsfunc(func: str) -> bool` to solve the following problem: Heuristically check function or expression. Here is the function: def is_jsfunc(func: str) -> bool: # not in puppeteer """Heuristically check function or expression.""" func = func.strip() if func.startswith('function') or func.startswith('async '): return True elif '=>' in func: return True return False
Heuristically check function or expression.
158,595
import logging import math import re from typing import Any, Dict, Optional, TYPE_CHECKING from pyppeteer import helper from pyppeteer.connection import CDPSession from pyppeteer.errors import ElementHandleError, NetworkError from pyppeteer.helper import debugError def _rewriteError(error: Exception) -> None: if error.args[0].endswith('Cannot find context with specified id'): msg = 'Execution context was destroyed, most likely because of a navigation.' # noqa: E501 raise type(error)(msg) raise error
null
158,596
import asyncio import json import logging from typing import Awaitable, Callable, Dict, Union, TYPE_CHECKING from pyee import EventEmitter import websockets from websockets.legacy.client import connect as ws_connect from pyppeteer.errors import NetworkError def _rewriteError(error: Exception, message: str) -> Exception: error.args = (message, ) return error def _createProtocolError(error: Exception, method: str, obj: Dict ) -> Exception: message = f'Protocol error ({method}): {obj["error"]["message"]}' if 'data' in obj['error']: message += f' {obj["error"]["data"]}' return _rewriteError(error, message)
null
158,597
import asyncio import base64 import json import logging import math import mimetypes from types import SimpleNamespace from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Union from pyee import EventEmitter from pyppeteer import helper from pyppeteer.connection import CDPSession from pyppeteer.coverage import Coverage from pyppeteer.dialog import Dialog from pyppeteer.element_handle import ElementHandle from pyppeteer.emulation_manager import EmulationManager from pyppeteer.errors import PageError from pyppeteer.execution_context import JSHandle from pyppeteer.frame_manager import Frame from pyppeteer.frame_manager import FrameManager from pyppeteer.helper import debugError from pyppeteer.input import Keyboard, Mouse, Touchscreen from pyppeteer.navigator_watcher import NavigatorWatcher from pyppeteer.network_manager import NetworkManager, Request, Response from pyppeteer.tracing import Tracing from pyppeteer.util import merge_dict from pyppeteer.worker import Worker unitToPixels = {'px': 1, 'in': 96, 'cm': 37.8, 'mm': 3.78} The provided code snippet includes necessary dependencies for implementing the `convertPrintParameterToInches` function. Write a Python function `def convertPrintParameterToInches(parameter: Union[None, int, float, str]) -> Optional[float]` to solve the following problem: Convert print parameter to inches. Here is the function: def convertPrintParameterToInches(parameter: Union[None, int, float, str]) -> Optional[float]: """Convert print parameter to inches.""" if parameter is None: return None if isinstance(parameter, (int, float)): pixels = parameter elif isinstance(parameter, str): text = parameter unit = text[-2:].lower() if unit in unitToPixels: valueText = text[:-2] else: unit = 'px' valueText = text try: value = float(valueText) except ValueError: raise ValueError('Failed to parse parameter value: ' + text) pixels = value * unitToPixels[unit] else: raise TypeError('page.pdf() Cannot handle parameter type: ' + str(type(parameter))) return pixels / 96
Convert print parameter to inches.
158,598
import datetime import logging import os import platform import uuid def get_machine_unique_identifier(): if platform.system() == "Windows": # Use the Windows Management Instrumentation (WMI) interface import wmi wmi_obj = wmi.WMI() for interface in wmi_obj.Win32_NetworkAdapterConfiguration(IPEnabled=True): mac_address = interface.MACAddress break else: for line in os.popen("ifconfig" if platform.system() != "Linux" else "ip link"): if "ether" in line or "HWaddr" in line: mac_address = line.split()[1] break # Create a UUID based on the MAC address and a namespace namespace = uuid.UUID("a9b8c7d6-e5f4-3210-9876-5a4b3c2d1e0f") if type(mac_address) != str: mac_address = str(datetime.datetime.now()) logging.info(f"machine identifier: {mac_address}") machine_unique_id = uuid.uuid5(namespace, mac_address) return machine_unique_id
null
158,599
import logging def get_tune(character, model): if "3.5" in model: filename = character+'35.txt' logging.info('chatGPT prompt: %s' % filename) return open('GPT/prompts/' + filename, 'r', encoding='utf-8').read() if '4' in model: filename = character+'4.txt' logging.info('chatGPT prompt: %s' % filename) return open('GPT/prompts/' + filename, 'r', encoding='utf-8').read()
null
158,600
import functools import logging import pickle from pathlib import Path from typing import Any, Dict, Iterable, List, NamedTuple, Set, Tuple, Union import numpy as np import yaml from onnxruntime import (GraphOptimizationLevel, InferenceSession, SessionOptions, get_available_providers, get_device) from typeguard import check_argument_types from .kaldifeat import compute_fbank_feats def read_yaml(yaml_path: Union[str, Path]) -> Dict: if not Path(yaml_path).exists(): raise FileExistsError(f'The {yaml_path} does not exist.') with open(str(yaml_path), 'rb') as f: data = yaml.load(f, Loader=yaml.Loader) return data
null
158,601
import functools import logging import pickle from pathlib import Path from typing import Any, Dict, Iterable, List, NamedTuple, Set, Tuple, Union import numpy as np import yaml from onnxruntime import (GraphOptimizationLevel, InferenceSession, SessionOptions, get_available_providers, get_device) from typeguard import check_argument_types from .kaldifeat import compute_fbank_feats logger_initialized = {} The provided code snippet includes necessary dependencies for implementing the `get_logger` function. Write a Python function `def get_logger(name='rapdi_paraformer')` to solve the following problem: Initialize and get a logger by name. If the logger has not been initialized, this method will initialize the logger by adding one or two handlers, otherwise the initialized logger will be directly returned. During initialization, a StreamHandler will always be added. Args: name (str): Logger name. Returns: logging.Logger: The expected logger. Here is the function: def get_logger(name='rapdi_paraformer'): """Initialize and get a logger by name. If the logger has not been initialized, this method will initialize the logger by adding one or two handlers, otherwise the initialized logger will be directly returned. During initialization, a StreamHandler will always be added. Args: name (str): Logger name. Returns: logging.Logger: The expected logger. """ logger = logging.getLogger(name) if name in logger_initialized: return logger for logger_name in logger_initialized: if name.startswith(logger_name): return logger formatter = logging.Formatter( '[%(asctime)s] %(name)s %(levelname)s: %(message)s', datefmt="%Y/%m/%d %H:%M:%S") sh = logging.StreamHandler() sh.setFormatter(formatter) logger.addHandler(sh) logger_initialized[name] = True logger.propagate = False return logger
Initialize and get a logger by name. If the logger has not been initialized, this method will initialize the logger by adding one or two handlers, otherwise the initialized logger will be directly returned. During initialization, a StreamHandler will always be added. Args: name (str): Logger name. Returns: logging.Logger: The expected logger.
158,602
import numpy as np from scipy.fftpack import dct def inverse_mel_scale(mel_freq): return 700.0 * (np.exp(mel_freq / 1127.0) - 1.0)
null
158,603
import numpy as np from scipy.fftpack import dct def compute_lifter_coeffs(q, M): """ Compute liftering coefficients (scaling on cepstral coeffs) the zeroth index is C0, which is not affected. :param q: Number of lifters :param M: Number of coefficients :return: Lifters. """ if M < 1: return np.array([]) if M == 1: return np.ones(1, float) n = np.arange(0, M) return 1 + 0.5*np.sin(np.pi*n/q)*q def compute_fbank_feats( waveform, blackman_coeff=0.42, dither=1.0, energy_floor=1.0, frame_length=25, frame_shift=10, high_freq=0, low_freq=20, num_mel_bins=23, preemphasis_coefficient=0.97, raw_energy=True, remove_dc_offset=True, round_to_power_of_two=True, sample_frequency=16000, snip_edges=True, use_energy=False, use_log_fbank=True, use_power=True, window_type='povey', dtype=np.float32): """ Compute (log) Mel filter bank energies :param waveform: Input waveform. :param blackman_coeff: Constant coefficient for generalized Blackman window. (float, default = 0.42) :param dither: Dithering constant (0.0 means no dither). If you turn this off, you should set the --energy-floor option, e.g. to 1.0 or 0.1 (float, default = 1) :param energy_floor: Floor on energy (absolute, not relative) in FBANK computation. Only makes a difference if --use-energy=true; only necessary if --dither=0.0. Suggested values: 0.1 or 1.0 (float, default = 0) :param frame_length: Frame length in milliseconds (float, default = 25) :param frame_shift: Frame shift in milliseconds (float, default = 10) :param high_freq: High cutoff frequency for mel bins (if <= 0, offset from Nyquist) (float, default = 0) :param low_freq: Low cutoff frequency for mel bins (float, default = 20) :param num_mel_bins: Number of triangular mel-frequency bins (int, default = 23) :param preemphasis_coefficient: Coefficient for use in signal preemphasis (float, default = 0.97) :param raw_energy: If true, compute energy before preemphasis and windowing (bool, default = true) :param remove_dc_offset: Subtract mean from waveform on each frame (bool, default = true) :param round_to_power_of_two: If true, round window size to power of two by zero-padding input to FFT. (bool, default = true) :param sample_frequency: Waveform data sample frequency (must match the waveform file, if specified there) (float, default = 16000) :param snip_edges: If true, end effects will be handled by outputting only frames that completely fit in the file, and the number of frames depends on the frame-length. If false, the number of frames depends only on the frame-shift, and we reflect the data at the ends. (bool, default = true) :param use_energy: Add an extra energy output. (bool, default = false) :param use_log_fbank: If true, produce log-filterbank, else produce linear. (bool, default = true) :param use_power: If true, use power, else use magnitude. (bool, default = true) :param window_type: Type of window ("hamming"|"hanning"|"povey"|"rectangular"|"sine"|"blackmann") (string, default = "povey") :param dtype: Type of array (np.float32|np.float64) (dtype or string, default=np.float32) :return: (Log) Mel filter bank energies. """ window_size = int(frame_length * sample_frequency * 0.001) window_shift = int(frame_shift * sample_frequency * 0.001) frames, log_energy = extract_window( waveform=waveform, blackman_coeff=blackman_coeff, dither=dither, window_size=window_size, window_shift=window_shift, preemphasis_coefficient=preemphasis_coefficient, raw_energy=raw_energy, remove_dc_offset=remove_dc_offset, snip_edges=snip_edges, window_type=window_type, dtype=dtype ) if round_to_power_of_two: n = 1 while n < window_size: n *= 2 else: n = window_size if use_power: spectrum = compute_power_spectrum(frames, n) else: spectrum = compute_spectrum(frames, n) mel_banks = compute_mel_banks( num_bins=num_mel_bins, sample_frequency=sample_frequency, low_freq=low_freq, high_freq=high_freq, n=n ).astype(dtype) feat = np.dot(spectrum, mel_banks.T) if use_log_fbank: feat = np.log(feat.clip(min=np.finfo(dtype).eps)) if use_energy: if energy_floor > 0.0: log_energy.clip(min=np.math.log(energy_floor)) return feat, log_energy return feat The provided code snippet includes necessary dependencies for implementing the `compute_mfcc_feats` function. Write a Python function `def compute_mfcc_feats( waveform, blackman_coeff=0.42, cepstral_lifter=22, dither=1.0, energy_floor=0.0, frame_length=25, frame_shift=10, high_freq=0, low_freq=20, num_ceps=13, num_mel_bins=23, preemphasis_coefficient=0.97, raw_energy=True, remove_dc_offset=True, round_to_power_of_two=True, sample_frequency=16000, snip_edges=True, use_energy=True, window_type='povey', dtype=np.float32)` to solve the following problem: Compute mel-frequency cepstral coefficients :param waveform: Input waveform. :param blackman_coeff: Constant coefficient for generalized Blackman window. (float, default = 0.42) :param cepstral_lifter: Constant that controls scaling of MFCCs (float, default = 22) :param dither: Dithering constant (0.0 means no dither). If you turn this off, you should set the --energy-floor option, e.g. to 1.0 or 0.1 (float, default = 1) :param energy_floor: Floor on energy (absolute, not relative) in MFCC computation. Only makes a difference if --use-energy=true; only necessary if --dither=0.0. Suggested values: 0.1 or 1.0 (float, default = 0) :param frame_length: Frame length in milliseconds (float, default = 25) :param frame_shift: Frame shift in milliseconds (float, default = 10) :param high_freq: High cutoff frequency for mel bins (if <= 0, offset from Nyquist) (float, default = 0) :param low_freq: Low cutoff frequency for mel bins (float, default = 20) :param num_ceps: Number of cepstra in MFCC computation (including C0) (int, default = 13) :param num_mel_bins: Number of triangular mel-frequency bins (int, default = 23) :param preemphasis_coefficient: Coefficient for use in signal preemphasis (float, default = 0.97) :param raw_energy: If true, compute energy before preemphasis and windowing (bool, default = true) :param remove_dc_offset: Subtract mean from waveform on each frame (bool, default = true) :param round_to_power_of_two: If true, round window size to power of two by zero-padding input to FFT. (bool, default = true) :param sample_frequency: Waveform data sample frequency (must match the waveform file, if specified there) (float, default = 16000) :param snip_edges: If true, end effects will be handled by outputting only frames that completely fit in the file, and the number of frames depends on the frame-length. If false, the number of frames depends only on the frame-shift, and we reflect the data at the ends. (bool, default = true) :param use_energy: Use energy (not C0) in MFCC computation (bool, default = true) :param window_type: Type of window ("hamming"|"hanning"|"povey"|"rectangular"|"sine"|"blackmann") (string, default = "povey") :param dtype: Type of array (np.float32|np.float64) (dtype or string, default=np.float32) :return: Mel-frequency cespstral coefficients. Here is the function: def compute_mfcc_feats( waveform, blackman_coeff=0.42, cepstral_lifter=22, dither=1.0, energy_floor=0.0, frame_length=25, frame_shift=10, high_freq=0, low_freq=20, num_ceps=13, num_mel_bins=23, preemphasis_coefficient=0.97, raw_energy=True, remove_dc_offset=True, round_to_power_of_two=True, sample_frequency=16000, snip_edges=True, use_energy=True, window_type='povey', dtype=np.float32): """ Compute mel-frequency cepstral coefficients :param waveform: Input waveform. :param blackman_coeff: Constant coefficient for generalized Blackman window. (float, default = 0.42) :param cepstral_lifter: Constant that controls scaling of MFCCs (float, default = 22) :param dither: Dithering constant (0.0 means no dither). If you turn this off, you should set the --energy-floor option, e.g. to 1.0 or 0.1 (float, default = 1) :param energy_floor: Floor on energy (absolute, not relative) in MFCC computation. Only makes a difference if --use-energy=true; only necessary if --dither=0.0. Suggested values: 0.1 or 1.0 (float, default = 0) :param frame_length: Frame length in milliseconds (float, default = 25) :param frame_shift: Frame shift in milliseconds (float, default = 10) :param high_freq: High cutoff frequency for mel bins (if <= 0, offset from Nyquist) (float, default = 0) :param low_freq: Low cutoff frequency for mel bins (float, default = 20) :param num_ceps: Number of cepstra in MFCC computation (including C0) (int, default = 13) :param num_mel_bins: Number of triangular mel-frequency bins (int, default = 23) :param preemphasis_coefficient: Coefficient for use in signal preemphasis (float, default = 0.97) :param raw_energy: If true, compute energy before preemphasis and windowing (bool, default = true) :param remove_dc_offset: Subtract mean from waveform on each frame (bool, default = true) :param round_to_power_of_two: If true, round window size to power of two by zero-padding input to FFT. (bool, default = true) :param sample_frequency: Waveform data sample frequency (must match the waveform file, if specified there) (float, default = 16000) :param snip_edges: If true, end effects will be handled by outputting only frames that completely fit in the file, and the number of frames depends on the frame-length. If false, the number of frames depends only on the frame-shift, and we reflect the data at the ends. (bool, default = true) :param use_energy: Use energy (not C0) in MFCC computation (bool, default = true) :param window_type: Type of window ("hamming"|"hanning"|"povey"|"rectangular"|"sine"|"blackmann") (string, default = "povey") :param dtype: Type of array (np.float32|np.float64) (dtype or string, default=np.float32) :return: Mel-frequency cespstral coefficients. """ feat, log_energy = compute_fbank_feats( waveform=waveform, blackman_coeff=blackman_coeff, dither=dither, energy_floor=energy_floor, frame_length=frame_length, frame_shift=frame_shift, high_freq=high_freq, low_freq=low_freq, num_mel_bins=num_mel_bins, preemphasis_coefficient=preemphasis_coefficient, raw_energy=raw_energy, remove_dc_offset=remove_dc_offset, round_to_power_of_two=round_to_power_of_two, sample_frequency=sample_frequency, snip_edges=snip_edges, use_energy=use_energy, use_log_fbank=True, use_power=True, window_type=window_type, dtype=dtype ) feat = dct(feat, type=2, axis=1, norm='ortho')[:, :num_ceps] lifter_coeffs = compute_lifter_coeffs(cepstral_lifter, num_ceps).astype(dtype) feat = feat * lifter_coeffs if use_energy: feat[:, 0] = log_energy return feat
Compute mel-frequency cepstral coefficients :param waveform: Input waveform. :param blackman_coeff: Constant coefficient for generalized Blackman window. (float, default = 0.42) :param cepstral_lifter: Constant that controls scaling of MFCCs (float, default = 22) :param dither: Dithering constant (0.0 means no dither). If you turn this off, you should set the --energy-floor option, e.g. to 1.0 or 0.1 (float, default = 1) :param energy_floor: Floor on energy (absolute, not relative) in MFCC computation. Only makes a difference if --use-energy=true; only necessary if --dither=0.0. Suggested values: 0.1 or 1.0 (float, default = 0) :param frame_length: Frame length in milliseconds (float, default = 25) :param frame_shift: Frame shift in milliseconds (float, default = 10) :param high_freq: High cutoff frequency for mel bins (if <= 0, offset from Nyquist) (float, default = 0) :param low_freq: Low cutoff frequency for mel bins (float, default = 20) :param num_ceps: Number of cepstra in MFCC computation (including C0) (int, default = 13) :param num_mel_bins: Number of triangular mel-frequency bins (int, default = 23) :param preemphasis_coefficient: Coefficient for use in signal preemphasis (float, default = 0.97) :param raw_energy: If true, compute energy before preemphasis and windowing (bool, default = true) :param remove_dc_offset: Subtract mean from waveform on each frame (bool, default = true) :param round_to_power_of_two: If true, round window size to power of two by zero-padding input to FFT. (bool, default = true) :param sample_frequency: Waveform data sample frequency (must match the waveform file, if specified there) (float, default = 16000) :param snip_edges: If true, end effects will be handled by outputting only frames that completely fit in the file, and the number of frames depends on the frame-length. If false, the number of frames depends only on the frame-shift, and we reflect the data at the ends. (bool, default = true) :param use_energy: Use energy (not C0) in MFCC computation (bool, default = true) :param window_type: Type of window ("hamming"|"hanning"|"povey"|"rectangular"|"sine"|"blackmann") (string, default = "povey") :param dtype: Type of array (np.float32|np.float64) (dtype or string, default=np.float32) :return: Mel-frequency cespstral coefficients.
158,604
import numpy as np from scipy.fftpack import dct def apply_cmvn_sliding_internal(feat, center=False, window=600, min_window=100, norm_vars=False): num_frames, feat_dim = feat.shape std = 1 if center: if num_frames <= window: mean = feat.mean(axis=0, keepdims=True).repeat(num_frames, axis=0) if norm_vars: std = feat.std(axis=0, keepdims=True).repeat(num_frames, axis=0) else: feat1 = feat[:window] feat2 = sliding_window(feat.T, window, 1) feat3 = feat[-window:] mean1 = feat1.mean(axis=0, keepdims=True).repeat(window // 2, axis=0) mean2 = feat2.mean(axis=2).T mean3 = feat3.mean(axis=0, keepdims=True).repeat((window - 1) // 2, axis=0) mean = np.concatenate([mean1, mean2, mean3]) if norm_vars: std1 = feat1.std(axis=0, keepdims=True).repeat(window // 2, axis=0) std2 = feat2.std(axis=2).T std3 = feat3.mean(axis=0, keepdims=True).repeat((window - 1) // 2, axis=0) std = np.concatenate([std1, std2, std3]) else: if num_frames <= min_window: mean = feat.mean(axis=0, keepdims=True).repeat(num_frames, axis=0) if norm_vars: std = feat.std(axis=0, keepdims=True).repeat(num_frames, axis=0) else: feat1 = feat[:min_window] mean1 = feat1.mean(axis=0, keepdims=True).repeat(min_window, axis=0) feat2_cumsum = np.cumsum(feat[:window], axis=0)[min_window:] cumcnt = np.arange(min_window + 1, min(window, num_frames) + 1, dtype=feat.dtype)[:, np.newaxis] mean2 = feat2_cumsum / cumcnt mean = np.concatenate([mean1, mean2]) if norm_vars: std1 = feat1.std(axis=0, keepdims=True).repeat(min_window, axis=0) feat2_power_cumsum = np.cumsum(np.square(feat[:window]), axis=0)[min_window:] std2 = np.sqrt(feat2_power_cumsum / cumcnt - np.square(mean2)) std = np.concatenate([std1, std2]) if num_frames > window: feat3 = sliding_window(feat.T, window, 1) mean3 = feat3.mean(axis=2).T mean = np.concatenate([mean, mean3[1:]]) if norm_vars: std3 = feat3.std(axis=2).T std = np.concatenate([std, std3[1:]]) feat = (feat - mean) / std return feat The provided code snippet includes necessary dependencies for implementing the `apply_cmvn_sliding` function. Write a Python function `def apply_cmvn_sliding(feat, center=False, window=600, min_window=100, norm_vars=False)` to solve the following problem: Apply sliding-window cepstral mean (and optionally variance) normalization :param feat: Cepstrum. :param center: If true, use a window centered on the current frame (to the extent possible, modulo end effects). If false, window is to the left. (bool, default = false) :param window: Window in frames for running average CMN computation (int, default = 600) :param min_window: Minimum CMN window used at start of decoding (adds latency only at start). Only applicable if center == false, ignored if center==true (int, default = 100) :param norm_vars: If true, normalize variance to one. (bool, default = false) :return: Normalized cepstrum. Here is the function: def apply_cmvn_sliding(feat, center=False, window=600, min_window=100, norm_vars=False): """ Apply sliding-window cepstral mean (and optionally variance) normalization :param feat: Cepstrum. :param center: If true, use a window centered on the current frame (to the extent possible, modulo end effects). If false, window is to the left. (bool, default = false) :param window: Window in frames for running average CMN computation (int, default = 600) :param min_window: Minimum CMN window used at start of decoding (adds latency only at start). Only applicable if center == false, ignored if center==true (int, default = 100) :param norm_vars: If true, normalize variance to one. (bool, default = false) :return: Normalized cepstrum. """ # double-precision feat = apply_cmvn_sliding_internal( feat=feat.astype(np.float64), center=center, window=window, min_window=min_window, norm_vars=norm_vars ).astype(feat.dtype) return feat
Apply sliding-window cepstral mean (and optionally variance) normalization :param feat: Cepstrum. :param center: If true, use a window centered on the current frame (to the extent possible, modulo end effects). If false, window is to the left. (bool, default = false) :param window: Window in frames for running average CMN computation (int, default = 600) :param min_window: Minimum CMN window used at start of decoding (adds latency only at start). Only applicable if center == false, ignored if center==true (int, default = 100) :param norm_vars: If true, normalize variance to one. (bool, default = false) :return: Normalized cepstrum.
158,605
import numpy as np from .feature import sliding_window def sliding_window(x, window_size, window_shift): shape = x.shape[:-1] + (x.shape[-1] - window_size + 1, window_size) strides = x.strides + (x.strides[-1],) return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)[::window_shift] The provided code snippet includes necessary dependencies for implementing the `compute_vad` function. Write a Python function `def compute_vad(log_energy, energy_mean_scale=0.5, energy_threshold=0.5, frames_context=0, proportion_threshold=0.6)` to solve the following problem: Apply voice activity detection :param log_energy: Log mel energy. :param energy_mean_scale: If this is set to s, to get the actual threshold we let m be the mean log-energy of the file, and use s*m + vad-energy-threshold (float, default = 0.5) :param energy_threshold: Constant term in energy threshold for VAD (also see energy_mean_scale) (float, default = 5) :param frames_context: Number of frames of context on each side of central frame, in window for which energy is monitored (int, default = 0) :param proportion_threshold: Parameter controlling the proportion of frames within the window that need to have more energy than the threshold (float, default = 0.6) :return: A vector of boolean that are True if we judge the frame voiced and False otherwise. Here is the function: def compute_vad(log_energy, energy_mean_scale=0.5, energy_threshold=0.5, frames_context=0, proportion_threshold=0.6): """ Apply voice activity detection :param log_energy: Log mel energy. :param energy_mean_scale: If this is set to s, to get the actual threshold we let m be the mean log-energy of the file, and use s*m + vad-energy-threshold (float, default = 0.5) :param energy_threshold: Constant term in energy threshold for VAD (also see energy_mean_scale) (float, default = 5) :param frames_context: Number of frames of context on each side of central frame, in window for which energy is monitored (int, default = 0) :param proportion_threshold: Parameter controlling the proportion of frames within the window that need to have more energy than the threshold (float, default = 0.6) :return: A vector of boolean that are True if we judge the frame voiced and False otherwise. """ assert len(log_energy.shape) == 1 assert energy_mean_scale >= 0 assert frames_context >= 0 assert 0 < proportion_threshold < 1 dtype = log_energy.dtype energy_threshold += energy_mean_scale * log_energy.mean() if frames_context > 0: num_frames = len(log_energy) window_size = frames_context * 2 + 1 log_energy_pad = np.concatenate([ np.zeros(frames_context, dtype=dtype), log_energy, np.zeros(frames_context, dtype=dtype) ]) log_energy_window = sliding_window(log_energy_pad, window_size, 1) num_count = np.count_nonzero(log_energy_window > energy_threshold, axis=1) den_count = np.ones(num_frames, dtype=dtype) * window_size max_den_count = np.arange(frames_context + 1, min(window_size, num_frames) + 1, dtype=dtype) den_count[:-(frames_context + 2):-1] = max_den_count den_count[:frames_context + 1] = np.min([den_count[:frames_context + 1], max_den_count], axis=0) vad = num_count / den_count >= proportion_threshold else: vad = log_energy > energy_threshold return vad
Apply voice activity detection :param log_energy: Log mel energy. :param energy_mean_scale: If this is set to s, to get the actual threshold we let m be the mean log-energy of the file, and use s*m + vad-energy-threshold (float, default = 0.5) :param energy_threshold: Constant term in energy threshold for VAD (also see energy_mean_scale) (float, default = 5) :param frames_context: Number of frames of context on each side of central frame, in window for which energy is monitored (int, default = 0) :param proportion_threshold: Parameter controlling the proportion of frames within the window that need to have more energy than the threshold (float, default = 0.6) :return: A vector of boolean that are True if we judge the frame voiced and False otherwise.
158,606
import sys import time import soundfile import os import torch import TTS.vits.commons as commons import TTS.vits.utils as utils from TTS.vits.models import SynthesizerTrn from TTS.vits.text.symbols import symbols from TTS.vits.text import text_to_sequence import logging def get_text(text, hps): text_norm = text_to_sequence(text, hps.data.text_cleaners) if hps.data.add_blank: text_norm = commons.intersperse(text_norm, 0) text_norm = torch.LongTensor(text_norm) return text_norm
null
158,607
import argparse import os import socket import time import logging import traceback from logging.handlers import TimedRotatingFileHandler import librosa import requests import revChatGPT import soundfile import GPT.tune from utils.FlushingFileHandler import FlushingFileHandler from ASR import ASRService from GPT import GPTService from TTS import TTService from SentimentEngine import SentimentEngine def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Unsupported value encountered.') def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--chatVer", type=int, nargs='?', required=True) parser.add_argument("--APIKey", type=str, nargs='?', required=False) parser.add_argument("--email", type=str, nargs='?', required=False) parser.add_argument("--password", type=str, nargs='?', required=False) parser.add_argument("--accessToken", type=str, nargs='?', required=False) parser.add_argument("--proxy", type=str, nargs='?', required=False) parser.add_argument("--paid", type=str2bool, nargs='?', required=False) parser.add_argument("--model", type=str, nargs='?', required=False) parser.add_argument("--stream", type=str2bool, nargs='?', required=True) parser.add_argument("--character", type=str, nargs='?', required=True) parser.add_argument("--ip", type=str, nargs='?', required=False) parser.add_argument("--brainwash", type=str2bool, nargs='?', required=False) return parser.parse_args()
null
158,608
import argparse import logging import platform import sys from argparse import Namespace from typing import Tuple, Union from pkg_resources import DistributionNotFound, get_distribution from udemy_enroller import ALL_VALID_BROWSER_STRINGS, DriverManager, Settings from udemy_enroller.logger import get_logger from udemy_enroller.runner import redeem_courses, redeem_courses_ui logger = get_logger() The provided code snippet includes necessary dependencies for implementing the `enable_debug_logging` function. Write a Python function `def enable_debug_logging() -> None` to solve the following problem: Enable debug logging for the scripts. :return: None Here is the function: def enable_debug_logging() -> None: """ Enable debug logging for the scripts. :return: None """ logger.setLevel(logging.DEBUG) for handler in logger.handlers: handler.setLevel(logging.DEBUG) logger.info("Enabled debug logging")
Enable debug logging for the scripts. :return: None
158,609
import argparse import logging import platform import sys from argparse import Namespace from typing import Tuple, Union from pkg_resources import DistributionNotFound, get_distribution from udemy_enroller import ALL_VALID_BROWSER_STRINGS, DriverManager, Settings from udemy_enroller.logger import get_logger from udemy_enroller.runner import redeem_courses, redeem_courses_ui logger = get_logger() The provided code snippet includes necessary dependencies for implementing the `log_package_details` function. Write a Python function `def log_package_details() -> None` to solve the following problem: Log details of the package. :return: None Here is the function: def log_package_details() -> None: """ Log details of the package. :return: None """ try: distribution = get_distribution("udemy_enroller") if distribution: logger.debug(f"Name: {distribution.project_name}") logger.debug(f"Version: {distribution.version}") logger.debug(f"Location: {distribution.location}") except DistributionNotFound: logger.debug("Not installed on python env.")
Log details of the package. :return: None
158,610
import argparse import logging import platform import sys from argparse import Namespace from typing import Tuple, Union from pkg_resources import DistributionNotFound, get_distribution from udemy_enroller import ALL_VALID_BROWSER_STRINGS, DriverManager, Settings from udemy_enroller.logger import get_logger from udemy_enroller.runner import redeem_courses, redeem_courses_ui logger = get_logger() The provided code snippet includes necessary dependencies for implementing the `log_python_version` function. Write a Python function `def log_python_version()` to solve the following problem: Log version of python in use. :return: None Here is the function: def log_python_version(): """ Log version of python in use. :return: None """ logger.debug(f"Python: {sys.version}")
Log version of python in use. :return: None
158,611
import argparse import logging import platform import sys from argparse import Namespace from typing import Tuple, Union from pkg_resources import DistributionNotFound, get_distribution from udemy_enroller import ALL_VALID_BROWSER_STRINGS, DriverManager, Settings from udemy_enroller.logger import get_logger from udemy_enroller.runner import redeem_courses, redeem_courses_ui logger = get_logger() The provided code snippet includes necessary dependencies for implementing the `log_os_version` function. Write a Python function `def log_os_version()` to solve the following problem: Log version of the OS. :return: None Here is the function: def log_os_version(): """ Log version of the OS. :return: None """ logger.debug(f"OS: {platform.platform()}")
Log version of the OS. :return: None
158,612
import argparse import logging import platform import sys from argparse import Namespace from typing import Tuple, Union from pkg_resources import DistributionNotFound, get_distribution from udemy_enroller import ALL_VALID_BROWSER_STRINGS, DriverManager, Settings from udemy_enroller.logger import get_logger from udemy_enroller.runner import redeem_courses, redeem_courses_ui The provided code snippet includes necessary dependencies for implementing the `determine_if_scraper_enabled` function. Write a Python function `def determine_if_scraper_enabled( idownloadcoupon_enabled: bool, freebiesglobal_enabled: bool, tutorialbar_enabled: bool, discudemy_enabled: bool, coursevania_enabled: bool, ) -> Tuple[bool, bool, bool, bool, bool]` to solve the following problem: Determine what scrapers should be enabled and disabled. :return: tuple containing boolean of what scrapers should run Here is the function: def determine_if_scraper_enabled( idownloadcoupon_enabled: bool, freebiesglobal_enabled: bool, tutorialbar_enabled: bool, discudemy_enabled: bool, coursevania_enabled: bool, ) -> Tuple[bool, bool, bool, bool, bool]: """ Determine what scrapers should be enabled and disabled. :return: tuple containing boolean of what scrapers should run """ if ( not idownloadcoupon_enabled and not freebiesglobal_enabled and not tutorialbar_enabled and not discudemy_enabled and not coursevania_enabled ): # Set all to True ( idownloadcoupon_enabled, freebiesglobal_enabled, tutorialbar_enabled, discudemy_enabled, coursevania_enabled, ) = (True, True, True, True, True) return ( idownloadcoupon_enabled, freebiesglobal_enabled, tutorialbar_enabled, discudemy_enabled, coursevania_enabled, )
Determine what scrapers should be enabled and disabled. :return: tuple containing boolean of what scrapers should run
158,613
import argparse import logging import platform import sys from argparse import Namespace from typing import Tuple, Union from pkg_resources import DistributionNotFound, get_distribution from udemy_enroller import ALL_VALID_BROWSER_STRINGS, DriverManager, Settings from udemy_enroller.logger import get_logger from udemy_enroller.runner import redeem_courses, redeem_courses_ui def redeem_courses( settings: Settings, idownloadcoupon_enabled: bool, freebiesglobal_enabled: bool, tutorialbar_enabled: bool, discudemy_enabled: bool, coursevania_enabled: bool, max_pages: Union[int, None], ) -> None: """ Wrap _redeem_courses to catch unhandled exceptions. :param Settings settings: Core settings used for Udemy :param bool idownloadcoupon_enabled: Boolean signifying if idownloadcoupon scraper should run :param bool freebiesglobal_enabled: Boolean signifying if freebiesglobal scraper should run :param bool tutorialbar_enabled: Boolean signifying if tutorialbar scraper should run :param bool discudemy_enabled: Boolean signifying if discudemy scraper should run :param bool coursevania_enabled: Boolean signifying if coursevania scraper should run :param int max_pages: Max pages to scrape from sites (if pagination exists) :return: """ try: scrapers = ScraperManager( idownloadcoupon_enabled, freebiesglobal_enabled, tutorialbar_enabled, discudemy_enabled, coursevania_enabled, max_pages, ) _redeem_courses(settings, scrapers) except Exception as e: logger.error(f"Exception in redeem courses: {e}") def redeem_courses_ui( driver, settings: Settings, idownloadcoupon_enabled: bool, freebiesglobal_enabled: bool, tutorialbar_enabled: bool, discudemy_enabled: bool, coursevania_enabled: bool, max_pages: Union[int, None], ) -> None: """ Wrap _redeem_courses so we always close browser on completion. :param WebDriver driver: WebDriver to use to complete enrolment :param Settings settings: Core settings used for Udemy :param bool idownloadcoupon_enabled: Boolean signifying if idownloadcoupon scraper should run :param bool freebiesglobal_enabled: Boolean signifying if freebiesglobal scraper should run :param bool tutorialbar_enabled: Boolean signifying if tutorialbar scraper should run :param bool discudemy_enabled: Boolean signifying if discudemy scraper should run :param bool coursevania_enabled: Boolean signifying if coursevania scraper should run :param int max_pages: Max pages to scrape from sites (if pagination exists) :return: """ try: scrapers = ScraperManager( idownloadcoupon_enabled, freebiesglobal_enabled, tutorialbar_enabled, discudemy_enabled, coursevania_enabled, max_pages, ) _redeem_courses_ui(driver, settings, scrapers) except Exception as e: logger.error(f"Exception in redeem courses: {e}") finally: logger.info("Closing browser") driver.quit() The provided code snippet includes necessary dependencies for implementing the `run` function. Write a Python function `def run( browser: str, idownloadcoupon_enabled: bool, freebiesglobal_enabled: bool, tutorialbar_enabled: bool, discudemy_enabled: bool, coursevania_enabled: bool, max_pages: Union[int, None], delete_settings: bool, delete_cookie: bool, )` to solve the following problem: Run the udemy enroller script. :param str browser: Name of the browser we want to create a driver for :param bool idownloadcoupon_enabled: :param bool freebiesglobal_enabled: :param bool tutorialbar_enabled: :param bool discudemy_enabled: :param bool coursevania_enabled: :param int max_pages: Max pages to scrape from sites (if pagination exists) :param bool delete_settings: Determines if we should delete old settings file :param bool delete_cookie: Determines if we should delete the cookie file :return: Here is the function: def run( browser: str, idownloadcoupon_enabled: bool, freebiesglobal_enabled: bool, tutorialbar_enabled: bool, discudemy_enabled: bool, coursevania_enabled: bool, max_pages: Union[int, None], delete_settings: bool, delete_cookie: bool, ): """ Run the udemy enroller script. :param str browser: Name of the browser we want to create a driver for :param bool idownloadcoupon_enabled: :param bool freebiesglobal_enabled: :param bool tutorialbar_enabled: :param bool discudemy_enabled: :param bool coursevania_enabled: :param int max_pages: Max pages to scrape from sites (if pagination exists) :param bool delete_settings: Determines if we should delete old settings file :param bool delete_cookie: Determines if we should delete the cookie file :return: """ settings = Settings(delete_settings, delete_cookie) if browser: dm = DriverManager(browser=browser, is_ci_build=settings.is_ci_build) redeem_courses_ui( dm.driver, settings, idownloadcoupon_enabled, freebiesglobal_enabled, tutorialbar_enabled, discudemy_enabled, coursevania_enabled, max_pages, ) else: redeem_courses( settings, idownloadcoupon_enabled, freebiesglobal_enabled, tutorialbar_enabled, discudemy_enabled, coursevania_enabled, max_pages, )
Run the udemy enroller script. :param str browser: Name of the browser we want to create a driver for :param bool idownloadcoupon_enabled: :param bool freebiesglobal_enabled: :param bool tutorialbar_enabled: :param bool discudemy_enabled: :param bool coursevania_enabled: :param int max_pages: Max pages to scrape from sites (if pagination exists) :param bool delete_settings: Determines if we should delete old settings file :param bool delete_cookie: Determines if we should delete the cookie file :return:
158,614
import argparse import logging import platform import sys from argparse import Namespace from typing import Tuple, Union from pkg_resources import DistributionNotFound, get_distribution from udemy_enroller import ALL_VALID_BROWSER_STRINGS, DriverManager, Settings from udemy_enroller.logger import get_logger from udemy_enroller.runner import redeem_courses, redeem_courses_ui The provided code snippet includes necessary dependencies for implementing the `parse_args` function. Write a Python function `def parse_args() -> Namespace` to solve the following problem: Parse args from the CLI or use the args passed in. :return: Args to be used in the script Here is the function: def parse_args() -> Namespace: """ Parse args from the CLI or use the args passed in. :return: Args to be used in the script """ parser = argparse.ArgumentParser(description="Udemy Enroller") parser.add_argument( "--browser", required=False, type=str, choices=ALL_VALID_BROWSER_STRINGS, help="Browser to use for Udemy Enroller", ) parser.add_argument( "--idownloadcoupon", action="store_true", default=False, help="Run idownloadcoupon scraper", ) parser.add_argument( "--freebiesglobal", action="store_true", default=False, help="Run freebiesglobal scraper", ) parser.add_argument( "--tutorialbar", action="store_true", default=False, help="Run tutorialbar scraper", ) parser.add_argument( "--discudemy", action="store_true", default=False, help="Run discudemy scraper", ) parser.add_argument( "--coursevania", action="store_true", default=False, help="Run coursevania scraper", ) parser.add_argument( "--max-pages", type=int, default=5, help="Max pages to scrape from sites (if pagination exists) (Default is 5)", ) parser.add_argument( "--delete-settings", action="store_true", default=False, help="Delete any existing settings file", ) parser.add_argument( "--delete-cookie", action="store_true", default=False, help="Delete existing cookie file", ) parser.add_argument( "--debug", action="store_true", help="Enable debug logging", ) return parser.parse_args()
Parse args from the CLI or use the args passed in. :return: Args to be used in the script
158,615
import os The provided code snippet includes necessary dependencies for implementing the `get_app_dir` function. Write a Python function `def get_app_dir() -> str` to solve the following problem: Get the app directory where all data related to the script is stored. :return: Here is the function: def get_app_dir() -> str: """ Get the app directory where all data related to the script is stored. :return: """ app_dir = os.path.join(os.path.expanduser("~"), ".udemy_enroller") if not os.path.isdir(app_dir): # If the app data dir does not exist create it os.mkdir(app_dir) return app_dir
Get the app directory where all data related to the script is stored. :return: