id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
9,000
Yubico/yubikey-manager
ykman/cli/piv.py
info
def info(ctx): """ Display status of PIV application. """ controller = ctx.obj['controller'] click.echo('PIV version: %d.%d.%d' % controller.version) # Largest possible number of PIN tries to get back is 15 tries = controller.get_pin_tries() tries = '15 or more.' if tries == 15 else tries click.echo('PIN tries remaining: %s' % tries) if controller.puk_blocked: click.echo('PUK blocked.') if controller.has_derived_key: click.echo('Management key is derived from PIN.') if controller.has_stored_key: click.echo('Management key is stored on the YubiKey, protected by PIN.') try: chuid = b2a_hex(controller.get_data(OBJ.CHUID)).decode() except APDUError as e: if e.sw == SW.NOT_FOUND: chuid = 'No data available.' click.echo('CHUID:\t' + chuid) try: ccc = b2a_hex(controller.get_data(OBJ.CAPABILITY)).decode() except APDUError as e: if e.sw == SW.NOT_FOUND: ccc = 'No data available.' click.echo('CCC: \t' + ccc) for (slot, cert) in controller.list_certificates().items(): click.echo('Slot %02x:' % slot) try: # Try to read out full DN, fallback to only CN. # Support for DN was added in crytography 2.5 subject_dn = cert.subject.rfc4514_string() issuer_dn = cert.issuer.rfc4514_string() print_dn = True except AttributeError: print_dn = False logger.debug('Failed to read DN, falling back to only CNs') subject_cn = cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) subject_cn = subject_cn[0].value if subject_cn else 'None' issuer_cn = cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME) issuer_cn = issuer_cn[0].value if issuer_cn else 'None' except ValueError as e: # Malformed certificates may throw ValueError logger.debug('Failed parsing certificate', exc_info=e) click.echo('\tMalformed certificate: {}'.format(e)) continue fingerprint = b2a_hex(cert.fingerprint(hashes.SHA256())).decode('ascii') algo = ALGO.from_public_key(cert.public_key()) serial = cert.serial_number not_before = cert.not_valid_before not_after = cert.not_valid_after # Print out everything click.echo('\tAlgorithm:\t%s' % algo.name) if print_dn: click.echo('\tSubject DN:\t%s' % subject_dn) click.echo('\tIssuer DN:\t%s' % issuer_dn) else: click.echo('\tSubject CN:\t%s' % subject_cn) click.echo('\tIssuer CN:\t%s' % issuer_cn) click.echo('\tSerial:\t\t%s' % serial) click.echo('\tFingerprint:\t%s' % fingerprint) click.echo('\tNot before:\t%s' % not_before) click.echo('\tNot after:\t%s' % not_after)
python
def info(ctx): """ Display status of PIV application. """ controller = ctx.obj['controller'] click.echo('PIV version: %d.%d.%d' % controller.version) # Largest possible number of PIN tries to get back is 15 tries = controller.get_pin_tries() tries = '15 or more.' if tries == 15 else tries click.echo('PIN tries remaining: %s' % tries) if controller.puk_blocked: click.echo('PUK blocked.') if controller.has_derived_key: click.echo('Management key is derived from PIN.') if controller.has_stored_key: click.echo('Management key is stored on the YubiKey, protected by PIN.') try: chuid = b2a_hex(controller.get_data(OBJ.CHUID)).decode() except APDUError as e: if e.sw == SW.NOT_FOUND: chuid = 'No data available.' click.echo('CHUID:\t' + chuid) try: ccc = b2a_hex(controller.get_data(OBJ.CAPABILITY)).decode() except APDUError as e: if e.sw == SW.NOT_FOUND: ccc = 'No data available.' click.echo('CCC: \t' + ccc) for (slot, cert) in controller.list_certificates().items(): click.echo('Slot %02x:' % slot) try: # Try to read out full DN, fallback to only CN. # Support for DN was added in crytography 2.5 subject_dn = cert.subject.rfc4514_string() issuer_dn = cert.issuer.rfc4514_string() print_dn = True except AttributeError: print_dn = False logger.debug('Failed to read DN, falling back to only CNs') subject_cn = cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) subject_cn = subject_cn[0].value if subject_cn else 'None' issuer_cn = cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME) issuer_cn = issuer_cn[0].value if issuer_cn else 'None' except ValueError as e: # Malformed certificates may throw ValueError logger.debug('Failed parsing certificate', exc_info=e) click.echo('\tMalformed certificate: {}'.format(e)) continue fingerprint = b2a_hex(cert.fingerprint(hashes.SHA256())).decode('ascii') algo = ALGO.from_public_key(cert.public_key()) serial = cert.serial_number not_before = cert.not_valid_before not_after = cert.not_valid_after # Print out everything click.echo('\tAlgorithm:\t%s' % algo.name) if print_dn: click.echo('\tSubject DN:\t%s' % subject_dn) click.echo('\tIssuer DN:\t%s' % issuer_dn) else: click.echo('\tSubject CN:\t%s' % subject_cn) click.echo('\tIssuer CN:\t%s' % issuer_cn) click.echo('\tSerial:\t\t%s' % serial) click.echo('\tFingerprint:\t%s' % fingerprint) click.echo('\tNot before:\t%s' % not_before) click.echo('\tNot after:\t%s' % not_after)
[ "def", "info", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "click", ".", "echo", "(", "'PIV version: %d.%d.%d'", "%", "controller", ".", "version", ")", "# Largest possible number of PIN tries to get back is 15", "tries", "=", "controller", ".", "get_pin_tries", "(", ")", "tries", "=", "'15 or more.'", "if", "tries", "==", "15", "else", "tries", "click", ".", "echo", "(", "'PIN tries remaining: %s'", "%", "tries", ")", "if", "controller", ".", "puk_blocked", ":", "click", ".", "echo", "(", "'PUK blocked.'", ")", "if", "controller", ".", "has_derived_key", ":", "click", ".", "echo", "(", "'Management key is derived from PIN.'", ")", "if", "controller", ".", "has_stored_key", ":", "click", ".", "echo", "(", "'Management key is stored on the YubiKey, protected by PIN.'", ")", "try", ":", "chuid", "=", "b2a_hex", "(", "controller", ".", "get_data", "(", "OBJ", ".", "CHUID", ")", ")", ".", "decode", "(", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "chuid", "=", "'No data available.'", "click", ".", "echo", "(", "'CHUID:\\t'", "+", "chuid", ")", "try", ":", "ccc", "=", "b2a_hex", "(", "controller", ".", "get_data", "(", "OBJ", ".", "CAPABILITY", ")", ")", ".", "decode", "(", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "ccc", "=", "'No data available.'", "click", ".", "echo", "(", "'CCC: \\t'", "+", "ccc", ")", "for", "(", "slot", ",", "cert", ")", "in", "controller", ".", "list_certificates", "(", ")", ".", "items", "(", ")", ":", "click", ".", "echo", "(", "'Slot %02x:'", "%", "slot", ")", "try", ":", "# Try to read out full DN, fallback to only CN.", "# Support for DN was added in crytography 2.5", "subject_dn", "=", "cert", ".", "subject", ".", "rfc4514_string", "(", ")", "issuer_dn", "=", "cert", ".", "issuer", ".", "rfc4514_string", "(", ")", "print_dn", "=", "True", "except", "AttributeError", ":", "print_dn", "=", "False", "logger", ".", "debug", "(", "'Failed to read DN, falling back to only CNs'", ")", "subject_cn", "=", "cert", ".", "subject", ".", "get_attributes_for_oid", "(", "x509", ".", "NameOID", ".", "COMMON_NAME", ")", "subject_cn", "=", "subject_cn", "[", "0", "]", ".", "value", "if", "subject_cn", "else", "'None'", "issuer_cn", "=", "cert", ".", "issuer", ".", "get_attributes_for_oid", "(", "x509", ".", "NameOID", ".", "COMMON_NAME", ")", "issuer_cn", "=", "issuer_cn", "[", "0", "]", ".", "value", "if", "issuer_cn", "else", "'None'", "except", "ValueError", "as", "e", ":", "# Malformed certificates may throw ValueError", "logger", ".", "debug", "(", "'Failed parsing certificate'", ",", "exc_info", "=", "e", ")", "click", ".", "echo", "(", "'\\tMalformed certificate: {}'", ".", "format", "(", "e", ")", ")", "continue", "fingerprint", "=", "b2a_hex", "(", "cert", ".", "fingerprint", "(", "hashes", ".", "SHA256", "(", ")", ")", ")", ".", "decode", "(", "'ascii'", ")", "algo", "=", "ALGO", ".", "from_public_key", "(", "cert", ".", "public_key", "(", ")", ")", "serial", "=", "cert", ".", "serial_number", "not_before", "=", "cert", ".", "not_valid_before", "not_after", "=", "cert", ".", "not_valid_after", "# Print out everything", "click", ".", "echo", "(", "'\\tAlgorithm:\\t%s'", "%", "algo", ".", "name", ")", "if", "print_dn", ":", "click", ".", "echo", "(", "'\\tSubject DN:\\t%s'", "%", "subject_dn", ")", "click", ".", "echo", "(", "'\\tIssuer DN:\\t%s'", "%", "issuer_dn", ")", "else", ":", "click", ".", "echo", "(", "'\\tSubject CN:\\t%s'", "%", "subject_cn", ")", "click", ".", "echo", "(", "'\\tIssuer CN:\\t%s'", "%", "issuer_cn", ")", "click", ".", "echo", "(", "'\\tSerial:\\t\\t%s'", "%", "serial", ")", "click", ".", "echo", "(", "'\\tFingerprint:\\t%s'", "%", "fingerprint", ")", "click", ".", "echo", "(", "'\\tNot before:\\t%s'", "%", "not_before", ")", "click", ".", "echo", "(", "'\\tNot after:\\t%s'", "%", "not_after", ")" ]
Display status of PIV application.
[ "Display", "status", "of", "PIV", "application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L125-L195
9,001
Yubico/yubikey-manager
ykman/cli/piv.py
reset
def reset(ctx): """ Reset all PIV data. This action will wipe all data and restore factory settings for the PIV application on your YubiKey. """ click.echo('Resetting PIV data...') ctx.obj['controller'].reset() click.echo( 'Success! All PIV data have been cleared from your YubiKey.') click.echo('Your YubiKey now has the default PIN, PUK and Management Key:') click.echo('\tPIN:\t123456') click.echo('\tPUK:\t12345678') click.echo( '\tManagement Key:\t010203040506070801020304050607080102030405060708')
python
def reset(ctx): """ Reset all PIV data. This action will wipe all data and restore factory settings for the PIV application on your YubiKey. """ click.echo('Resetting PIV data...') ctx.obj['controller'].reset() click.echo( 'Success! All PIV data have been cleared from your YubiKey.') click.echo('Your YubiKey now has the default PIN, PUK and Management Key:') click.echo('\tPIN:\t123456') click.echo('\tPUK:\t12345678') click.echo( '\tManagement Key:\t010203040506070801020304050607080102030405060708')
[ "def", "reset", "(", "ctx", ")", ":", "click", ".", "echo", "(", "'Resetting PIV data...'", ")", "ctx", ".", "obj", "[", "'controller'", "]", ".", "reset", "(", ")", "click", ".", "echo", "(", "'Success! All PIV data have been cleared from your YubiKey.'", ")", "click", ".", "echo", "(", "'Your YubiKey now has the default PIN, PUK and Management Key:'", ")", "click", ".", "echo", "(", "'\\tPIN:\\t123456'", ")", "click", ".", "echo", "(", "'\\tPUK:\\t12345678'", ")", "click", ".", "echo", "(", "'\\tManagement Key:\\t010203040506070801020304050607080102030405060708'", ")" ]
Reset all PIV data. This action will wipe all data and restore factory settings for the PIV application on your YubiKey.
[ "Reset", "all", "PIV", "data", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L203-L219
9,002
Yubico/yubikey-manager
ykman/cli/piv.py
generate_key
def generate_key( ctx, slot, public_key_output, management_key, pin, algorithm, format, pin_policy, touch_policy): """ Generate an asymmetric key pair. The private key is generated on the YubiKey, and written to one of the slots. \b SLOT PIV slot where private key should be stored. PUBLIC-KEY File containing the generated public key. Use '-' to use stdout. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) algorithm_id = ALGO.from_string(algorithm) if pin_policy: pin_policy = PIN_POLICY.from_string(pin_policy) if touch_policy: touch_policy = TOUCH_POLICY.from_string(touch_policy) _check_pin_policy(ctx, dev, controller, pin_policy) _check_touch_policy(ctx, controller, touch_policy) try: public_key = controller.generate_key( slot, algorithm_id, pin_policy, touch_policy) except UnsupportedAlgorithm: ctx.fail('Algorithm {} is not supported by this ' 'YubiKey.'.format(algorithm)) key_encoding = format public_key_output.write(public_key.public_bytes( encoding=key_encoding, format=serialization.PublicFormat.SubjectPublicKeyInfo))
python
def generate_key( ctx, slot, public_key_output, management_key, pin, algorithm, format, pin_policy, touch_policy): """ Generate an asymmetric key pair. The private key is generated on the YubiKey, and written to one of the slots. \b SLOT PIV slot where private key should be stored. PUBLIC-KEY File containing the generated public key. Use '-' to use stdout. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) algorithm_id = ALGO.from_string(algorithm) if pin_policy: pin_policy = PIN_POLICY.from_string(pin_policy) if touch_policy: touch_policy = TOUCH_POLICY.from_string(touch_policy) _check_pin_policy(ctx, dev, controller, pin_policy) _check_touch_policy(ctx, controller, touch_policy) try: public_key = controller.generate_key( slot, algorithm_id, pin_policy, touch_policy) except UnsupportedAlgorithm: ctx.fail('Algorithm {} is not supported by this ' 'YubiKey.'.format(algorithm)) key_encoding = format public_key_output.write(public_key.public_bytes( encoding=key_encoding, format=serialization.PublicFormat.SubjectPublicKeyInfo))
[ "def", "generate_key", "(", "ctx", ",", "slot", ",", "public_key_output", ",", "management_key", ",", "pin", ",", "algorithm", ",", "format", ",", "pin_policy", ",", "touch_policy", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "algorithm_id", "=", "ALGO", ".", "from_string", "(", "algorithm", ")", "if", "pin_policy", ":", "pin_policy", "=", "PIN_POLICY", ".", "from_string", "(", "pin_policy", ")", "if", "touch_policy", ":", "touch_policy", "=", "TOUCH_POLICY", ".", "from_string", "(", "touch_policy", ")", "_check_pin_policy", "(", "ctx", ",", "dev", ",", "controller", ",", "pin_policy", ")", "_check_touch_policy", "(", "ctx", ",", "controller", ",", "touch_policy", ")", "try", ":", "public_key", "=", "controller", ".", "generate_key", "(", "slot", ",", "algorithm_id", ",", "pin_policy", ",", "touch_policy", ")", "except", "UnsupportedAlgorithm", ":", "ctx", ".", "fail", "(", "'Algorithm {} is not supported by this '", "'YubiKey.'", ".", "format", "(", "algorithm", ")", ")", "key_encoding", "=", "format", "public_key_output", ".", "write", "(", "public_key", ".", "public_bytes", "(", "encoding", "=", "key_encoding", ",", "format", "=", "serialization", ".", "PublicFormat", ".", "SubjectPublicKeyInfo", ")", ")" ]
Generate an asymmetric key pair. The private key is generated on the YubiKey, and written to one of the slots. \b SLOT PIV slot where private key should be stored. PUBLIC-KEY File containing the generated public key. Use '-' to use stdout.
[ "Generate", "an", "asymmetric", "key", "pair", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L237-L279
9,003
Yubico/yubikey-manager
ykman/cli/piv.py
import_certificate
def import_certificate( ctx, slot, management_key, pin, cert, password, verify): """ Import a X.509 certificate. Write a certificate to one of the slots on the YubiKey. \b SLOT PIV slot to import the certificate to. CERTIFICATE File containing the certificate. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) data = cert.read() while True: if password is not None: password = password.encode() try: certs = parse_certificates(data, password) except (ValueError, TypeError): if password is None: password = click.prompt( 'Enter password to decrypt certificate', default='', hide_input=True, show_default=False, err=True) continue else: password = None click.echo('Wrong password.') continue break if len(certs) > 1: # If multiple certs, only import leaf. # Leaf is the cert with a subject that is not an issuer in the chain. leafs = get_leaf_certificates(certs) cert_to_import = leafs[0] else: cert_to_import = certs[0] def do_import(retry=True): try: controller.import_certificate( slot, cert_to_import, verify=verify, touch_callback=prompt_for_touch) except KeypairMismatch: ctx.fail('This certificate is not tied to the private key in the ' '{} slot.'.format(slot.name)) except APDUError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED and retry: _verify_pin(ctx, controller, pin) do_import(retry=False) else: raise do_import()
python
def import_certificate( ctx, slot, management_key, pin, cert, password, verify): """ Import a X.509 certificate. Write a certificate to one of the slots on the YubiKey. \b SLOT PIV slot to import the certificate to. CERTIFICATE File containing the certificate. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) data = cert.read() while True: if password is not None: password = password.encode() try: certs = parse_certificates(data, password) except (ValueError, TypeError): if password is None: password = click.prompt( 'Enter password to decrypt certificate', default='', hide_input=True, show_default=False, err=True) continue else: password = None click.echo('Wrong password.') continue break if len(certs) > 1: # If multiple certs, only import leaf. # Leaf is the cert with a subject that is not an issuer in the chain. leafs = get_leaf_certificates(certs) cert_to_import = leafs[0] else: cert_to_import = certs[0] def do_import(retry=True): try: controller.import_certificate( slot, cert_to_import, verify=verify, touch_callback=prompt_for_touch) except KeypairMismatch: ctx.fail('This certificate is not tied to the private key in the ' '{} slot.'.format(slot.name)) except APDUError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED and retry: _verify_pin(ctx, controller, pin) do_import(retry=False) else: raise do_import()
[ "def", "import_certificate", "(", "ctx", ",", "slot", ",", "management_key", ",", "pin", ",", "cert", ",", "password", ",", "verify", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "data", "=", "cert", ".", "read", "(", ")", "while", "True", ":", "if", "password", "is", "not", "None", ":", "password", "=", "password", ".", "encode", "(", ")", "try", ":", "certs", "=", "parse_certificates", "(", "data", ",", "password", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "if", "password", "is", "None", ":", "password", "=", "click", ".", "prompt", "(", "'Enter password to decrypt certificate'", ",", "default", "=", "''", ",", "hide_input", "=", "True", ",", "show_default", "=", "False", ",", "err", "=", "True", ")", "continue", "else", ":", "password", "=", "None", "click", ".", "echo", "(", "'Wrong password.'", ")", "continue", "break", "if", "len", "(", "certs", ")", ">", "1", ":", "# If multiple certs, only import leaf.", "# Leaf is the cert with a subject that is not an issuer in the chain.", "leafs", "=", "get_leaf_certificates", "(", "certs", ")", "cert_to_import", "=", "leafs", "[", "0", "]", "else", ":", "cert_to_import", "=", "certs", "[", "0", "]", "def", "do_import", "(", "retry", "=", "True", ")", ":", "try", ":", "controller", ".", "import_certificate", "(", "slot", ",", "cert_to_import", ",", "verify", "=", "verify", ",", "touch_callback", "=", "prompt_for_touch", ")", "except", "KeypairMismatch", ":", "ctx", ".", "fail", "(", "'This certificate is not tied to the private key in the '", "'{} slot.'", ".", "format", "(", "slot", ".", "name", ")", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "SECURITY_CONDITION_NOT_SATISFIED", "and", "retry", ":", "_verify_pin", "(", "ctx", ",", "controller", ",", "pin", ")", "do_import", "(", "retry", "=", "False", ")", "else", ":", "raise", "do_import", "(", ")" ]
Import a X.509 certificate. Write a certificate to one of the slots on the YubiKey. \b SLOT PIV slot to import the certificate to. CERTIFICATE File containing the certificate. Use '-' to use stdin.
[ "Import", "a", "X", ".", "509", "certificate", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L293-L353
9,004
Yubico/yubikey-manager
ykman/cli/piv.py
import_key
def import_key( ctx, slot, management_key, pin, private_key, pin_policy, touch_policy, password): """ Import a private key. Write a private key to one of the slots on the YubiKey. \b SLOT PIV slot to import the private key to. PRIVATE-KEY File containing the private key. Use '-' to use stdin. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) data = private_key.read() while True: if password is not None: password = password.encode() try: private_key = parse_private_key(data, password) except (ValueError, TypeError): if password is None: password = click.prompt( 'Enter password to decrypt key', default='', hide_input=True, show_default=False, err=True) continue else: password = None click.echo('Wrong password.') continue break if pin_policy: pin_policy = PIN_POLICY.from_string(pin_policy) if touch_policy: touch_policy = TOUCH_POLICY.from_string(touch_policy) _check_pin_policy(ctx, dev, controller, pin_policy) _check_touch_policy(ctx, controller, touch_policy) _check_key_size(ctx, controller, private_key) controller.import_key( slot, private_key, pin_policy, touch_policy)
python
def import_key( ctx, slot, management_key, pin, private_key, pin_policy, touch_policy, password): """ Import a private key. Write a private key to one of the slots on the YubiKey. \b SLOT PIV slot to import the private key to. PRIVATE-KEY File containing the private key. Use '-' to use stdin. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) data = private_key.read() while True: if password is not None: password = password.encode() try: private_key = parse_private_key(data, password) except (ValueError, TypeError): if password is None: password = click.prompt( 'Enter password to decrypt key', default='', hide_input=True, show_default=False, err=True) continue else: password = None click.echo('Wrong password.') continue break if pin_policy: pin_policy = PIN_POLICY.from_string(pin_policy) if touch_policy: touch_policy = TOUCH_POLICY.from_string(touch_policy) _check_pin_policy(ctx, dev, controller, pin_policy) _check_touch_policy(ctx, controller, touch_policy) _check_key_size(ctx, controller, private_key) controller.import_key( slot, private_key, pin_policy, touch_policy)
[ "def", "import_key", "(", "ctx", ",", "slot", ",", "management_key", ",", "pin", ",", "private_key", ",", "pin_policy", ",", "touch_policy", ",", "password", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "data", "=", "private_key", ".", "read", "(", ")", "while", "True", ":", "if", "password", "is", "not", "None", ":", "password", "=", "password", ".", "encode", "(", ")", "try", ":", "private_key", "=", "parse_private_key", "(", "data", ",", "password", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "if", "password", "is", "None", ":", "password", "=", "click", ".", "prompt", "(", "'Enter password to decrypt key'", ",", "default", "=", "''", ",", "hide_input", "=", "True", ",", "show_default", "=", "False", ",", "err", "=", "True", ")", "continue", "else", ":", "password", "=", "None", "click", ".", "echo", "(", "'Wrong password.'", ")", "continue", "break", "if", "pin_policy", ":", "pin_policy", "=", "PIN_POLICY", ".", "from_string", "(", "pin_policy", ")", "if", "touch_policy", ":", "touch_policy", "=", "TOUCH_POLICY", ".", "from_string", "(", "touch_policy", ")", "_check_pin_policy", "(", "ctx", ",", "dev", ",", "controller", ",", "pin_policy", ")", "_check_touch_policy", "(", "ctx", ",", "controller", ",", "touch_policy", ")", "_check_key_size", "(", "ctx", ",", "controller", ",", "private_key", ")", "controller", ".", "import_key", "(", "slot", ",", "private_key", ",", "pin_policy", ",", "touch_policy", ")" ]
Import a private key. Write a private key to one of the slots on the YubiKey. \b SLOT PIV slot to import the private key to. PRIVATE-KEY File containing the private key. Use '-' to use stdin.
[ "Import", "a", "private", "key", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L366-L416
9,005
Yubico/yubikey-manager
ykman/cli/piv.py
export_certificate
def export_certificate(ctx, slot, format, certificate): """ Export a X.509 certificate. Reads a certificate from one of the slots on the YubiKey. \b SLOT PIV slot to read certificate from. CERTIFICATE File to write certificate to. Use '-' to use stdout. """ controller = ctx.obj['controller'] try: cert = controller.read_certificate(slot) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail('No certificate found.') else: logger.error('Failed to read certificate from slot %s', slot, exc_info=e) certificate.write(cert.public_bytes(encoding=format))
python
def export_certificate(ctx, slot, format, certificate): """ Export a X.509 certificate. Reads a certificate from one of the slots on the YubiKey. \b SLOT PIV slot to read certificate from. CERTIFICATE File to write certificate to. Use '-' to use stdout. """ controller = ctx.obj['controller'] try: cert = controller.read_certificate(slot) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail('No certificate found.') else: logger.error('Failed to read certificate from slot %s', slot, exc_info=e) certificate.write(cert.public_bytes(encoding=format))
[ "def", "export_certificate", "(", "ctx", ",", "slot", ",", "format", ",", "certificate", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "try", ":", "cert", "=", "controller", ".", "read_certificate", "(", "slot", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "ctx", ".", "fail", "(", "'No certificate found.'", ")", "else", ":", "logger", ".", "error", "(", "'Failed to read certificate from slot %s'", ",", "slot", ",", "exc_info", "=", "e", ")", "certificate", ".", "write", "(", "cert", ".", "public_bytes", "(", "encoding", "=", "format", ")", ")" ]
Export a X.509 certificate. Reads a certificate from one of the slots on the YubiKey. \b SLOT PIV slot to read certificate from. CERTIFICATE File to write certificate to. Use '-' to use stdout.
[ "Export", "a", "X", ".", "509", "certificate", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L449-L468
9,006
Yubico/yubikey-manager
ykman/cli/piv.py
set_chuid
def set_chuid(ctx, management_key, pin): """ Generate and set a CHUID on the YubiKey. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) controller.update_chuid()
python
def set_chuid(ctx, management_key, pin): """ Generate and set a CHUID on the YubiKey. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) controller.update_chuid()
[ "def", "set_chuid", "(", "ctx", ",", "management_key", ",", "pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "controller", ".", "update_chuid", "(", ")" ]
Generate and set a CHUID on the YubiKey.
[ "Generate", "and", "set", "a", "CHUID", "on", "the", "YubiKey", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L475-L481
9,007
Yubico/yubikey-manager
ykman/cli/piv.py
set_ccc
def set_ccc(ctx, management_key, pin): """ Generate and set a CCC on the YubiKey. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) controller.update_ccc()
python
def set_ccc(ctx, management_key, pin): """ Generate and set a CCC on the YubiKey. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) controller.update_ccc()
[ "def", "set_ccc", "(", "ctx", ",", "management_key", ",", "pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "controller", ".", "update_ccc", "(", ")" ]
Generate and set a CCC on the YubiKey.
[ "Generate", "and", "set", "a", "CCC", "on", "the", "YubiKey", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L488-L494
9,008
Yubico/yubikey-manager
ykman/cli/piv.py
generate_certificate
def generate_certificate( ctx, slot, management_key, pin, public_key, subject, valid_days): """ Generate a self-signed X.509 certificate. A self-signed certificate is generated and written to one of the slots on the YubiKey. A private key need to exist in the slot. \b SLOT PIV slot where private key is stored. PUBLIC-KEY File containing a public key. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated( ctx, controller, pin, management_key, require_pin_and_key=True) data = public_key.read() public_key = serialization.load_pem_public_key( data, default_backend()) now = datetime.datetime.now() valid_to = now + datetime.timedelta(days=valid_days) try: controller.generate_self_signed_certificate( slot, public_key, subject, now, valid_to, touch_callback=prompt_for_touch) except APDUError as e: logger.error('Failed to generate certificate for slot %s', slot, exc_info=e) ctx.fail('Certificate generation failed.')
python
def generate_certificate( ctx, slot, management_key, pin, public_key, subject, valid_days): """ Generate a self-signed X.509 certificate. A self-signed certificate is generated and written to one of the slots on the YubiKey. A private key need to exist in the slot. \b SLOT PIV slot where private key is stored. PUBLIC-KEY File containing a public key. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated( ctx, controller, pin, management_key, require_pin_and_key=True) data = public_key.read() public_key = serialization.load_pem_public_key( data, default_backend()) now = datetime.datetime.now() valid_to = now + datetime.timedelta(days=valid_days) try: controller.generate_self_signed_certificate( slot, public_key, subject, now, valid_to, touch_callback=prompt_for_touch) except APDUError as e: logger.error('Failed to generate certificate for slot %s', slot, exc_info=e) ctx.fail('Certificate generation failed.')
[ "def", "generate_certificate", "(", "ctx", ",", "slot", ",", "management_key", ",", "pin", ",", "public_key", ",", "subject", ",", "valid_days", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ",", "require_pin_and_key", "=", "True", ")", "data", "=", "public_key", ".", "read", "(", ")", "public_key", "=", "serialization", ".", "load_pem_public_key", "(", "data", ",", "default_backend", "(", ")", ")", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "valid_to", "=", "now", "+", "datetime", ".", "timedelta", "(", "days", "=", "valid_days", ")", "try", ":", "controller", ".", "generate_self_signed_certificate", "(", "slot", ",", "public_key", ",", "subject", ",", "now", ",", "valid_to", ",", "touch_callback", "=", "prompt_for_touch", ")", "except", "APDUError", "as", "e", ":", "logger", ".", "error", "(", "'Failed to generate certificate for slot %s'", ",", "slot", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Certificate generation failed.'", ")" ]
Generate a self-signed X.509 certificate. A self-signed certificate is generated and written to one of the slots on the YubiKey. A private key need to exist in the slot. \b SLOT PIV slot where private key is stored. PUBLIC-KEY File containing a public key. Use '-' to use stdin.
[ "Generate", "a", "self", "-", "signed", "X", ".", "509", "certificate", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L542-L573
9,009
Yubico/yubikey-manager
ykman/cli/piv.py
change_pin
def change_pin(ctx, pin, new_pin): """ Change the PIN code. The PIN must be between 6 and 8 characters long, and supports any type of alphanumeric characters. For cross-platform compatibility, numeric digits are recommended. """ controller = ctx.obj['controller'] if not pin: pin = _prompt_pin(ctx, prompt='Enter your current PIN') if not new_pin: new_pin = click.prompt( 'Enter your new PIN', default='', hide_input=True, show_default=False, confirmation_prompt=True, err=True) if not _valid_pin_length(pin): ctx.fail('Current PIN must be between 6 and 8 characters long.') if not _valid_pin_length(new_pin): ctx.fail('New PIN must be between 6 and 8 characters long.') try: controller.change_pin(pin, new_pin) click.echo('New PIN set.') except AuthenticationBlocked as e: logger.debug('PIN is blocked.', exc_info=e) ctx.fail('PIN is blocked.') except WrongPin as e: logger.debug( 'Failed to change PIN, %d tries left', e.tries_left, exc_info=e) ctx.fail('PIN change failed - %d tries left.' % e.tries_left)
python
def change_pin(ctx, pin, new_pin): """ Change the PIN code. The PIN must be between 6 and 8 characters long, and supports any type of alphanumeric characters. For cross-platform compatibility, numeric digits are recommended. """ controller = ctx.obj['controller'] if not pin: pin = _prompt_pin(ctx, prompt='Enter your current PIN') if not new_pin: new_pin = click.prompt( 'Enter your new PIN', default='', hide_input=True, show_default=False, confirmation_prompt=True, err=True) if not _valid_pin_length(pin): ctx.fail('Current PIN must be between 6 and 8 characters long.') if not _valid_pin_length(new_pin): ctx.fail('New PIN must be between 6 and 8 characters long.') try: controller.change_pin(pin, new_pin) click.echo('New PIN set.') except AuthenticationBlocked as e: logger.debug('PIN is blocked.', exc_info=e) ctx.fail('PIN is blocked.') except WrongPin as e: logger.debug( 'Failed to change PIN, %d tries left', e.tries_left, exc_info=e) ctx.fail('PIN change failed - %d tries left.' % e.tries_left)
[ "def", "change_pin", "(", "ctx", ",", "pin", ",", "new_pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "pin", ":", "pin", "=", "_prompt_pin", "(", "ctx", ",", "prompt", "=", "'Enter your current PIN'", ")", "if", "not", "new_pin", ":", "new_pin", "=", "click", ".", "prompt", "(", "'Enter your new PIN'", ",", "default", "=", "''", ",", "hide_input", "=", "True", ",", "show_default", "=", "False", ",", "confirmation_prompt", "=", "True", ",", "err", "=", "True", ")", "if", "not", "_valid_pin_length", "(", "pin", ")", ":", "ctx", ".", "fail", "(", "'Current PIN must be between 6 and 8 characters long.'", ")", "if", "not", "_valid_pin_length", "(", "new_pin", ")", ":", "ctx", ".", "fail", "(", "'New PIN must be between 6 and 8 characters long.'", ")", "try", ":", "controller", ".", "change_pin", "(", "pin", ",", "new_pin", ")", "click", ".", "echo", "(", "'New PIN set.'", ")", "except", "AuthenticationBlocked", "as", "e", ":", "logger", ".", "debug", "(", "'PIN is blocked.'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'PIN is blocked.'", ")", "except", "WrongPin", "as", "e", ":", "logger", ".", "debug", "(", "'Failed to change PIN, %d tries left'", ",", "e", ".", "tries_left", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'PIN change failed - %d tries left.'", "%", "e", ".", "tries_left", ")" ]
Change the PIN code. The PIN must be between 6 and 8 characters long, and supports any type of alphanumeric characters. For cross-platform compatibility, numeric digits are recommended.
[ "Change", "the", "PIN", "code", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L635-L670
9,010
Yubico/yubikey-manager
ykman/cli/piv.py
change_puk
def change_puk(ctx, puk, new_puk): """ Change the PUK code. If the PIN is lost or blocked it can be reset using a PUK. The PUK must be between 6 and 8 characters long, and supports any type of alphanumeric characters. """ controller = ctx.obj['controller'] if not puk: puk = _prompt_pin(ctx, prompt='Enter your current PUK') if not new_puk: new_puk = click.prompt( 'Enter your new PUK', default='', hide_input=True, show_default=False, confirmation_prompt=True, err=True) if not _valid_pin_length(puk): ctx.fail('Current PUK must be between 6 and 8 characters long.') if not _valid_pin_length(new_puk): ctx.fail('New PUK must be between 6 and 8 characters long.') try: controller.change_puk(puk, new_puk) click.echo('New PUK set.') except AuthenticationBlocked as e: logger.debug('PUK is blocked.', exc_info=e) ctx.fail('PUK is blocked.') except WrongPuk as e: logger.debug( 'Failed to change PUK, %d tries left', e.tries_left, exc_info=e) ctx.fail('PUK change failed - %d tries left.' % e.tries_left)
python
def change_puk(ctx, puk, new_puk): """ Change the PUK code. If the PIN is lost or blocked it can be reset using a PUK. The PUK must be between 6 and 8 characters long, and supports any type of alphanumeric characters. """ controller = ctx.obj['controller'] if not puk: puk = _prompt_pin(ctx, prompt='Enter your current PUK') if not new_puk: new_puk = click.prompt( 'Enter your new PUK', default='', hide_input=True, show_default=False, confirmation_prompt=True, err=True) if not _valid_pin_length(puk): ctx.fail('Current PUK must be between 6 and 8 characters long.') if not _valid_pin_length(new_puk): ctx.fail('New PUK must be between 6 and 8 characters long.') try: controller.change_puk(puk, new_puk) click.echo('New PUK set.') except AuthenticationBlocked as e: logger.debug('PUK is blocked.', exc_info=e) ctx.fail('PUK is blocked.') except WrongPuk as e: logger.debug( 'Failed to change PUK, %d tries left', e.tries_left, exc_info=e) ctx.fail('PUK change failed - %d tries left.' % e.tries_left)
[ "def", "change_puk", "(", "ctx", ",", "puk", ",", "new_puk", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "puk", ":", "puk", "=", "_prompt_pin", "(", "ctx", ",", "prompt", "=", "'Enter your current PUK'", ")", "if", "not", "new_puk", ":", "new_puk", "=", "click", ".", "prompt", "(", "'Enter your new PUK'", ",", "default", "=", "''", ",", "hide_input", "=", "True", ",", "show_default", "=", "False", ",", "confirmation_prompt", "=", "True", ",", "err", "=", "True", ")", "if", "not", "_valid_pin_length", "(", "puk", ")", ":", "ctx", ".", "fail", "(", "'Current PUK must be between 6 and 8 characters long.'", ")", "if", "not", "_valid_pin_length", "(", "new_puk", ")", ":", "ctx", ".", "fail", "(", "'New PUK must be between 6 and 8 characters long.'", ")", "try", ":", "controller", ".", "change_puk", "(", "puk", ",", "new_puk", ")", "click", ".", "echo", "(", "'New PUK set.'", ")", "except", "AuthenticationBlocked", "as", "e", ":", "logger", ".", "debug", "(", "'PUK is blocked.'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'PUK is blocked.'", ")", "except", "WrongPuk", "as", "e", ":", "logger", ".", "debug", "(", "'Failed to change PUK, %d tries left'", ",", "e", ".", "tries_left", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'PUK change failed - %d tries left.'", "%", "e", ".", "tries_left", ")" ]
Change the PUK code. If the PIN is lost or blocked it can be reset using a PUK. The PUK must be between 6 and 8 characters long, and supports any type of alphanumeric characters.
[ "Change", "the", "PUK", "code", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L677-L711
9,011
Yubico/yubikey-manager
ykman/cli/piv.py
change_management_key
def change_management_key( ctx, management_key, pin, new_management_key, touch, protect, generate, force): """ Change the management key. Management functionality is guarded by a 24 byte management key. This key is required for administrative tasks, such as generating key pairs. A random key may be generated and stored on the YubiKey, protected by PIN. """ controller = ctx.obj['controller'] pin_verified = _ensure_authenticated( ctx, controller, pin, management_key, require_pin_and_key=protect, mgm_key_prompt='Enter your current management key ' '[blank to use default key]', no_prompt=force) if new_management_key and generate: ctx.fail('Invalid options: --new-management-key conflicts with ' '--generate') # Touch not supported on NEO. if touch and controller.version < (4, 0, 0): ctx.fail('Require touch not supported on this YubiKey.') # If an old stored key needs to be cleared, the PIN is needed. if not pin_verified and controller.has_stored_key: if pin: _verify_pin(ctx, controller, pin, no_prompt=force) elif not force: click.confirm( 'The current management key is stored on the YubiKey' ' and will not be cleared if no PIN is provided. Continue?', abort=True, err=True) if not new_management_key and not protect: if generate: new_management_key = generate_random_management_key() if not protect: click.echo( 'Generated management key: {}'.format( b2a_hex(new_management_key).decode('utf-8'))) elif force: ctx.fail('New management key not given. Please remove the --force ' 'flag, or set the --generate flag or the ' '--new-management-key option.') else: new_management_key = click.prompt( 'Enter your new management key', hide_input=True, confirmation_prompt=True, err=True) if new_management_key and type(new_management_key) is not bytes: try: new_management_key = a2b_hex(new_management_key) except Exception: ctx.fail('New management key has the wrong format.') try: controller.set_mgm_key( new_management_key, touch=touch, store_on_device=protect) except APDUError as e: logger.error('Failed to change management key', exc_info=e) ctx.fail('Changing the management key failed.')
python
def change_management_key( ctx, management_key, pin, new_management_key, touch, protect, generate, force): """ Change the management key. Management functionality is guarded by a 24 byte management key. This key is required for administrative tasks, such as generating key pairs. A random key may be generated and stored on the YubiKey, protected by PIN. """ controller = ctx.obj['controller'] pin_verified = _ensure_authenticated( ctx, controller, pin, management_key, require_pin_and_key=protect, mgm_key_prompt='Enter your current management key ' '[blank to use default key]', no_prompt=force) if new_management_key and generate: ctx.fail('Invalid options: --new-management-key conflicts with ' '--generate') # Touch not supported on NEO. if touch and controller.version < (4, 0, 0): ctx.fail('Require touch not supported on this YubiKey.') # If an old stored key needs to be cleared, the PIN is needed. if not pin_verified and controller.has_stored_key: if pin: _verify_pin(ctx, controller, pin, no_prompt=force) elif not force: click.confirm( 'The current management key is stored on the YubiKey' ' and will not be cleared if no PIN is provided. Continue?', abort=True, err=True) if not new_management_key and not protect: if generate: new_management_key = generate_random_management_key() if not protect: click.echo( 'Generated management key: {}'.format( b2a_hex(new_management_key).decode('utf-8'))) elif force: ctx.fail('New management key not given. Please remove the --force ' 'flag, or set the --generate flag or the ' '--new-management-key option.') else: new_management_key = click.prompt( 'Enter your new management key', hide_input=True, confirmation_prompt=True, err=True) if new_management_key and type(new_management_key) is not bytes: try: new_management_key = a2b_hex(new_management_key) except Exception: ctx.fail('New management key has the wrong format.') try: controller.set_mgm_key( new_management_key, touch=touch, store_on_device=protect) except APDUError as e: logger.error('Failed to change management key', exc_info=e) ctx.fail('Changing the management key failed.')
[ "def", "change_management_key", "(", "ctx", ",", "management_key", ",", "pin", ",", "new_management_key", ",", "touch", ",", "protect", ",", "generate", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "pin_verified", "=", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ",", "require_pin_and_key", "=", "protect", ",", "mgm_key_prompt", "=", "'Enter your current management key '", "'[blank to use default key]'", ",", "no_prompt", "=", "force", ")", "if", "new_management_key", "and", "generate", ":", "ctx", ".", "fail", "(", "'Invalid options: --new-management-key conflicts with '", "'--generate'", ")", "# Touch not supported on NEO.", "if", "touch", "and", "controller", ".", "version", "<", "(", "4", ",", "0", ",", "0", ")", ":", "ctx", ".", "fail", "(", "'Require touch not supported on this YubiKey.'", ")", "# If an old stored key needs to be cleared, the PIN is needed.", "if", "not", "pin_verified", "and", "controller", ".", "has_stored_key", ":", "if", "pin", ":", "_verify_pin", "(", "ctx", ",", "controller", ",", "pin", ",", "no_prompt", "=", "force", ")", "elif", "not", "force", ":", "click", ".", "confirm", "(", "'The current management key is stored on the YubiKey'", "' and will not be cleared if no PIN is provided. Continue?'", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "if", "not", "new_management_key", "and", "not", "protect", ":", "if", "generate", ":", "new_management_key", "=", "generate_random_management_key", "(", ")", "if", "not", "protect", ":", "click", ".", "echo", "(", "'Generated management key: {}'", ".", "format", "(", "b2a_hex", "(", "new_management_key", ")", ".", "decode", "(", "'utf-8'", ")", ")", ")", "elif", "force", ":", "ctx", ".", "fail", "(", "'New management key not given. Please remove the --force '", "'flag, or set the --generate flag or the '", "'--new-management-key option.'", ")", "else", ":", "new_management_key", "=", "click", ".", "prompt", "(", "'Enter your new management key'", ",", "hide_input", "=", "True", ",", "confirmation_prompt", "=", "True", ",", "err", "=", "True", ")", "if", "new_management_key", "and", "type", "(", "new_management_key", ")", "is", "not", "bytes", ":", "try", ":", "new_management_key", "=", "a2b_hex", "(", "new_management_key", ")", "except", "Exception", ":", "ctx", ".", "fail", "(", "'New management key has the wrong format.'", ")", "try", ":", "controller", ".", "set_mgm_key", "(", "new_management_key", ",", "touch", "=", "touch", ",", "store_on_device", "=", "protect", ")", "except", "APDUError", "as", "e", ":", "logger", ".", "error", "(", "'Failed to change management key'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Changing the management key failed.'", ")" ]
Change the management key. Management functionality is guarded by a 24 byte management key. This key is required for administrative tasks, such as generating key pairs. A random key may be generated and stored on the YubiKey, protected by PIN.
[ "Change", "the", "management", "key", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L735-L802
9,012
Yubico/yubikey-manager
ykman/cli/piv.py
unblock_pin
def unblock_pin(ctx, puk, new_pin): """ Unblock the PIN. Reset the PIN using the PUK code. """ controller = ctx.obj['controller'] if not puk: puk = click.prompt( 'Enter PUK', default='', show_default=False, hide_input=True, err=True) if not new_pin: new_pin = click.prompt( 'Enter a new PIN', default='', show_default=False, hide_input=True, err=True) controller.unblock_pin(puk, new_pin)
python
def unblock_pin(ctx, puk, new_pin): """ Unblock the PIN. Reset the PIN using the PUK code. """ controller = ctx.obj['controller'] if not puk: puk = click.prompt( 'Enter PUK', default='', show_default=False, hide_input=True, err=True) if not new_pin: new_pin = click.prompt( 'Enter a new PIN', default='', show_default=False, hide_input=True, err=True) controller.unblock_pin(puk, new_pin)
[ "def", "unblock_pin", "(", "ctx", ",", "puk", ",", "new_pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "puk", ":", "puk", "=", "click", ".", "prompt", "(", "'Enter PUK'", ",", "default", "=", "''", ",", "show_default", "=", "False", ",", "hide_input", "=", "True", ",", "err", "=", "True", ")", "if", "not", "new_pin", ":", "new_pin", "=", "click", ".", "prompt", "(", "'Enter a new PIN'", ",", "default", "=", "''", ",", "show_default", "=", "False", ",", "hide_input", "=", "True", ",", "err", "=", "True", ")", "controller", ".", "unblock_pin", "(", "puk", ",", "new_pin", ")" ]
Unblock the PIN. Reset the PIN using the PUK code.
[ "Unblock", "the", "PIN", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L809-L824
9,013
Yubico/yubikey-manager
ykman/cli/piv.py
read_object
def read_object(ctx, pin, object_id): """ Read arbitrary PIV object. Read PIV object by providing the object id. \b OBJECT-ID Id of PIV object in HEX. """ controller = ctx.obj['controller'] def do_read_object(retry=True): try: click.echo(controller.get_data(object_id)) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail('No data found.') elif e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: _verify_pin(ctx, controller, pin) do_read_object(retry=False) else: raise do_read_object()
python
def read_object(ctx, pin, object_id): """ Read arbitrary PIV object. Read PIV object by providing the object id. \b OBJECT-ID Id of PIV object in HEX. """ controller = ctx.obj['controller'] def do_read_object(retry=True): try: click.echo(controller.get_data(object_id)) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail('No data found.') elif e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: _verify_pin(ctx, controller, pin) do_read_object(retry=False) else: raise do_read_object()
[ "def", "read_object", "(", "ctx", ",", "pin", ",", "object_id", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "def", "do_read_object", "(", "retry", "=", "True", ")", ":", "try", ":", "click", ".", "echo", "(", "controller", ".", "get_data", "(", "object_id", ")", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "ctx", ".", "fail", "(", "'No data found.'", ")", "elif", "e", ".", "sw", "==", "SW", ".", "SECURITY_CONDITION_NOT_SATISFIED", ":", "_verify_pin", "(", "ctx", ",", "controller", ",", "pin", ")", "do_read_object", "(", "retry", "=", "False", ")", "else", ":", "raise", "do_read_object", "(", ")" ]
Read arbitrary PIV object. Read PIV object by providing the object id. \b OBJECT-ID Id of PIV object in HEX.
[ "Read", "arbitrary", "PIV", "object", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L833-L857
9,014
Yubico/yubikey-manager
ykman/cli/piv.py
write_object
def write_object(ctx, pin, management_key, object_id, data): """ Write an arbitrary PIV object. Write a PIV object by providing the object id. Yubico writable PIV objects are available in the range 5f0000 - 5fffff. \b OBJECT-ID Id of PIV object in HEX. DATA File containing the data to be written. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) def do_write_object(retry=True): try: controller.put_data(object_id, data.read()) except APDUError as e: logger.debug('Failed writing object', exc_info=e) if e.sw == SW.INCORRECT_PARAMETERS: ctx.fail('Something went wrong, is the object id valid?') raise do_write_object()
python
def write_object(ctx, pin, management_key, object_id, data): """ Write an arbitrary PIV object. Write a PIV object by providing the object id. Yubico writable PIV objects are available in the range 5f0000 - 5fffff. \b OBJECT-ID Id of PIV object in HEX. DATA File containing the data to be written. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) def do_write_object(retry=True): try: controller.put_data(object_id, data.read()) except APDUError as e: logger.debug('Failed writing object', exc_info=e) if e.sw == SW.INCORRECT_PARAMETERS: ctx.fail('Something went wrong, is the object id valid?') raise do_write_object()
[ "def", "write_object", "(", "ctx", ",", "pin", ",", "management_key", ",", "object_id", ",", "data", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "def", "do_write_object", "(", "retry", "=", "True", ")", ":", "try", ":", "controller", ".", "put_data", "(", "object_id", ",", "data", ".", "read", "(", ")", ")", "except", "APDUError", "as", "e", ":", "logger", ".", "debug", "(", "'Failed writing object'", ",", "exc_info", "=", "e", ")", "if", "e", ".", "sw", "==", "SW", ".", "INCORRECT_PARAMETERS", ":", "ctx", ".", "fail", "(", "'Something went wrong, is the object id valid?'", ")", "raise", "do_write_object", "(", ")" ]
Write an arbitrary PIV object. Write a PIV object by providing the object id. Yubico writable PIV objects are available in the range 5f0000 - 5fffff. \b OBJECT-ID Id of PIV object in HEX. DATA File containing the data to be written. Use '-' to use stdin.
[ "Write", "an", "arbitrary", "PIV", "object", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L869-L894
9,015
Yubico/yubikey-manager
ykman/cli/fido.py
fido
def fido(ctx): """ Manage FIDO applications. Examples: \b Reset the FIDO (FIDO2 and U2F) applications: $ ykman fido reset \b Change the FIDO2 PIN from 123456 to 654321: $ ykman fido set-pin --pin 123456 --new-pin 654321 """ dev = ctx.obj['dev'] if dev.is_fips: try: ctx.obj['controller'] = FipsU2fController(dev.driver) except Exception as e: logger.debug('Failed to load FipsU2fController', exc_info=e) ctx.fail('Failed to load FIDO Application.') else: try: ctx.obj['controller'] = Fido2Controller(dev.driver) except Exception as e: logger.debug('Failed to load Fido2Controller', exc_info=e) ctx.fail('Failed to load FIDO 2 Application.')
python
def fido(ctx): """ Manage FIDO applications. Examples: \b Reset the FIDO (FIDO2 and U2F) applications: $ ykman fido reset \b Change the FIDO2 PIN from 123456 to 654321: $ ykman fido set-pin --pin 123456 --new-pin 654321 """ dev = ctx.obj['dev'] if dev.is_fips: try: ctx.obj['controller'] = FipsU2fController(dev.driver) except Exception as e: logger.debug('Failed to load FipsU2fController', exc_info=e) ctx.fail('Failed to load FIDO Application.') else: try: ctx.obj['controller'] = Fido2Controller(dev.driver) except Exception as e: logger.debug('Failed to load Fido2Controller', exc_info=e) ctx.fail('Failed to load FIDO 2 Application.')
[ "def", "fido", "(", "ctx", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "if", "dev", ".", "is_fips", ":", "try", ":", "ctx", ".", "obj", "[", "'controller'", "]", "=", "FipsU2fController", "(", "dev", ".", "driver", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "'Failed to load FipsU2fController'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to load FIDO Application.'", ")", "else", ":", "try", ":", "ctx", ".", "obj", "[", "'controller'", "]", "=", "Fido2Controller", "(", "dev", ".", "driver", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "'Failed to load Fido2Controller'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to load FIDO 2 Application.'", ")" ]
Manage FIDO applications. Examples: \b Reset the FIDO (FIDO2 and U2F) applications: $ ykman fido reset \b Change the FIDO2 PIN from 123456 to 654321: $ ykman fido set-pin --pin 123456 --new-pin 654321
[ "Manage", "FIDO", "applications", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/fido.py#L51-L78
9,016
Yubico/yubikey-manager
ykman/cli/fido.py
info
def info(ctx): """ Display status of FIDO2 application. """ controller = ctx.obj['controller'] if controller.is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No')) else: if controller.has_pin: try: click.echo( 'PIN is set, with {} tries left.'.format( controller.get_pin_retries())) except CtapError as e: if e.code == CtapError.ERR.PIN_BLOCKED: click.echo('PIN is blocked.') else: click.echo('PIN is not set.')
python
def info(ctx): """ Display status of FIDO2 application. """ controller = ctx.obj['controller'] if controller.is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No')) else: if controller.has_pin: try: click.echo( 'PIN is set, with {} tries left.'.format( controller.get_pin_retries())) except CtapError as e: if e.code == CtapError.ERR.PIN_BLOCKED: click.echo('PIN is blocked.') else: click.echo('PIN is not set.')
[ "def", "info", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "controller", ".", "is_fips", ":", "click", ".", "echo", "(", "'FIPS Approved Mode: {}'", ".", "format", "(", "'Yes'", "if", "controller", ".", "is_in_fips_mode", "else", "'No'", ")", ")", "else", ":", "if", "controller", ".", "has_pin", ":", "try", ":", "click", ".", "echo", "(", "'PIN is set, with {} tries left.'", ".", "format", "(", "controller", ".", "get_pin_retries", "(", ")", ")", ")", "except", "CtapError", "as", "e", ":", "if", "e", ".", "code", "==", "CtapError", ".", "ERR", ".", "PIN_BLOCKED", ":", "click", ".", "echo", "(", "'PIN is blocked.'", ")", "else", ":", "click", ".", "echo", "(", "'PIN is not set.'", ")" ]
Display status of FIDO2 application.
[ "Display", "status", "of", "FIDO2", "application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/fido.py#L83-L102
9,017
Yubico/yubikey-manager
ykman/cli/fido.py
reset
def reset(ctx, force): """ Reset all FIDO applications. This action will wipe all FIDO credentials, including FIDO U2F credentials, on the YubiKey and remove the PIN code. The reset must be triggered immediately after the YubiKey is inserted, and requires a touch on the YubiKey. """ n_keys = len(list(get_descriptors())) if n_keys > 1: ctx.fail('Only one YubiKey can be connected to perform a reset.') if not force: if not click.confirm('WARNING! This will delete all FIDO credentials, ' 'including FIDO U2F credentials, and restore ' 'factory settings. Proceed?', err=True): ctx.abort() def prompt_re_insert_key(): click.echo('Remove and re-insert your YubiKey to perform the reset...') removed = False while True: sleep(0.1) n_keys = len(list(get_descriptors())) if not n_keys: removed = True if removed and n_keys == 1: return def try_reset(controller_type): if not force: prompt_re_insert_key() dev = list(get_descriptors())[0].open_device(TRANSPORT.FIDO) controller = controller_type(dev.driver) controller.reset(touch_callback=prompt_for_touch) else: controller = ctx.obj['controller'] controller.reset(touch_callback=prompt_for_touch) if ctx.obj['dev'].is_fips: if not force: destroy_input = click.prompt( 'WARNING! This is a YubiKey FIPS device. This command will ' 'also overwrite the U2F attestation key; this action cannot be ' 'undone and this YubiKey will no longer be a FIPS compliant ' 'device.\n' 'To proceed, please enter the text "OVERWRITE"', default='', show_default=False, err=True ) if destroy_input != 'OVERWRITE': ctx.fail('Reset aborted by user.') try: try_reset(FipsU2fController) except ApduError as e: if e.code == SW.COMMAND_NOT_ALLOWED: ctx.fail( 'Reset failed. Reset must be triggered within 5 seconds' ' after the YubiKey is inserted.') else: logger.error('Reset failed', exc_info=e) ctx.fail('Reset failed.') except Exception as e: logger.error('Reset failed', exc_info=e) ctx.fail('Reset failed.') else: try: try_reset(Fido2Controller) except CtapError as e: if e.code == CtapError.ERR.ACTION_TIMEOUT: ctx.fail( 'Reset failed. You need to touch your' ' YubiKey to confirm the reset.') elif e.code == CtapError.ERR.NOT_ALLOWED: ctx.fail( 'Reset failed. Reset must be triggered within 5 seconds' ' after the YubiKey is inserted.') else: logger.error(e) ctx.fail('Reset failed.') except Exception as e: logger.error(e) ctx.fail('Reset failed.')
python
def reset(ctx, force): """ Reset all FIDO applications. This action will wipe all FIDO credentials, including FIDO U2F credentials, on the YubiKey and remove the PIN code. The reset must be triggered immediately after the YubiKey is inserted, and requires a touch on the YubiKey. """ n_keys = len(list(get_descriptors())) if n_keys > 1: ctx.fail('Only one YubiKey can be connected to perform a reset.') if not force: if not click.confirm('WARNING! This will delete all FIDO credentials, ' 'including FIDO U2F credentials, and restore ' 'factory settings. Proceed?', err=True): ctx.abort() def prompt_re_insert_key(): click.echo('Remove and re-insert your YubiKey to perform the reset...') removed = False while True: sleep(0.1) n_keys = len(list(get_descriptors())) if not n_keys: removed = True if removed and n_keys == 1: return def try_reset(controller_type): if not force: prompt_re_insert_key() dev = list(get_descriptors())[0].open_device(TRANSPORT.FIDO) controller = controller_type(dev.driver) controller.reset(touch_callback=prompt_for_touch) else: controller = ctx.obj['controller'] controller.reset(touch_callback=prompt_for_touch) if ctx.obj['dev'].is_fips: if not force: destroy_input = click.prompt( 'WARNING! This is a YubiKey FIPS device. This command will ' 'also overwrite the U2F attestation key; this action cannot be ' 'undone and this YubiKey will no longer be a FIPS compliant ' 'device.\n' 'To proceed, please enter the text "OVERWRITE"', default='', show_default=False, err=True ) if destroy_input != 'OVERWRITE': ctx.fail('Reset aborted by user.') try: try_reset(FipsU2fController) except ApduError as e: if e.code == SW.COMMAND_NOT_ALLOWED: ctx.fail( 'Reset failed. Reset must be triggered within 5 seconds' ' after the YubiKey is inserted.') else: logger.error('Reset failed', exc_info=e) ctx.fail('Reset failed.') except Exception as e: logger.error('Reset failed', exc_info=e) ctx.fail('Reset failed.') else: try: try_reset(Fido2Controller) except CtapError as e: if e.code == CtapError.ERR.ACTION_TIMEOUT: ctx.fail( 'Reset failed. You need to touch your' ' YubiKey to confirm the reset.') elif e.code == CtapError.ERR.NOT_ALLOWED: ctx.fail( 'Reset failed. Reset must be triggered within 5 seconds' ' after the YubiKey is inserted.') else: logger.error(e) ctx.fail('Reset failed.') except Exception as e: logger.error(e) ctx.fail('Reset failed.')
[ "def", "reset", "(", "ctx", ",", "force", ")", ":", "n_keys", "=", "len", "(", "list", "(", "get_descriptors", "(", ")", ")", ")", "if", "n_keys", ">", "1", ":", "ctx", ".", "fail", "(", "'Only one YubiKey can be connected to perform a reset.'", ")", "if", "not", "force", ":", "if", "not", "click", ".", "confirm", "(", "'WARNING! This will delete all FIDO credentials, '", "'including FIDO U2F credentials, and restore '", "'factory settings. Proceed?'", ",", "err", "=", "True", ")", ":", "ctx", ".", "abort", "(", ")", "def", "prompt_re_insert_key", "(", ")", ":", "click", ".", "echo", "(", "'Remove and re-insert your YubiKey to perform the reset...'", ")", "removed", "=", "False", "while", "True", ":", "sleep", "(", "0.1", ")", "n_keys", "=", "len", "(", "list", "(", "get_descriptors", "(", ")", ")", ")", "if", "not", "n_keys", ":", "removed", "=", "True", "if", "removed", "and", "n_keys", "==", "1", ":", "return", "def", "try_reset", "(", "controller_type", ")", ":", "if", "not", "force", ":", "prompt_re_insert_key", "(", ")", "dev", "=", "list", "(", "get_descriptors", "(", ")", ")", "[", "0", "]", ".", "open_device", "(", "TRANSPORT", ".", "FIDO", ")", "controller", "=", "controller_type", "(", "dev", ".", "driver", ")", "controller", ".", "reset", "(", "touch_callback", "=", "prompt_for_touch", ")", "else", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "controller", ".", "reset", "(", "touch_callback", "=", "prompt_for_touch", ")", "if", "ctx", ".", "obj", "[", "'dev'", "]", ".", "is_fips", ":", "if", "not", "force", ":", "destroy_input", "=", "click", ".", "prompt", "(", "'WARNING! This is a YubiKey FIPS device. This command will '", "'also overwrite the U2F attestation key; this action cannot be '", "'undone and this YubiKey will no longer be a FIPS compliant '", "'device.\\n'", "'To proceed, please enter the text \"OVERWRITE\"'", ",", "default", "=", "''", ",", "show_default", "=", "False", ",", "err", "=", "True", ")", "if", "destroy_input", "!=", "'OVERWRITE'", ":", "ctx", ".", "fail", "(", "'Reset aborted by user.'", ")", "try", ":", "try_reset", "(", "FipsU2fController", ")", "except", "ApduError", "as", "e", ":", "if", "e", ".", "code", "==", "SW", ".", "COMMAND_NOT_ALLOWED", ":", "ctx", ".", "fail", "(", "'Reset failed. Reset must be triggered within 5 seconds'", "' after the YubiKey is inserted.'", ")", "else", ":", "logger", ".", "error", "(", "'Reset failed'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Reset failed.'", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Reset failed'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Reset failed.'", ")", "else", ":", "try", ":", "try_reset", "(", "Fido2Controller", ")", "except", "CtapError", "as", "e", ":", "if", "e", ".", "code", "==", "CtapError", ".", "ERR", ".", "ACTION_TIMEOUT", ":", "ctx", ".", "fail", "(", "'Reset failed. You need to touch your'", "' YubiKey to confirm the reset.'", ")", "elif", "e", ".", "code", "==", "CtapError", ".", "ERR", ".", "NOT_ALLOWED", ":", "ctx", ".", "fail", "(", "'Reset failed. Reset must be triggered within 5 seconds'", "' after the YubiKey is inserted.'", ")", "else", ":", "logger", ".", "error", "(", "e", ")", "ctx", ".", "fail", "(", "'Reset failed.'", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "e", ")", "ctx", ".", "fail", "(", "'Reset failed.'", ")" ]
Reset all FIDO applications. This action will wipe all FIDO credentials, including FIDO U2F credentials, on the YubiKey and remove the PIN code. The reset must be triggered immediately after the YubiKey is inserted, and requires a touch on the YubiKey.
[ "Reset", "all", "FIDO", "applications", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/fido.py#L210-L302
9,018
Yubico/yubikey-manager
ykman/cli/fido.py
unlock
def unlock(ctx, pin): """ Verify U2F PIN for YubiKey FIPS. Unlock the YubiKey FIPS and allow U2F registration. """ controller = ctx.obj['controller'] if not controller.is_fips: ctx.fail('This is not a YubiKey FIPS, and therefore' ' does not support a U2F PIN.') if pin is None: pin = _prompt_current_pin('Enter your PIN') _fail_if_not_valid_pin(ctx, pin, True) try: controller.verify_pin(pin) except ApduError as e: if e.code == SW.VERIFY_FAIL_NO_RETRY: ctx.fail('Wrong PIN.') if e.code == SW.AUTH_METHOD_BLOCKED: ctx.fail('PIN is blocked.') if e.code == SW.COMMAND_NOT_ALLOWED: ctx.fail('PIN is not set.') logger.error('PIN verification failed', exc_info=e) ctx.fail('PIN verification failed.')
python
def unlock(ctx, pin): """ Verify U2F PIN for YubiKey FIPS. Unlock the YubiKey FIPS and allow U2F registration. """ controller = ctx.obj['controller'] if not controller.is_fips: ctx.fail('This is not a YubiKey FIPS, and therefore' ' does not support a U2F PIN.') if pin is None: pin = _prompt_current_pin('Enter your PIN') _fail_if_not_valid_pin(ctx, pin, True) try: controller.verify_pin(pin) except ApduError as e: if e.code == SW.VERIFY_FAIL_NO_RETRY: ctx.fail('Wrong PIN.') if e.code == SW.AUTH_METHOD_BLOCKED: ctx.fail('PIN is blocked.') if e.code == SW.COMMAND_NOT_ALLOWED: ctx.fail('PIN is not set.') logger.error('PIN verification failed', exc_info=e) ctx.fail('PIN verification failed.')
[ "def", "unlock", "(", "ctx", ",", "pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "controller", ".", "is_fips", ":", "ctx", ".", "fail", "(", "'This is not a YubiKey FIPS, and therefore'", "' does not support a U2F PIN.'", ")", "if", "pin", "is", "None", ":", "pin", "=", "_prompt_current_pin", "(", "'Enter your PIN'", ")", "_fail_if_not_valid_pin", "(", "ctx", ",", "pin", ",", "True", ")", "try", ":", "controller", ".", "verify_pin", "(", "pin", ")", "except", "ApduError", "as", "e", ":", "if", "e", ".", "code", "==", "SW", ".", "VERIFY_FAIL_NO_RETRY", ":", "ctx", ".", "fail", "(", "'Wrong PIN.'", ")", "if", "e", ".", "code", "==", "SW", ".", "AUTH_METHOD_BLOCKED", ":", "ctx", ".", "fail", "(", "'PIN is blocked.'", ")", "if", "e", ".", "code", "==", "SW", ".", "COMMAND_NOT_ALLOWED", ":", "ctx", ".", "fail", "(", "'PIN is not set.'", ")", "logger", ".", "error", "(", "'PIN verification failed'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'PIN verification failed.'", ")" ]
Verify U2F PIN for YubiKey FIPS. Unlock the YubiKey FIPS and allow U2F registration.
[ "Verify", "U2F", "PIN", "for", "YubiKey", "FIPS", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/fido.py#L308-L335
9,019
Yubico/yubikey-manager
ykman/piv.py
PivController.get_pin_tries
def get_pin_tries(self): """ Returns the number of PIN retries left, 0 PIN authentication blocked. Note that 15 is the highest value that will be returned even if remaining tries is higher. """ # Verify without PIN gives number of tries left. _, sw = self.send_cmd(INS.VERIFY, 0, PIN, check=None) return tries_left(sw, self.version)
python
def get_pin_tries(self): """ Returns the number of PIN retries left, 0 PIN authentication blocked. Note that 15 is the highest value that will be returned even if remaining tries is higher. """ # Verify without PIN gives number of tries left. _, sw = self.send_cmd(INS.VERIFY, 0, PIN, check=None) return tries_left(sw, self.version)
[ "def", "get_pin_tries", "(", "self", ")", ":", "# Verify without PIN gives number of tries left.", "_", ",", "sw", "=", "self", ".", "send_cmd", "(", "INS", ".", "VERIFY", ",", "0", ",", "PIN", ",", "check", "=", "None", ")", "return", "tries_left", "(", "sw", ",", "self", ".", "version", ")" ]
Returns the number of PIN retries left, 0 PIN authentication blocked. Note that 15 is the highest value that will be returned even if remaining tries is higher.
[ "Returns", "the", "number", "of", "PIN", "retries", "left", "0", "PIN", "authentication", "blocked", ".", "Note", "that", "15", "is", "the", "highest", "value", "that", "will", "be", "returned", "even", "if", "remaining", "tries", "is", "higher", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/piv.py#L778-L786
9,020
Yubico/yubikey-manager
ykman/cli/__main__.py
cli
def cli(ctx, device, log_level, log_file, reader): """ Configure your YubiKey via the command line. Examples: \b List connected YubiKeys, only output serial number: $ ykman list --serials \b Show information about YubiKey with serial number 0123456: $ ykman --device 0123456 info """ ctx.obj = YkmanContextObject() if log_level: ykman.logging_setup.setup(log_level, log_file=log_file) if reader and device: ctx.fail('--reader and --device options can\'t be combined.') subcmd = next(c for c in COMMANDS if c.name == ctx.invoked_subcommand) if subcmd == list_keys: if reader: ctx.fail('--reader and list command can\'t be combined.') return transports = getattr(subcmd, 'transports', TRANSPORT.usb_transports()) if transports: def resolve_device(): if device is not None: dev = _run_cmd_for_serial(ctx, subcmd.name, transports, device) else: dev = _run_cmd_for_single(ctx, subcmd.name, transports, reader) ctx.call_on_close(dev.close) return dev ctx.obj.add_resolver('dev', resolve_device)
python
def cli(ctx, device, log_level, log_file, reader): """ Configure your YubiKey via the command line. Examples: \b List connected YubiKeys, only output serial number: $ ykman list --serials \b Show information about YubiKey with serial number 0123456: $ ykman --device 0123456 info """ ctx.obj = YkmanContextObject() if log_level: ykman.logging_setup.setup(log_level, log_file=log_file) if reader and device: ctx.fail('--reader and --device options can\'t be combined.') subcmd = next(c for c in COMMANDS if c.name == ctx.invoked_subcommand) if subcmd == list_keys: if reader: ctx.fail('--reader and list command can\'t be combined.') return transports = getattr(subcmd, 'transports', TRANSPORT.usb_transports()) if transports: def resolve_device(): if device is not None: dev = _run_cmd_for_serial(ctx, subcmd.name, transports, device) else: dev = _run_cmd_for_single(ctx, subcmd.name, transports, reader) ctx.call_on_close(dev.close) return dev ctx.obj.add_resolver('dev', resolve_device)
[ "def", "cli", "(", "ctx", ",", "device", ",", "log_level", ",", "log_file", ",", "reader", ")", ":", "ctx", ".", "obj", "=", "YkmanContextObject", "(", ")", "if", "log_level", ":", "ykman", ".", "logging_setup", ".", "setup", "(", "log_level", ",", "log_file", "=", "log_file", ")", "if", "reader", "and", "device", ":", "ctx", ".", "fail", "(", "'--reader and --device options can\\'t be combined.'", ")", "subcmd", "=", "next", "(", "c", "for", "c", "in", "COMMANDS", "if", "c", ".", "name", "==", "ctx", ".", "invoked_subcommand", ")", "if", "subcmd", "==", "list_keys", ":", "if", "reader", ":", "ctx", ".", "fail", "(", "'--reader and list command can\\'t be combined.'", ")", "return", "transports", "=", "getattr", "(", "subcmd", ",", "'transports'", ",", "TRANSPORT", ".", "usb_transports", "(", ")", ")", "if", "transports", ":", "def", "resolve_device", "(", ")", ":", "if", "device", "is", "not", "None", ":", "dev", "=", "_run_cmd_for_serial", "(", "ctx", ",", "subcmd", ".", "name", ",", "transports", ",", "device", ")", "else", ":", "dev", "=", "_run_cmd_for_single", "(", "ctx", ",", "subcmd", ".", "name", ",", "transports", ",", "reader", ")", "ctx", ".", "call_on_close", "(", "dev", ".", "close", ")", "return", "dev", "ctx", ".", "obj", ".", "add_resolver", "(", "'dev'", ",", "resolve_device", ")" ]
Configure your YubiKey via the command line. Examples: \b List connected YubiKeys, only output serial number: $ ykman list --serials \b Show information about YubiKey with serial number 0123456: $ ykman --device 0123456 info
[ "Configure", "your", "YubiKey", "via", "the", "command", "line", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/__main__.py#L154-L191
9,021
Yubico/yubikey-manager
ykman/cli/__main__.py
list_keys
def list_keys(ctx, serials, readers): """ List connected YubiKeys. """ if readers: for reader in list_readers(): click.echo(reader.name) ctx.exit() all_descriptors = get_descriptors() descriptors = [d for d in all_descriptors if d.key_type != YUBIKEY.SKY] skys = len(all_descriptors) - len(descriptors) handled_serials = set() for dev in list_devices(): handled = False if skys > 0 and dev.key_type == YUBIKEY.SKY: skys -= 1 serial = None handled = True else: serial = dev.serial if serial not in handled_serials: handled_serials.add(serial) matches = [d for d in descriptors if (d.key_type, d.mode) == (dev.driver.key_type, dev.driver.mode)] if len(matches) > 0: d = matches[0] descriptors.remove(d) handled = True if handled: if serials: if serial: click.echo(serial) else: click.echo('{} [{}]{}'.format( dev.device_name, dev.mode, ' Serial: {}'.format(serial) if serial else '') ) dev.close() if not descriptors and not skys: break
python
def list_keys(ctx, serials, readers): """ List connected YubiKeys. """ if readers: for reader in list_readers(): click.echo(reader.name) ctx.exit() all_descriptors = get_descriptors() descriptors = [d for d in all_descriptors if d.key_type != YUBIKEY.SKY] skys = len(all_descriptors) - len(descriptors) handled_serials = set() for dev in list_devices(): handled = False if skys > 0 and dev.key_type == YUBIKEY.SKY: skys -= 1 serial = None handled = True else: serial = dev.serial if serial not in handled_serials: handled_serials.add(serial) matches = [d for d in descriptors if (d.key_type, d.mode) == (dev.driver.key_type, dev.driver.mode)] if len(matches) > 0: d = matches[0] descriptors.remove(d) handled = True if handled: if serials: if serial: click.echo(serial) else: click.echo('{} [{}]{}'.format( dev.device_name, dev.mode, ' Serial: {}'.format(serial) if serial else '') ) dev.close() if not descriptors and not skys: break
[ "def", "list_keys", "(", "ctx", ",", "serials", ",", "readers", ")", ":", "if", "readers", ":", "for", "reader", "in", "list_readers", "(", ")", ":", "click", ".", "echo", "(", "reader", ".", "name", ")", "ctx", ".", "exit", "(", ")", "all_descriptors", "=", "get_descriptors", "(", ")", "descriptors", "=", "[", "d", "for", "d", "in", "all_descriptors", "if", "d", ".", "key_type", "!=", "YUBIKEY", ".", "SKY", "]", "skys", "=", "len", "(", "all_descriptors", ")", "-", "len", "(", "descriptors", ")", "handled_serials", "=", "set", "(", ")", "for", "dev", "in", "list_devices", "(", ")", ":", "handled", "=", "False", "if", "skys", ">", "0", "and", "dev", ".", "key_type", "==", "YUBIKEY", ".", "SKY", ":", "skys", "-=", "1", "serial", "=", "None", "handled", "=", "True", "else", ":", "serial", "=", "dev", ".", "serial", "if", "serial", "not", "in", "handled_serials", ":", "handled_serials", ".", "add", "(", "serial", ")", "matches", "=", "[", "d", "for", "d", "in", "descriptors", "if", "(", "d", ".", "key_type", ",", "d", ".", "mode", ")", "==", "(", "dev", ".", "driver", ".", "key_type", ",", "dev", ".", "driver", ".", "mode", ")", "]", "if", "len", "(", "matches", ")", ">", "0", ":", "d", "=", "matches", "[", "0", "]", "descriptors", ".", "remove", "(", "d", ")", "handled", "=", "True", "if", "handled", ":", "if", "serials", ":", "if", "serial", ":", "click", ".", "echo", "(", "serial", ")", "else", ":", "click", ".", "echo", "(", "'{} [{}]{}'", ".", "format", "(", "dev", ".", "device_name", ",", "dev", ".", "mode", ",", "' Serial: {}'", ".", "format", "(", "serial", ")", "if", "serial", "else", "''", ")", ")", "dev", ".", "close", "(", ")", "if", "not", "descriptors", "and", "not", "skys", ":", "break" ]
List connected YubiKeys.
[ "List", "connected", "YubiKeys", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/__main__.py#L200-L241
9,022
Yubico/yubikey-manager
ykman/cli/otp.py
otp
def otp(ctx, access_code): """ Manage OTP Application. The YubiKey provides two keyboard-based slots which can each be configured with a credential. Several credential types are supported. A slot configuration may be write-protected with an access code. This prevents the configuration to be overwritten without the access code provided. Mode switching the YubiKey is not possible when a slot is configured with an access code. Examples: \b Swap the configurations between the two slots: $ ykman otp swap \b Program a random challenge-response credential to slot 2: $ ykman otp chalresp --generate 2 \b Program a Yubico OTP credential to slot 2, using the serial as public id: $ ykman otp yubiotp 1 --serial-public-id \b Program a random 38 characters long static password to slot 2: $ ykman otp static --generate 2 --length 38 """ ctx.obj['controller'] = OtpController(ctx.obj['dev'].driver) if access_code is not None: if access_code == '': access_code = click.prompt( 'Enter access code', show_default=False, err=True) try: access_code = parse_access_code_hex(access_code) except Exception as e: ctx.fail('Failed to parse access code: ' + str(e)) ctx.obj['controller'].access_code = access_code
python
def otp(ctx, access_code): """ Manage OTP Application. The YubiKey provides two keyboard-based slots which can each be configured with a credential. Several credential types are supported. A slot configuration may be write-protected with an access code. This prevents the configuration to be overwritten without the access code provided. Mode switching the YubiKey is not possible when a slot is configured with an access code. Examples: \b Swap the configurations between the two slots: $ ykman otp swap \b Program a random challenge-response credential to slot 2: $ ykman otp chalresp --generate 2 \b Program a Yubico OTP credential to slot 2, using the serial as public id: $ ykman otp yubiotp 1 --serial-public-id \b Program a random 38 characters long static password to slot 2: $ ykman otp static --generate 2 --length 38 """ ctx.obj['controller'] = OtpController(ctx.obj['dev'].driver) if access_code is not None: if access_code == '': access_code = click.prompt( 'Enter access code', show_default=False, err=True) try: access_code = parse_access_code_hex(access_code) except Exception as e: ctx.fail('Failed to parse access code: ' + str(e)) ctx.obj['controller'].access_code = access_code
[ "def", "otp", "(", "ctx", ",", "access_code", ")", ":", "ctx", ".", "obj", "[", "'controller'", "]", "=", "OtpController", "(", "ctx", ".", "obj", "[", "'dev'", "]", ".", "driver", ")", "if", "access_code", "is", "not", "None", ":", "if", "access_code", "==", "''", ":", "access_code", "=", "click", ".", "prompt", "(", "'Enter access code'", ",", "show_default", "=", "False", ",", "err", "=", "True", ")", "try", ":", "access_code", "=", "parse_access_code_hex", "(", "access_code", ")", "except", "Exception", "as", "e", ":", "ctx", ".", "fail", "(", "'Failed to parse access code: '", "+", "str", "(", "e", ")", ")", "ctx", ".", "obj", "[", "'controller'", "]", ".", "access_code", "=", "access_code" ]
Manage OTP Application. The YubiKey provides two keyboard-based slots which can each be configured with a credential. Several credential types are supported. A slot configuration may be write-protected with an access code. This prevents the configuration to be overwritten without the access code provided. Mode switching the YubiKey is not possible when a slot is configured with an access code. Examples: \b Swap the configurations between the two slots: $ ykman otp swap \b Program a random challenge-response credential to slot 2: $ ykman otp chalresp --generate 2 \b Program a Yubico OTP credential to slot 2, using the serial as public id: $ ykman otp yubiotp 1 --serial-public-id \b Program a random 38 characters long static password to slot 2: $ ykman otp static --generate 2 --length 38
[ "Manage", "OTP", "Application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L98-L140
9,023
Yubico/yubikey-manager
ykman/cli/otp.py
info
def info(ctx): """ Display status of YubiKey Slots. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] slot1, slot2 = controller.slot_status click.echo('Slot 1: {}'.format(slot1 and 'programmed' or 'empty')) click.echo('Slot 2: {}'.format(slot2 and 'programmed' or 'empty')) if dev.is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No'))
python
def info(ctx): """ Display status of YubiKey Slots. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] slot1, slot2 = controller.slot_status click.echo('Slot 1: {}'.format(slot1 and 'programmed' or 'empty')) click.echo('Slot 2: {}'.format(slot2 and 'programmed' or 'empty')) if dev.is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No'))
[ "def", "info", "(", "ctx", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "slot1", ",", "slot2", "=", "controller", ".", "slot_status", "click", ".", "echo", "(", "'Slot 1: {}'", ".", "format", "(", "slot1", "and", "'programmed'", "or", "'empty'", ")", ")", "click", ".", "echo", "(", "'Slot 2: {}'", ".", "format", "(", "slot2", "and", "'programmed'", "or", "'empty'", ")", ")", "if", "dev", ".", "is_fips", ":", "click", ".", "echo", "(", "'FIPS Approved Mode: {}'", ".", "format", "(", "'Yes'", "if", "controller", ".", "is_in_fips_mode", "else", "'No'", ")", ")" ]
Display status of YubiKey Slots.
[ "Display", "status", "of", "YubiKey", "Slots", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L145-L158
9,024
Yubico/yubikey-manager
ykman/cli/otp.py
swap
def swap(ctx): """ Swaps the two slot configurations. """ controller = ctx.obj['controller'] click.echo('Swapping slots...') try: controller.swap_slots() except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def swap(ctx): """ Swaps the two slot configurations. """ controller = ctx.obj['controller'] click.echo('Swapping slots...') try: controller.swap_slots() except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "swap", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "click", ".", "echo", "(", "'Swapping slots...'", ")", "try", ":", "controller", ".", "swap_slots", "(", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Swaps the two slot configurations.
[ "Swaps", "the", "two", "slot", "configurations", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L165-L174
9,025
Yubico/yubikey-manager
ykman/cli/otp.py
ndef
def ndef(ctx, slot, prefix): """ Select slot configuration to use for NDEF. The default prefix will be used if no prefix is specified. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] if not dev.config.nfc_supported: ctx.fail('NFC interface not available.') if not controller.slot_status[slot - 1]: ctx.fail('Slot {} is empty.'.format(slot)) try: if prefix: controller.configure_ndef_slot(slot, prefix) else: controller.configure_ndef_slot(slot) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def ndef(ctx, slot, prefix): """ Select slot configuration to use for NDEF. The default prefix will be used if no prefix is specified. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] if not dev.config.nfc_supported: ctx.fail('NFC interface not available.') if not controller.slot_status[slot - 1]: ctx.fail('Slot {} is empty.'.format(slot)) try: if prefix: controller.configure_ndef_slot(slot, prefix) else: controller.configure_ndef_slot(slot) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "ndef", "(", "ctx", ",", "slot", ",", "prefix", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "dev", ".", "config", ".", "nfc_supported", ":", "ctx", ".", "fail", "(", "'NFC interface not available.'", ")", "if", "not", "controller", ".", "slot_status", "[", "slot", "-", "1", "]", ":", "ctx", ".", "fail", "(", "'Slot {} is empty.'", ".", "format", "(", "slot", ")", ")", "try", ":", "if", "prefix", ":", "controller", ".", "configure_ndef_slot", "(", "slot", ",", "prefix", ")", "else", ":", "controller", ".", "configure_ndef_slot", "(", "slot", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Select slot configuration to use for NDEF. The default prefix will be used if no prefix is specified.
[ "Select", "slot", "configuration", "to", "use", "for", "NDEF", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L182-L202
9,026
Yubico/yubikey-manager
ykman/cli/otp.py
delete
def delete(ctx, slot, force): """ Deletes the configuration of a slot. """ controller = ctx.obj['controller'] if not force and not controller.slot_status[slot - 1]: ctx.fail('Not possible to delete an empty slot.') force or click.confirm( 'Do you really want to delete' ' the configuration of slot {}?'.format(slot), abort=True, err=True) click.echo('Deleting the configuration of slot {}...'.format(slot)) try: controller.zap_slot(slot) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def delete(ctx, slot, force): """ Deletes the configuration of a slot. """ controller = ctx.obj['controller'] if not force and not controller.slot_status[slot - 1]: ctx.fail('Not possible to delete an empty slot.') force or click.confirm( 'Do you really want to delete' ' the configuration of slot {}?'.format(slot), abort=True, err=True) click.echo('Deleting the configuration of slot {}...'.format(slot)) try: controller.zap_slot(slot) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "delete", "(", "ctx", ",", "slot", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "force", "and", "not", "controller", ".", "slot_status", "[", "slot", "-", "1", "]", ":", "ctx", ".", "fail", "(", "'Not possible to delete an empty slot.'", ")", "force", "or", "click", ".", "confirm", "(", "'Do you really want to delete'", "' the configuration of slot {}?'", ".", "format", "(", "slot", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "click", ".", "echo", "(", "'Deleting the configuration of slot {}...'", ".", "format", "(", "slot", ")", ")", "try", ":", "controller", ".", "zap_slot", "(", "slot", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Deletes the configuration of a slot.
[ "Deletes", "the", "configuration", "of", "a", "slot", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L209-L223
9,027
Yubico/yubikey-manager
ykman/cli/otp.py
yubiotp
def yubiotp(ctx, slot, public_id, private_id, key, no_enter, force, serial_public_id, generate_private_id, generate_key): """ Program a Yubico OTP credential. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] if public_id and serial_public_id: ctx.fail('Invalid options: --public-id conflicts with ' '--serial-public-id.') if private_id and generate_private_id: ctx.fail('Invalid options: --private-id conflicts with ' '--generate-public-id.') if key and generate_key: ctx.fail('Invalid options: --key conflicts with --generate-key.') if not public_id: if serial_public_id: if dev.serial is None: ctx.fail('Serial number not set, public ID must be provided') public_id = modhex_encode( b'\xff\x00' + struct.pack(b'>I', dev.serial)) click.echo( 'Using YubiKey serial as public ID: {}'.format(public_id)) elif force: ctx.fail( 'Public ID not given. Please remove the --force flag, or ' 'add the --serial-public-id flag or --public-id option.') else: public_id = click.prompt('Enter public ID', err=True) try: public_id = modhex_decode(public_id) except KeyError: ctx.fail('Invalid public ID, must be modhex.') if not private_id: if generate_private_id: private_id = os.urandom(6) click.echo( 'Using a randomly generated private ID: {}'.format( b2a_hex(private_id).decode('ascii'))) elif force: ctx.fail( 'Private ID not given. Please remove the --force flag, or ' 'add the --generate-private-id flag or --private-id option.') else: private_id = click.prompt('Enter private ID', err=True) private_id = a2b_hex(private_id) if not key: if generate_key: key = os.urandom(16) click.echo( 'Using a randomly generated secret key: {}'.format( b2a_hex(key).decode('ascii'))) elif force: ctx.fail('Secret key not given. Please remove the --force flag, or ' 'add the --generate-key flag or --key option.') else: key = click.prompt('Enter secret key', err=True) key = a2b_hex(key) force or click.confirm('Program an OTP credential in slot {}?'.format(slot), abort=True, err=True) try: controller.program_otp(slot, key, public_id, private_id, not no_enter) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def yubiotp(ctx, slot, public_id, private_id, key, no_enter, force, serial_public_id, generate_private_id, generate_key): """ Program a Yubico OTP credential. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] if public_id and serial_public_id: ctx.fail('Invalid options: --public-id conflicts with ' '--serial-public-id.') if private_id and generate_private_id: ctx.fail('Invalid options: --private-id conflicts with ' '--generate-public-id.') if key and generate_key: ctx.fail('Invalid options: --key conflicts with --generate-key.') if not public_id: if serial_public_id: if dev.serial is None: ctx.fail('Serial number not set, public ID must be provided') public_id = modhex_encode( b'\xff\x00' + struct.pack(b'>I', dev.serial)) click.echo( 'Using YubiKey serial as public ID: {}'.format(public_id)) elif force: ctx.fail( 'Public ID not given. Please remove the --force flag, or ' 'add the --serial-public-id flag or --public-id option.') else: public_id = click.prompt('Enter public ID', err=True) try: public_id = modhex_decode(public_id) except KeyError: ctx.fail('Invalid public ID, must be modhex.') if not private_id: if generate_private_id: private_id = os.urandom(6) click.echo( 'Using a randomly generated private ID: {}'.format( b2a_hex(private_id).decode('ascii'))) elif force: ctx.fail( 'Private ID not given. Please remove the --force flag, or ' 'add the --generate-private-id flag or --private-id option.') else: private_id = click.prompt('Enter private ID', err=True) private_id = a2b_hex(private_id) if not key: if generate_key: key = os.urandom(16) click.echo( 'Using a randomly generated secret key: {}'.format( b2a_hex(key).decode('ascii'))) elif force: ctx.fail('Secret key not given. Please remove the --force flag, or ' 'add the --generate-key flag or --key option.') else: key = click.prompt('Enter secret key', err=True) key = a2b_hex(key) force or click.confirm('Program an OTP credential in slot {}?'.format(slot), abort=True, err=True) try: controller.program_otp(slot, key, public_id, private_id, not no_enter) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "yubiotp", "(", "ctx", ",", "slot", ",", "public_id", ",", "private_id", ",", "key", ",", "no_enter", ",", "force", ",", "serial_public_id", ",", "generate_private_id", ",", "generate_key", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "public_id", "and", "serial_public_id", ":", "ctx", ".", "fail", "(", "'Invalid options: --public-id conflicts with '", "'--serial-public-id.'", ")", "if", "private_id", "and", "generate_private_id", ":", "ctx", ".", "fail", "(", "'Invalid options: --private-id conflicts with '", "'--generate-public-id.'", ")", "if", "key", "and", "generate_key", ":", "ctx", ".", "fail", "(", "'Invalid options: --key conflicts with --generate-key.'", ")", "if", "not", "public_id", ":", "if", "serial_public_id", ":", "if", "dev", ".", "serial", "is", "None", ":", "ctx", ".", "fail", "(", "'Serial number not set, public ID must be provided'", ")", "public_id", "=", "modhex_encode", "(", "b'\\xff\\x00'", "+", "struct", ".", "pack", "(", "b'>I'", ",", "dev", ".", "serial", ")", ")", "click", ".", "echo", "(", "'Using YubiKey serial as public ID: {}'", ".", "format", "(", "public_id", ")", ")", "elif", "force", ":", "ctx", ".", "fail", "(", "'Public ID not given. Please remove the --force flag, or '", "'add the --serial-public-id flag or --public-id option.'", ")", "else", ":", "public_id", "=", "click", ".", "prompt", "(", "'Enter public ID'", ",", "err", "=", "True", ")", "try", ":", "public_id", "=", "modhex_decode", "(", "public_id", ")", "except", "KeyError", ":", "ctx", ".", "fail", "(", "'Invalid public ID, must be modhex.'", ")", "if", "not", "private_id", ":", "if", "generate_private_id", ":", "private_id", "=", "os", ".", "urandom", "(", "6", ")", "click", ".", "echo", "(", "'Using a randomly generated private ID: {}'", ".", "format", "(", "b2a_hex", "(", "private_id", ")", ".", "decode", "(", "'ascii'", ")", ")", ")", "elif", "force", ":", "ctx", ".", "fail", "(", "'Private ID not given. Please remove the --force flag, or '", "'add the --generate-private-id flag or --private-id option.'", ")", "else", ":", "private_id", "=", "click", ".", "prompt", "(", "'Enter private ID'", ",", "err", "=", "True", ")", "private_id", "=", "a2b_hex", "(", "private_id", ")", "if", "not", "key", ":", "if", "generate_key", ":", "key", "=", "os", ".", "urandom", "(", "16", ")", "click", ".", "echo", "(", "'Using a randomly generated secret key: {}'", ".", "format", "(", "b2a_hex", "(", "key", ")", ".", "decode", "(", "'ascii'", ")", ")", ")", "elif", "force", ":", "ctx", ".", "fail", "(", "'Secret key not given. Please remove the --force flag, or '", "'add the --generate-key flag or --key option.'", ")", "else", ":", "key", "=", "click", ".", "prompt", "(", "'Enter secret key'", ",", "err", "=", "True", ")", "key", "=", "a2b_hex", "(", "key", ")", "force", "or", "click", ".", "confirm", "(", "'Program an OTP credential in slot {}?'", ".", "format", "(", "slot", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "try", ":", "controller", ".", "program_otp", "(", "slot", ",", "key", ",", "public_id", ",", "private_id", ",", "not", "no_enter", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Program a Yubico OTP credential.
[ "Program", "a", "Yubico", "OTP", "credential", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L247-L321
9,028
Yubico/yubikey-manager
ykman/cli/otp.py
static
def static( ctx, slot, password, generate, length, keyboard_layout, no_enter, force): """ Configure a static password. To avoid problems with different keyboard layouts, the following characters are allowed by default: cbdefghijklnrtuv Use the --keyboard-layout option to allow more characters based on preferred keyboard layout. """ controller = ctx.obj['controller'] keyboard_layout = KEYBOARD_LAYOUT[keyboard_layout] if password and len(password) > 38: ctx.fail('Password too long (maximum length is 38 characters).') if generate and not length: ctx.fail('Provide a length for the generated password.') if not password and not generate: password = click.prompt('Enter a static password', err=True) elif not password and generate: password = generate_static_pw(length, keyboard_layout) if not force: _confirm_slot_overwrite(controller, slot) try: controller.program_static( slot, password, not no_enter, keyboard_layout=keyboard_layout) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def static( ctx, slot, password, generate, length, keyboard_layout, no_enter, force): """ Configure a static password. To avoid problems with different keyboard layouts, the following characters are allowed by default: cbdefghijklnrtuv Use the --keyboard-layout option to allow more characters based on preferred keyboard layout. """ controller = ctx.obj['controller'] keyboard_layout = KEYBOARD_LAYOUT[keyboard_layout] if password and len(password) > 38: ctx.fail('Password too long (maximum length is 38 characters).') if generate and not length: ctx.fail('Provide a length for the generated password.') if not password and not generate: password = click.prompt('Enter a static password', err=True) elif not password and generate: password = generate_static_pw(length, keyboard_layout) if not force: _confirm_slot_overwrite(controller, slot) try: controller.program_static( slot, password, not no_enter, keyboard_layout=keyboard_layout) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "static", "(", "ctx", ",", "slot", ",", "password", ",", "generate", ",", "length", ",", "keyboard_layout", ",", "no_enter", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "keyboard_layout", "=", "KEYBOARD_LAYOUT", "[", "keyboard_layout", "]", "if", "password", "and", "len", "(", "password", ")", ">", "38", ":", "ctx", ".", "fail", "(", "'Password too long (maximum length is 38 characters).'", ")", "if", "generate", "and", "not", "length", ":", "ctx", ".", "fail", "(", "'Provide a length for the generated password.'", ")", "if", "not", "password", "and", "not", "generate", ":", "password", "=", "click", ".", "prompt", "(", "'Enter a static password'", ",", "err", "=", "True", ")", "elif", "not", "password", "and", "generate", ":", "password", "=", "generate_static_pw", "(", "length", ",", "keyboard_layout", ")", "if", "not", "force", ":", "_confirm_slot_overwrite", "(", "controller", ",", "slot", ")", "try", ":", "controller", ".", "program_static", "(", "slot", ",", "password", ",", "not", "no_enter", ",", "keyboard_layout", "=", "keyboard_layout", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Configure a static password. To avoid problems with different keyboard layouts, the following characters are allowed by default: cbdefghijklnrtuv Use the --keyboard-layout option to allow more characters based on preferred keyboard layout.
[ "Configure", "a", "static", "password", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L341-L373
9,029
Yubico/yubikey-manager
ykman/cli/otp.py
chalresp
def chalresp(ctx, slot, key, totp, touch, force, generate): """ Program a challenge-response credential. If KEY is not given, an interactive prompt will ask for it. """ controller = ctx.obj['controller'] if key: if generate: ctx.fail('Invalid options: --generate conflicts with KEY argument.') elif totp: key = parse_b32_key(key) else: key = parse_key(key) else: if force and not generate: ctx.fail('No secret key given. Please remove the --force flag, ' 'set the KEY argument or set the --generate flag.') elif totp: while True: key = click.prompt('Enter a secret key (base32)', err=True) try: key = parse_b32_key(key) break except Exception as e: click.echo(e) else: if generate: key = os.urandom(20) click.echo('Using a randomly generated key: {}'.format( b2a_hex(key).decode('ascii'))) else: key = click.prompt('Enter a secret key', err=True) key = parse_key(key) cred_type = 'TOTP' if totp else 'challenge-response' force or click.confirm('Program a {} credential in slot {}?' .format(cred_type, slot), abort=True, err=True) try: controller.program_chalresp(slot, key, touch) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def chalresp(ctx, slot, key, totp, touch, force, generate): """ Program a challenge-response credential. If KEY is not given, an interactive prompt will ask for it. """ controller = ctx.obj['controller'] if key: if generate: ctx.fail('Invalid options: --generate conflicts with KEY argument.') elif totp: key = parse_b32_key(key) else: key = parse_key(key) else: if force and not generate: ctx.fail('No secret key given. Please remove the --force flag, ' 'set the KEY argument or set the --generate flag.') elif totp: while True: key = click.prompt('Enter a secret key (base32)', err=True) try: key = parse_b32_key(key) break except Exception as e: click.echo(e) else: if generate: key = os.urandom(20) click.echo('Using a randomly generated key: {}'.format( b2a_hex(key).decode('ascii'))) else: key = click.prompt('Enter a secret key', err=True) key = parse_key(key) cred_type = 'TOTP' if totp else 'challenge-response' force or click.confirm('Program a {} credential in slot {}?' .format(cred_type, slot), abort=True, err=True) try: controller.program_chalresp(slot, key, touch) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "chalresp", "(", "ctx", ",", "slot", ",", "key", ",", "totp", ",", "touch", ",", "force", ",", "generate", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "key", ":", "if", "generate", ":", "ctx", ".", "fail", "(", "'Invalid options: --generate conflicts with KEY argument.'", ")", "elif", "totp", ":", "key", "=", "parse_b32_key", "(", "key", ")", "else", ":", "key", "=", "parse_key", "(", "key", ")", "else", ":", "if", "force", "and", "not", "generate", ":", "ctx", ".", "fail", "(", "'No secret key given. Please remove the --force flag, '", "'set the KEY argument or set the --generate flag.'", ")", "elif", "totp", ":", "while", "True", ":", "key", "=", "click", ".", "prompt", "(", "'Enter a secret key (base32)'", ",", "err", "=", "True", ")", "try", ":", "key", "=", "parse_b32_key", "(", "key", ")", "break", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "e", ")", "else", ":", "if", "generate", ":", "key", "=", "os", ".", "urandom", "(", "20", ")", "click", ".", "echo", "(", "'Using a randomly generated key: {}'", ".", "format", "(", "b2a_hex", "(", "key", ")", ".", "decode", "(", "'ascii'", ")", ")", ")", "else", ":", "key", "=", "click", ".", "prompt", "(", "'Enter a secret key'", ",", "err", "=", "True", ")", "key", "=", "parse_key", "(", "key", ")", "cred_type", "=", "'TOTP'", "if", "totp", "else", "'challenge-response'", "force", "or", "click", ".", "confirm", "(", "'Program a {} credential in slot {}?'", ".", "format", "(", "cred_type", ",", "slot", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "try", ":", "controller", ".", "program_chalresp", "(", "slot", ",", "key", ",", "touch", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Program a challenge-response credential. If KEY is not given, an interactive prompt will ask for it.
[ "Program", "a", "challenge", "-", "response", "credential", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L390-L432
9,030
Yubico/yubikey-manager
ykman/cli/otp.py
calculate
def calculate(ctx, slot, challenge, totp, digits): """ Perform a challenge-response operation. Send a challenge (in hex) to a YubiKey slot with a challenge-response credential, and read the response. Supports output as a OATH-TOTP code. """ controller = ctx.obj['controller'] if not challenge and not totp: ctx.fail('No challenge provided.') # Check that slot is not empty slot1, slot2 = controller.slot_status if (slot == 1 and not slot1) or (slot == 2 and not slot2): ctx.fail('Cannot perform challenge-response on an empty slot.') # Timestamp challenge should be int if challenge and totp: try: challenge = int(challenge) except Exception as e: logger.error('Error', exc_info=e) ctx.fail('Timestamp challenge for TOTP must be an integer.') try: res = controller.calculate( slot, challenge, totp=totp, digits=int(digits), wait_for_touch=False) except YkpersError as e: # Touch is set if e.errno == 11: prompt_for_touch() try: res = controller.calculate( slot, challenge, totp=totp, digits=int(digits), wait_for_touch=True) except YkpersError as e: # Touch timed out if e.errno == 4: ctx.fail('The YubiKey timed out.') else: ctx.fail(e) else: ctx.fail('Failed to calculate challenge.') click.echo(res)
python
def calculate(ctx, slot, challenge, totp, digits): """ Perform a challenge-response operation. Send a challenge (in hex) to a YubiKey slot with a challenge-response credential, and read the response. Supports output as a OATH-TOTP code. """ controller = ctx.obj['controller'] if not challenge and not totp: ctx.fail('No challenge provided.') # Check that slot is not empty slot1, slot2 = controller.slot_status if (slot == 1 and not slot1) or (slot == 2 and not slot2): ctx.fail('Cannot perform challenge-response on an empty slot.') # Timestamp challenge should be int if challenge and totp: try: challenge = int(challenge) except Exception as e: logger.error('Error', exc_info=e) ctx.fail('Timestamp challenge for TOTP must be an integer.') try: res = controller.calculate( slot, challenge, totp=totp, digits=int(digits), wait_for_touch=False) except YkpersError as e: # Touch is set if e.errno == 11: prompt_for_touch() try: res = controller.calculate( slot, challenge, totp=totp, digits=int(digits), wait_for_touch=True) except YkpersError as e: # Touch timed out if e.errno == 4: ctx.fail('The YubiKey timed out.') else: ctx.fail(e) else: ctx.fail('Failed to calculate challenge.') click.echo(res)
[ "def", "calculate", "(", "ctx", ",", "slot", ",", "challenge", ",", "totp", ",", "digits", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "challenge", "and", "not", "totp", ":", "ctx", ".", "fail", "(", "'No challenge provided.'", ")", "# Check that slot is not empty", "slot1", ",", "slot2", "=", "controller", ".", "slot_status", "if", "(", "slot", "==", "1", "and", "not", "slot1", ")", "or", "(", "slot", "==", "2", "and", "not", "slot2", ")", ":", "ctx", ".", "fail", "(", "'Cannot perform challenge-response on an empty slot.'", ")", "# Timestamp challenge should be int", "if", "challenge", "and", "totp", ":", "try", ":", "challenge", "=", "int", "(", "challenge", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Error'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Timestamp challenge for TOTP must be an integer.'", ")", "try", ":", "res", "=", "controller", ".", "calculate", "(", "slot", ",", "challenge", ",", "totp", "=", "totp", ",", "digits", "=", "int", "(", "digits", ")", ",", "wait_for_touch", "=", "False", ")", "except", "YkpersError", "as", "e", ":", "# Touch is set", "if", "e", ".", "errno", "==", "11", ":", "prompt_for_touch", "(", ")", "try", ":", "res", "=", "controller", ".", "calculate", "(", "slot", ",", "challenge", ",", "totp", "=", "totp", ",", "digits", "=", "int", "(", "digits", ")", ",", "wait_for_touch", "=", "True", ")", "except", "YkpersError", "as", "e", ":", "# Touch timed out", "if", "e", ".", "errno", "==", "4", ":", "ctx", ".", "fail", "(", "'The YubiKey timed out.'", ")", "else", ":", "ctx", ".", "fail", "(", "e", ")", "else", ":", "ctx", ".", "fail", "(", "'Failed to calculate challenge.'", ")", "click", ".", "echo", "(", "res", ")" ]
Perform a challenge-response operation. Send a challenge (in hex) to a YubiKey slot with a challenge-response credential, and read the response. Supports output as a OATH-TOTP code.
[ "Perform", "a", "challenge", "-", "response", "operation", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L445-L488
9,031
Yubico/yubikey-manager
ykman/cli/otp.py
hotp
def hotp(ctx, slot, key, digits, counter, no_enter, force): """ Program an HMAC-SHA1 OATH-HOTP credential. """ controller = ctx.obj['controller'] if not key: while True: key = click.prompt('Enter a secret key (base32)', err=True) try: key = parse_b32_key(key) break except Exception as e: click.echo(e) force or click.confirm( 'Program a HOTP credential in slot {}?'.format(slot), abort=True, err=True) try: controller.program_hotp( slot, key, counter, int(digits) == 8, not no_enter) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def hotp(ctx, slot, key, digits, counter, no_enter, force): """ Program an HMAC-SHA1 OATH-HOTP credential. """ controller = ctx.obj['controller'] if not key: while True: key = click.prompt('Enter a secret key (base32)', err=True) try: key = parse_b32_key(key) break except Exception as e: click.echo(e) force or click.confirm( 'Program a HOTP credential in slot {}?'.format(slot), abort=True, err=True) try: controller.program_hotp( slot, key, counter, int(digits) == 8, not no_enter) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "hotp", "(", "ctx", ",", "slot", ",", "key", ",", "digits", ",", "counter", ",", "no_enter", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "key", ":", "while", "True", ":", "key", "=", "click", ".", "prompt", "(", "'Enter a secret key (base32)'", ",", "err", "=", "True", ")", "try", ":", "key", "=", "parse_b32_key", "(", "key", ")", "break", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "e", ")", "force", "or", "click", ".", "confirm", "(", "'Program a HOTP credential in slot {}?'", ".", "format", "(", "slot", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "try", ":", "controller", ".", "program_hotp", "(", "slot", ",", "key", ",", "counter", ",", "int", "(", "digits", ")", "==", "8", ",", "not", "no_enter", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Program an HMAC-SHA1 OATH-HOTP credential.
[ "Program", "an", "HMAC", "-", "SHA1", "OATH", "-", "HOTP", "credential", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L502-L524
9,032
Yubico/yubikey-manager
ykman/cli/otp.py
settings
def settings(ctx, slot, new_access_code, delete_access_code, enter, pacing, force): """ Update the settings for a slot. Change the settings for a slot without changing the stored secret. All settings not specified will be written with default values. """ controller = ctx.obj['controller'] if (new_access_code is not None) and delete_access_code: ctx.fail('--new-access-code conflicts with --delete-access-code.') if not controller.slot_status[slot - 1]: ctx.fail('Not possible to update settings on an empty slot.') if new_access_code is not None: if new_access_code == '': new_access_code = click.prompt( 'Enter new access code', show_default=False, err=True) try: new_access_code = parse_access_code_hex(new_access_code) except Exception as e: ctx.fail('Failed to parse access code: ' + str(e)) force or click.confirm( 'Update the settings for slot {}? ' 'All existing settings will be overwritten.'.format(slot), abort=True, err=True) click.echo('Updating settings for slot {}...'.format(slot)) if pacing is not None: pacing = int(pacing) try: controller.update_settings(slot, enter=enter, pacing=pacing) except YkpersError as e: _failed_to_write_msg(ctx, e) if new_access_code: try: controller.set_access_code(slot, new_access_code) except Exception as e: logger.error('Failed to set access code', exc_info=e) ctx.fail('Failed to set access code: ' + str(e)) if delete_access_code: try: controller.delete_access_code(slot) except Exception as e: logger.error('Failed to delete access code', exc_info=e) ctx.fail('Failed to delete access code: ' + str(e))
python
def settings(ctx, slot, new_access_code, delete_access_code, enter, pacing, force): """ Update the settings for a slot. Change the settings for a slot without changing the stored secret. All settings not specified will be written with default values. """ controller = ctx.obj['controller'] if (new_access_code is not None) and delete_access_code: ctx.fail('--new-access-code conflicts with --delete-access-code.') if not controller.slot_status[slot - 1]: ctx.fail('Not possible to update settings on an empty slot.') if new_access_code is not None: if new_access_code == '': new_access_code = click.prompt( 'Enter new access code', show_default=False, err=True) try: new_access_code = parse_access_code_hex(new_access_code) except Exception as e: ctx.fail('Failed to parse access code: ' + str(e)) force or click.confirm( 'Update the settings for slot {}? ' 'All existing settings will be overwritten.'.format(slot), abort=True, err=True) click.echo('Updating settings for slot {}...'.format(slot)) if pacing is not None: pacing = int(pacing) try: controller.update_settings(slot, enter=enter, pacing=pacing) except YkpersError as e: _failed_to_write_msg(ctx, e) if new_access_code: try: controller.set_access_code(slot, new_access_code) except Exception as e: logger.error('Failed to set access code', exc_info=e) ctx.fail('Failed to set access code: ' + str(e)) if delete_access_code: try: controller.delete_access_code(slot) except Exception as e: logger.error('Failed to delete access code', exc_info=e) ctx.fail('Failed to delete access code: ' + str(e))
[ "def", "settings", "(", "ctx", ",", "slot", ",", "new_access_code", ",", "delete_access_code", ",", "enter", ",", "pacing", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "(", "new_access_code", "is", "not", "None", ")", "and", "delete_access_code", ":", "ctx", ".", "fail", "(", "'--new-access-code conflicts with --delete-access-code.'", ")", "if", "not", "controller", ".", "slot_status", "[", "slot", "-", "1", "]", ":", "ctx", ".", "fail", "(", "'Not possible to update settings on an empty slot.'", ")", "if", "new_access_code", "is", "not", "None", ":", "if", "new_access_code", "==", "''", ":", "new_access_code", "=", "click", ".", "prompt", "(", "'Enter new access code'", ",", "show_default", "=", "False", ",", "err", "=", "True", ")", "try", ":", "new_access_code", "=", "parse_access_code_hex", "(", "new_access_code", ")", "except", "Exception", "as", "e", ":", "ctx", ".", "fail", "(", "'Failed to parse access code: '", "+", "str", "(", "e", ")", ")", "force", "or", "click", ".", "confirm", "(", "'Update the settings for slot {}? '", "'All existing settings will be overwritten.'", ".", "format", "(", "slot", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "click", ".", "echo", "(", "'Updating settings for slot {}...'", ".", "format", "(", "slot", ")", ")", "if", "pacing", "is", "not", "None", ":", "pacing", "=", "int", "(", "pacing", ")", "try", ":", "controller", ".", "update_settings", "(", "slot", ",", "enter", "=", "enter", ",", "pacing", "=", "pacing", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")", "if", "new_access_code", ":", "try", ":", "controller", ".", "set_access_code", "(", "slot", ",", "new_access_code", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Failed to set access code'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to set access code: '", "+", "str", "(", "e", ")", ")", "if", "delete_access_code", ":", "try", ":", "controller", ".", "delete_access_code", "(", "slot", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Failed to delete access code'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to delete access code: '", "+", "str", "(", "e", ")", ")" ]
Update the settings for a slot. Change the settings for a slot without changing the stored secret. All settings not specified will be written with default values.
[ "Update", "the", "settings", "for", "a", "slot", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L545-L597
9,033
Yubico/yubikey-manager
ykman/util.py
parse_private_key
def parse_private_key(data, password): """ Identifies, decrypts and returns a cryptography private key object. """ # PEM if is_pem(data): if b'ENCRYPTED' in data: if password is None: raise TypeError('No password provided for encrypted key.') try: return serialization.load_pem_private_key( data, password, backend=default_backend()) except ValueError: # Cryptography raises ValueError if decryption fails. raise except Exception: pass # PKCS12 if is_pkcs12(data): try: p12 = crypto.load_pkcs12(data, password) data = crypto.dump_privatekey( crypto.FILETYPE_PEM, p12.get_privatekey()) return serialization.load_pem_private_key( data, password=None, backend=default_backend()) except crypto.Error as e: raise ValueError(e) # DER try: return serialization.load_der_private_key( data, password, backend=default_backend()) except Exception: pass # All parsing failed raise ValueError('Could not parse private key.')
python
def parse_private_key(data, password): """ Identifies, decrypts and returns a cryptography private key object. """ # PEM if is_pem(data): if b'ENCRYPTED' in data: if password is None: raise TypeError('No password provided for encrypted key.') try: return serialization.load_pem_private_key( data, password, backend=default_backend()) except ValueError: # Cryptography raises ValueError if decryption fails. raise except Exception: pass # PKCS12 if is_pkcs12(data): try: p12 = crypto.load_pkcs12(data, password) data = crypto.dump_privatekey( crypto.FILETYPE_PEM, p12.get_privatekey()) return serialization.load_pem_private_key( data, password=None, backend=default_backend()) except crypto.Error as e: raise ValueError(e) # DER try: return serialization.load_der_private_key( data, password, backend=default_backend()) except Exception: pass # All parsing failed raise ValueError('Could not parse private key.')
[ "def", "parse_private_key", "(", "data", ",", "password", ")", ":", "# PEM", "if", "is_pem", "(", "data", ")", ":", "if", "b'ENCRYPTED'", "in", "data", ":", "if", "password", "is", "None", ":", "raise", "TypeError", "(", "'No password provided for encrypted key.'", ")", "try", ":", "return", "serialization", ".", "load_pem_private_key", "(", "data", ",", "password", ",", "backend", "=", "default_backend", "(", ")", ")", "except", "ValueError", ":", "# Cryptography raises ValueError if decryption fails.", "raise", "except", "Exception", ":", "pass", "# PKCS12", "if", "is_pkcs12", "(", "data", ")", ":", "try", ":", "p12", "=", "crypto", ".", "load_pkcs12", "(", "data", ",", "password", ")", "data", "=", "crypto", ".", "dump_privatekey", "(", "crypto", ".", "FILETYPE_PEM", ",", "p12", ".", "get_privatekey", "(", ")", ")", "return", "serialization", ".", "load_pem_private_key", "(", "data", ",", "password", "=", "None", ",", "backend", "=", "default_backend", "(", ")", ")", "except", "crypto", ".", "Error", "as", "e", ":", "raise", "ValueError", "(", "e", ")", "# DER", "try", ":", "return", "serialization", ".", "load_der_private_key", "(", "data", ",", "password", ",", "backend", "=", "default_backend", "(", ")", ")", "except", "Exception", ":", "pass", "# All parsing failed", "raise", "ValueError", "(", "'Could not parse private key.'", ")" ]
Identifies, decrypts and returns a cryptography private key object.
[ "Identifies", "decrypts", "and", "returns", "a", "cryptography", "private", "key", "object", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/util.py#L419-L456
9,034
Yubico/yubikey-manager
ykman/util.py
parse_certificates
def parse_certificates(data, password): """ Identifies, decrypts and returns list of cryptography x509 certificates. """ # PEM if is_pem(data): certs = [] for cert in data.split(PEM_IDENTIFIER): try: certs.append( x509.load_pem_x509_certificate( PEM_IDENTIFIER + cert, default_backend())) except Exception: pass # Could be valid PEM but not certificates. if len(certs) > 0: return certs # PKCS12 if is_pkcs12(data): try: p12 = crypto.load_pkcs12(data, password) data = crypto.dump_certificate( crypto.FILETYPE_PEM, p12.get_certificate()) return [x509.load_pem_x509_certificate(data, default_backend())] except crypto.Error as e: raise ValueError(e) # DER try: return [x509.load_der_x509_certificate(data, default_backend())] except Exception: pass raise ValueError('Could not parse certificate.')
python
def parse_certificates(data, password): """ Identifies, decrypts and returns list of cryptography x509 certificates. """ # PEM if is_pem(data): certs = [] for cert in data.split(PEM_IDENTIFIER): try: certs.append( x509.load_pem_x509_certificate( PEM_IDENTIFIER + cert, default_backend())) except Exception: pass # Could be valid PEM but not certificates. if len(certs) > 0: return certs # PKCS12 if is_pkcs12(data): try: p12 = crypto.load_pkcs12(data, password) data = crypto.dump_certificate( crypto.FILETYPE_PEM, p12.get_certificate()) return [x509.load_pem_x509_certificate(data, default_backend())] except crypto.Error as e: raise ValueError(e) # DER try: return [x509.load_der_x509_certificate(data, default_backend())] except Exception: pass raise ValueError('Could not parse certificate.')
[ "def", "parse_certificates", "(", "data", ",", "password", ")", ":", "# PEM", "if", "is_pem", "(", "data", ")", ":", "certs", "=", "[", "]", "for", "cert", "in", "data", ".", "split", "(", "PEM_IDENTIFIER", ")", ":", "try", ":", "certs", ".", "append", "(", "x509", ".", "load_pem_x509_certificate", "(", "PEM_IDENTIFIER", "+", "cert", ",", "default_backend", "(", ")", ")", ")", "except", "Exception", ":", "pass", "# Could be valid PEM but not certificates.", "if", "len", "(", "certs", ")", ">", "0", ":", "return", "certs", "# PKCS12", "if", "is_pkcs12", "(", "data", ")", ":", "try", ":", "p12", "=", "crypto", ".", "load_pkcs12", "(", "data", ",", "password", ")", "data", "=", "crypto", ".", "dump_certificate", "(", "crypto", ".", "FILETYPE_PEM", ",", "p12", ".", "get_certificate", "(", ")", ")", "return", "[", "x509", ".", "load_pem_x509_certificate", "(", "data", ",", "default_backend", "(", ")", ")", "]", "except", "crypto", ".", "Error", "as", "e", ":", "raise", "ValueError", "(", "e", ")", "# DER", "try", ":", "return", "[", "x509", ".", "load_der_x509_certificate", "(", "data", ",", "default_backend", "(", ")", ")", "]", "except", "Exception", ":", "pass", "raise", "ValueError", "(", "'Could not parse certificate.'", ")" ]
Identifies, decrypts and returns list of cryptography x509 certificates.
[ "Identifies", "decrypts", "and", "returns", "list", "of", "cryptography", "x509", "certificates", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/util.py#L459-L494
9,035
Yubico/yubikey-manager
ykman/util.py
get_leaf_certificates
def get_leaf_certificates(certs): """ Extracts the leaf certificates from a list of certificates. Leaf certificates are ones whose subject does not appear as issuer among the others. """ issuers = [cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME) for cert in certs] leafs = [cert for cert in certs if (cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) not in issuers)] return leafs
python
def get_leaf_certificates(certs): """ Extracts the leaf certificates from a list of certificates. Leaf certificates are ones whose subject does not appear as issuer among the others. """ issuers = [cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME) for cert in certs] leafs = [cert for cert in certs if (cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) not in issuers)] return leafs
[ "def", "get_leaf_certificates", "(", "certs", ")", ":", "issuers", "=", "[", "cert", ".", "issuer", ".", "get_attributes_for_oid", "(", "x509", ".", "NameOID", ".", "COMMON_NAME", ")", "for", "cert", "in", "certs", "]", "leafs", "=", "[", "cert", "for", "cert", "in", "certs", "if", "(", "cert", ".", "subject", ".", "get_attributes_for_oid", "(", "x509", ".", "NameOID", ".", "COMMON_NAME", ")", "not", "in", "issuers", ")", "]", "return", "leafs" ]
Extracts the leaf certificates from a list of certificates. Leaf certificates are ones whose subject does not appear as issuer among the others.
[ "Extracts", "the", "leaf", "certificates", "from", "a", "list", "of", "certificates", ".", "Leaf", "certificates", "are", "ones", "whose", "subject", "does", "not", "appear", "as", "issuer", "among", "the", "others", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/util.py#L497-L508
9,036
Yubico/yubikey-manager
ykman/cli/config.py
set_lock_code
def set_lock_code(ctx, lock_code, new_lock_code, clear, generate, force): """ Set or change the configuration lock code. A lock code may be used to protect the application configuration. The lock code must be a 32 characters (16 bytes) hex value. """ dev = ctx.obj['dev'] def prompt_new_lock_code(): return prompt_lock_code(prompt='Enter your new lock code') def prompt_current_lock_code(): return prompt_lock_code(prompt='Enter your current lock code') def change_lock_code(lock_code, new_lock_code): lock_code = _parse_lock_code(ctx, lock_code) new_lock_code = _parse_lock_code(ctx, new_lock_code) try: dev.write_config( device_config( config_lock=new_lock_code), reboot=True, lock_key=lock_code) except Exception as e: logger.error('Changing the lock code failed', exc_info=e) ctx.fail('Failed to change the lock code. Wrong current code?') def set_lock_code(new_lock_code): new_lock_code = _parse_lock_code(ctx, new_lock_code) try: dev.write_config( device_config( config_lock=new_lock_code), reboot=True) except Exception as e: logger.error('Setting the lock code failed', exc_info=e) ctx.fail('Failed to set the lock code.') if generate and new_lock_code: ctx.fail('Invalid options: --new-lock-code conflicts with --generate.') if clear: new_lock_code = CLEAR_LOCK_CODE if generate: new_lock_code = b2a_hex(os.urandom(16)).decode('utf-8') click.echo( 'Using a randomly generated lock code: {}'.format(new_lock_code)) force or click.confirm( 'Lock configuration with this lock code?', abort=True, err=True) if dev.config.configuration_locked: if lock_code: if new_lock_code: change_lock_code(lock_code, new_lock_code) else: new_lock_code = prompt_new_lock_code() change_lock_code(lock_code, new_lock_code) else: if new_lock_code: lock_code = prompt_current_lock_code() change_lock_code(lock_code, new_lock_code) else: lock_code = prompt_current_lock_code() new_lock_code = prompt_new_lock_code() change_lock_code(lock_code, new_lock_code) else: if lock_code: ctx.fail( 'There is no current lock code set. ' 'Use --new-lock-code to set one.') else: if new_lock_code: set_lock_code(new_lock_code) else: new_lock_code = prompt_new_lock_code() set_lock_code(new_lock_code)
python
def set_lock_code(ctx, lock_code, new_lock_code, clear, generate, force): """ Set or change the configuration lock code. A lock code may be used to protect the application configuration. The lock code must be a 32 characters (16 bytes) hex value. """ dev = ctx.obj['dev'] def prompt_new_lock_code(): return prompt_lock_code(prompt='Enter your new lock code') def prompt_current_lock_code(): return prompt_lock_code(prompt='Enter your current lock code') def change_lock_code(lock_code, new_lock_code): lock_code = _parse_lock_code(ctx, lock_code) new_lock_code = _parse_lock_code(ctx, new_lock_code) try: dev.write_config( device_config( config_lock=new_lock_code), reboot=True, lock_key=lock_code) except Exception as e: logger.error('Changing the lock code failed', exc_info=e) ctx.fail('Failed to change the lock code. Wrong current code?') def set_lock_code(new_lock_code): new_lock_code = _parse_lock_code(ctx, new_lock_code) try: dev.write_config( device_config( config_lock=new_lock_code), reboot=True) except Exception as e: logger.error('Setting the lock code failed', exc_info=e) ctx.fail('Failed to set the lock code.') if generate and new_lock_code: ctx.fail('Invalid options: --new-lock-code conflicts with --generate.') if clear: new_lock_code = CLEAR_LOCK_CODE if generate: new_lock_code = b2a_hex(os.urandom(16)).decode('utf-8') click.echo( 'Using a randomly generated lock code: {}'.format(new_lock_code)) force or click.confirm( 'Lock configuration with this lock code?', abort=True, err=True) if dev.config.configuration_locked: if lock_code: if new_lock_code: change_lock_code(lock_code, new_lock_code) else: new_lock_code = prompt_new_lock_code() change_lock_code(lock_code, new_lock_code) else: if new_lock_code: lock_code = prompt_current_lock_code() change_lock_code(lock_code, new_lock_code) else: lock_code = prompt_current_lock_code() new_lock_code = prompt_new_lock_code() change_lock_code(lock_code, new_lock_code) else: if lock_code: ctx.fail( 'There is no current lock code set. ' 'Use --new-lock-code to set one.') else: if new_lock_code: set_lock_code(new_lock_code) else: new_lock_code = prompt_new_lock_code() set_lock_code(new_lock_code)
[ "def", "set_lock_code", "(", "ctx", ",", "lock_code", ",", "new_lock_code", ",", "clear", ",", "generate", ",", "force", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "def", "prompt_new_lock_code", "(", ")", ":", "return", "prompt_lock_code", "(", "prompt", "=", "'Enter your new lock code'", ")", "def", "prompt_current_lock_code", "(", ")", ":", "return", "prompt_lock_code", "(", "prompt", "=", "'Enter your current lock code'", ")", "def", "change_lock_code", "(", "lock_code", ",", "new_lock_code", ")", ":", "lock_code", "=", "_parse_lock_code", "(", "ctx", ",", "lock_code", ")", "new_lock_code", "=", "_parse_lock_code", "(", "ctx", ",", "new_lock_code", ")", "try", ":", "dev", ".", "write_config", "(", "device_config", "(", "config_lock", "=", "new_lock_code", ")", ",", "reboot", "=", "True", ",", "lock_key", "=", "lock_code", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Changing the lock code failed'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to change the lock code. Wrong current code?'", ")", "def", "set_lock_code", "(", "new_lock_code", ")", ":", "new_lock_code", "=", "_parse_lock_code", "(", "ctx", ",", "new_lock_code", ")", "try", ":", "dev", ".", "write_config", "(", "device_config", "(", "config_lock", "=", "new_lock_code", ")", ",", "reboot", "=", "True", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Setting the lock code failed'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to set the lock code.'", ")", "if", "generate", "and", "new_lock_code", ":", "ctx", ".", "fail", "(", "'Invalid options: --new-lock-code conflicts with --generate.'", ")", "if", "clear", ":", "new_lock_code", "=", "CLEAR_LOCK_CODE", "if", "generate", ":", "new_lock_code", "=", "b2a_hex", "(", "os", ".", "urandom", "(", "16", ")", ")", ".", "decode", "(", "'utf-8'", ")", "click", ".", "echo", "(", "'Using a randomly generated lock code: {}'", ".", "format", "(", "new_lock_code", ")", ")", "force", "or", "click", ".", "confirm", "(", "'Lock configuration with this lock code?'", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "if", "dev", ".", "config", ".", "configuration_locked", ":", "if", "lock_code", ":", "if", "new_lock_code", ":", "change_lock_code", "(", "lock_code", ",", "new_lock_code", ")", "else", ":", "new_lock_code", "=", "prompt_new_lock_code", "(", ")", "change_lock_code", "(", "lock_code", ",", "new_lock_code", ")", "else", ":", "if", "new_lock_code", ":", "lock_code", "=", "prompt_current_lock_code", "(", ")", "change_lock_code", "(", "lock_code", ",", "new_lock_code", ")", "else", ":", "lock_code", "=", "prompt_current_lock_code", "(", ")", "new_lock_code", "=", "prompt_new_lock_code", "(", ")", "change_lock_code", "(", "lock_code", ",", "new_lock_code", ")", "else", ":", "if", "lock_code", ":", "ctx", ".", "fail", "(", "'There is no current lock code set. '", "'Use --new-lock-code to set one.'", ")", "else", ":", "if", "new_lock_code", ":", "set_lock_code", "(", "new_lock_code", ")", "else", ":", "new_lock_code", "=", "prompt_new_lock_code", "(", ")", "set_lock_code", "(", "new_lock_code", ")" ]
Set or change the configuration lock code. A lock code may be used to protect the application configuration. The lock code must be a 32 characters (16 bytes) hex value.
[ "Set", "or", "change", "the", "configuration", "lock", "code", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/config.py#L101-L179
9,037
Yubico/yubikey-manager
ykman/cli/config.py
nfc
def nfc(ctx, enable, disable, enable_all, disable_all, list, lock_code, force): """ Enable or disable applications over NFC. """ if not (list or enable_all or enable or disable_all or disable): ctx.fail('No configuration options chosen.') if enable_all: enable = APPLICATION.__members__.keys() if disable_all: disable = APPLICATION.__members__.keys() _ensure_not_invalid_options(ctx, enable, disable) dev = ctx.obj['dev'] nfc_supported = dev.config.nfc_supported nfc_enabled = dev.config.nfc_enabled if not nfc_supported: ctx.fail('NFC interface not available.') if list: _list_apps(ctx, nfc_enabled) for app in enable: if APPLICATION[app] & nfc_supported: nfc_enabled |= APPLICATION[app] else: ctx.fail('{} not supported over NFC.'.format(app)) for app in disable: if APPLICATION[app] & nfc_supported: nfc_enabled &= ~APPLICATION[app] else: ctx.fail('{} not supported over NFC.'.format(app)) f_confirm = '{}{}Configure NFC interface?'.format( 'Enable {}.\n'.format( ', '.join( [str(APPLICATION[app]) for app in enable])) if enable else '', 'Disable {}.\n'.format( ', '.join( [str(APPLICATION[app]) for app in disable])) if disable else '') is_locked = dev.config.configuration_locked if force and is_locked and not lock_code: ctx.fail('Configuration is locked - please supply the --lock-code ' 'option.') if lock_code and not is_locked: ctx.fail('Configuration is not locked - please remove the ' '--lock-code option.') force or click.confirm(f_confirm, abort=True, err=True) if is_locked and not lock_code: lock_code = prompt_lock_code() if lock_code: lock_code = _parse_lock_code(ctx, lock_code) try: dev.write_config( device_config( nfc_enabled=nfc_enabled), reboot=True, lock_key=lock_code) except Exception as e: logger.error('Failed to write config', exc_info=e) ctx.fail('Failed to configure NFC applications.')
python
def nfc(ctx, enable, disable, enable_all, disable_all, list, lock_code, force): """ Enable or disable applications over NFC. """ if not (list or enable_all or enable or disable_all or disable): ctx.fail('No configuration options chosen.') if enable_all: enable = APPLICATION.__members__.keys() if disable_all: disable = APPLICATION.__members__.keys() _ensure_not_invalid_options(ctx, enable, disable) dev = ctx.obj['dev'] nfc_supported = dev.config.nfc_supported nfc_enabled = dev.config.nfc_enabled if not nfc_supported: ctx.fail('NFC interface not available.') if list: _list_apps(ctx, nfc_enabled) for app in enable: if APPLICATION[app] & nfc_supported: nfc_enabled |= APPLICATION[app] else: ctx.fail('{} not supported over NFC.'.format(app)) for app in disable: if APPLICATION[app] & nfc_supported: nfc_enabled &= ~APPLICATION[app] else: ctx.fail('{} not supported over NFC.'.format(app)) f_confirm = '{}{}Configure NFC interface?'.format( 'Enable {}.\n'.format( ', '.join( [str(APPLICATION[app]) for app in enable])) if enable else '', 'Disable {}.\n'.format( ', '.join( [str(APPLICATION[app]) for app in disable])) if disable else '') is_locked = dev.config.configuration_locked if force and is_locked and not lock_code: ctx.fail('Configuration is locked - please supply the --lock-code ' 'option.') if lock_code and not is_locked: ctx.fail('Configuration is not locked - please remove the ' '--lock-code option.') force or click.confirm(f_confirm, abort=True, err=True) if is_locked and not lock_code: lock_code = prompt_lock_code() if lock_code: lock_code = _parse_lock_code(ctx, lock_code) try: dev.write_config( device_config( nfc_enabled=nfc_enabled), reboot=True, lock_key=lock_code) except Exception as e: logger.error('Failed to write config', exc_info=e) ctx.fail('Failed to configure NFC applications.')
[ "def", "nfc", "(", "ctx", ",", "enable", ",", "disable", ",", "enable_all", ",", "disable_all", ",", "list", ",", "lock_code", ",", "force", ")", ":", "if", "not", "(", "list", "or", "enable_all", "or", "enable", "or", "disable_all", "or", "disable", ")", ":", "ctx", ".", "fail", "(", "'No configuration options chosen.'", ")", "if", "enable_all", ":", "enable", "=", "APPLICATION", ".", "__members__", ".", "keys", "(", ")", "if", "disable_all", ":", "disable", "=", "APPLICATION", ".", "__members__", ".", "keys", "(", ")", "_ensure_not_invalid_options", "(", "ctx", ",", "enable", ",", "disable", ")", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "nfc_supported", "=", "dev", ".", "config", ".", "nfc_supported", "nfc_enabled", "=", "dev", ".", "config", ".", "nfc_enabled", "if", "not", "nfc_supported", ":", "ctx", ".", "fail", "(", "'NFC interface not available.'", ")", "if", "list", ":", "_list_apps", "(", "ctx", ",", "nfc_enabled", ")", "for", "app", "in", "enable", ":", "if", "APPLICATION", "[", "app", "]", "&", "nfc_supported", ":", "nfc_enabled", "|=", "APPLICATION", "[", "app", "]", "else", ":", "ctx", ".", "fail", "(", "'{} not supported over NFC.'", ".", "format", "(", "app", ")", ")", "for", "app", "in", "disable", ":", "if", "APPLICATION", "[", "app", "]", "&", "nfc_supported", ":", "nfc_enabled", "&=", "~", "APPLICATION", "[", "app", "]", "else", ":", "ctx", ".", "fail", "(", "'{} not supported over NFC.'", ".", "format", "(", "app", ")", ")", "f_confirm", "=", "'{}{}Configure NFC interface?'", ".", "format", "(", "'Enable {}.\\n'", ".", "format", "(", "', '", ".", "join", "(", "[", "str", "(", "APPLICATION", "[", "app", "]", ")", "for", "app", "in", "enable", "]", ")", ")", "if", "enable", "else", "''", ",", "'Disable {}.\\n'", ".", "format", "(", "', '", ".", "join", "(", "[", "str", "(", "APPLICATION", "[", "app", "]", ")", "for", "app", "in", "disable", "]", ")", ")", "if", "disable", "else", "''", ")", "is_locked", "=", "dev", ".", "config", ".", "configuration_locked", "if", "force", "and", "is_locked", "and", "not", "lock_code", ":", "ctx", ".", "fail", "(", "'Configuration is locked - please supply the --lock-code '", "'option.'", ")", "if", "lock_code", "and", "not", "is_locked", ":", "ctx", ".", "fail", "(", "'Configuration is not locked - please remove the '", "'--lock-code option.'", ")", "force", "or", "click", ".", "confirm", "(", "f_confirm", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "if", "is_locked", "and", "not", "lock_code", ":", "lock_code", "=", "prompt_lock_code", "(", ")", "if", "lock_code", ":", "lock_code", "=", "_parse_lock_code", "(", "ctx", ",", "lock_code", ")", "try", ":", "dev", ".", "write_config", "(", "device_config", "(", "nfc_enabled", "=", "nfc_enabled", ")", ",", "reboot", "=", "True", ",", "lock_key", "=", "lock_code", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Failed to write config'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to configure NFC applications.'", ")" ]
Enable or disable applications over NFC.
[ "Enable", "or", "disable", "applications", "over", "NFC", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/config.py#L332-L401
9,038
Yubico/yubikey-manager
ykman/cli/info.py
info
def info(ctx, check_fips): """ Show general information. Displays information about the attached YubiKey such as serial number, firmware version, applications, etc. """ dev = ctx.obj['dev'] if dev.is_fips and check_fips: fips_status = get_overall_fips_status(dev.serial, dev.config) click.echo('Device type: {}'.format(dev.device_name)) click.echo('Serial number: {}'.format( dev.serial or 'Not set or unreadable')) if dev.version: f_version = '.'.join(str(x) for x in dev.version) click.echo('Firmware version: {}'.format(f_version)) else: click.echo('Firmware version: Uncertain, re-run with only one ' 'YubiKey connected') config = dev.config if config.form_factor: click.echo('Form factor: {!s}'.format(config.form_factor)) click.echo('Enabled USB interfaces: {}'.format(dev.mode)) if config.nfc_supported: f_nfc = 'enabled' if config.nfc_enabled else 'disabled' click.echo('NFC interface is {}.'.format(f_nfc)) if config.configuration_locked: click.echo('Configured applications are protected by a lock code.') click.echo() print_app_status_table(config) if dev.is_fips and check_fips: click.echo() click.echo('FIPS Approved Mode: {}'.format( 'Yes' if all(fips_status.values()) else 'No')) status_keys = list(fips_status.keys()) status_keys.sort() for status_key in status_keys: click.echo(' {}: {}'.format( status_key, 'Yes' if fips_status[status_key] else 'No'))
python
def info(ctx, check_fips): """ Show general information. Displays information about the attached YubiKey such as serial number, firmware version, applications, etc. """ dev = ctx.obj['dev'] if dev.is_fips and check_fips: fips_status = get_overall_fips_status(dev.serial, dev.config) click.echo('Device type: {}'.format(dev.device_name)) click.echo('Serial number: {}'.format( dev.serial or 'Not set or unreadable')) if dev.version: f_version = '.'.join(str(x) for x in dev.version) click.echo('Firmware version: {}'.format(f_version)) else: click.echo('Firmware version: Uncertain, re-run with only one ' 'YubiKey connected') config = dev.config if config.form_factor: click.echo('Form factor: {!s}'.format(config.form_factor)) click.echo('Enabled USB interfaces: {}'.format(dev.mode)) if config.nfc_supported: f_nfc = 'enabled' if config.nfc_enabled else 'disabled' click.echo('NFC interface is {}.'.format(f_nfc)) if config.configuration_locked: click.echo('Configured applications are protected by a lock code.') click.echo() print_app_status_table(config) if dev.is_fips and check_fips: click.echo() click.echo('FIPS Approved Mode: {}'.format( 'Yes' if all(fips_status.values()) else 'No')) status_keys = list(fips_status.keys()) status_keys.sort() for status_key in status_keys: click.echo(' {}: {}'.format( status_key, 'Yes' if fips_status[status_key] else 'No'))
[ "def", "info", "(", "ctx", ",", "check_fips", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "if", "dev", ".", "is_fips", "and", "check_fips", ":", "fips_status", "=", "get_overall_fips_status", "(", "dev", ".", "serial", ",", "dev", ".", "config", ")", "click", ".", "echo", "(", "'Device type: {}'", ".", "format", "(", "dev", ".", "device_name", ")", ")", "click", ".", "echo", "(", "'Serial number: {}'", ".", "format", "(", "dev", ".", "serial", "or", "'Not set or unreadable'", ")", ")", "if", "dev", ".", "version", ":", "f_version", "=", "'.'", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "dev", ".", "version", ")", "click", ".", "echo", "(", "'Firmware version: {}'", ".", "format", "(", "f_version", ")", ")", "else", ":", "click", ".", "echo", "(", "'Firmware version: Uncertain, re-run with only one '", "'YubiKey connected'", ")", "config", "=", "dev", ".", "config", "if", "config", ".", "form_factor", ":", "click", ".", "echo", "(", "'Form factor: {!s}'", ".", "format", "(", "config", ".", "form_factor", ")", ")", "click", ".", "echo", "(", "'Enabled USB interfaces: {}'", ".", "format", "(", "dev", ".", "mode", ")", ")", "if", "config", ".", "nfc_supported", ":", "f_nfc", "=", "'enabled'", "if", "config", ".", "nfc_enabled", "else", "'disabled'", "click", ".", "echo", "(", "'NFC interface is {}.'", ".", "format", "(", "f_nfc", ")", ")", "if", "config", ".", "configuration_locked", ":", "click", ".", "echo", "(", "'Configured applications are protected by a lock code.'", ")", "click", ".", "echo", "(", ")", "print_app_status_table", "(", "config", ")", "if", "dev", ".", "is_fips", "and", "check_fips", ":", "click", ".", "echo", "(", ")", "click", ".", "echo", "(", "'FIPS Approved Mode: {}'", ".", "format", "(", "'Yes'", "if", "all", "(", "fips_status", ".", "values", "(", ")", ")", "else", "'No'", ")", ")", "status_keys", "=", "list", "(", "fips_status", ".", "keys", "(", ")", ")", "status_keys", ".", "sort", "(", ")", "for", "status_key", "in", "status_keys", ":", "click", ".", "echo", "(", "' {}: {}'", ".", "format", "(", "status_key", ",", "'Yes'", "if", "fips_status", "[", "status_key", "]", "else", "'No'", ")", ")" ]
Show general information. Displays information about the attached YubiKey such as serial number, firmware version, applications, etc.
[ "Show", "general", "information", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/info.py#L130-L175
9,039
Yubico/yubikey-manager
ykman/cli/oath.py
oath
def oath(ctx, password): """ Manage OATH Application. Examples: \b Generate codes for credentials starting with 'yubi': $ ykman oath code yubi \b Add a touch credential with the secret key f5up4ub3dw and the name yubico: $ ykman oath add yubico f5up4ub3dw --touch \b Set a password for the OATH application: $ ykman oath set-password """ try: controller = OathController(ctx.obj['dev'].driver) ctx.obj['controller'] = controller ctx.obj['settings'] = Settings('oath') except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail("The OATH application can't be found on this YubiKey.") raise if password: ctx.obj['key'] = controller.derive_key(password)
python
def oath(ctx, password): """ Manage OATH Application. Examples: \b Generate codes for credentials starting with 'yubi': $ ykman oath code yubi \b Add a touch credential with the secret key f5up4ub3dw and the name yubico: $ ykman oath add yubico f5up4ub3dw --touch \b Set a password for the OATH application: $ ykman oath set-password """ try: controller = OathController(ctx.obj['dev'].driver) ctx.obj['controller'] = controller ctx.obj['settings'] = Settings('oath') except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail("The OATH application can't be found on this YubiKey.") raise if password: ctx.obj['key'] = controller.derive_key(password)
[ "def", "oath", "(", "ctx", ",", "password", ")", ":", "try", ":", "controller", "=", "OathController", "(", "ctx", ".", "obj", "[", "'dev'", "]", ".", "driver", ")", "ctx", ".", "obj", "[", "'controller'", "]", "=", "controller", "ctx", ".", "obj", "[", "'settings'", "]", "=", "Settings", "(", "'oath'", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "ctx", ".", "fail", "(", "\"The OATH application can't be found on this YubiKey.\"", ")", "raise", "if", "password", ":", "ctx", ".", "obj", "[", "'key'", "]", "=", "controller", ".", "derive_key", "(", "password", ")" ]
Manage OATH Application. Examples: \b Generate codes for credentials starting with 'yubi': $ ykman oath code yubi \b Add a touch credential with the secret key f5up4ub3dw and the name yubico: $ ykman oath add yubico f5up4ub3dw --touch \b Set a password for the OATH application: $ ykman oath set-password
[ "Manage", "OATH", "Application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L87-L115
9,040
Yubico/yubikey-manager
ykman/cli/oath.py
info
def info(ctx): """ Display status of OATH application. """ controller = ctx.obj['controller'] version = controller.version click.echo( 'OATH version: {}.{}.{}'.format(version[0], version[1], version[2])) click.echo('Password protection ' + ('enabled' if controller.locked else 'disabled')) keys = ctx.obj['settings'].get('keys', {}) if controller.locked and controller.id in keys: click.echo('The password for this YubiKey is remembered by ykman.') if ctx.obj['dev'].is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No'))
python
def info(ctx): """ Display status of OATH application. """ controller = ctx.obj['controller'] version = controller.version click.echo( 'OATH version: {}.{}.{}'.format(version[0], version[1], version[2])) click.echo('Password protection ' + ('enabled' if controller.locked else 'disabled')) keys = ctx.obj['settings'].get('keys', {}) if controller.locked and controller.id in keys: click.echo('The password for this YubiKey is remembered by ykman.') if ctx.obj['dev'].is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No'))
[ "def", "info", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "version", "=", "controller", ".", "version", "click", ".", "echo", "(", "'OATH version: {}.{}.{}'", ".", "format", "(", "version", "[", "0", "]", ",", "version", "[", "1", "]", ",", "version", "[", "2", "]", ")", ")", "click", ".", "echo", "(", "'Password protection '", "+", "(", "'enabled'", "if", "controller", ".", "locked", "else", "'disabled'", ")", ")", "keys", "=", "ctx", ".", "obj", "[", "'settings'", "]", ".", "get", "(", "'keys'", ",", "{", "}", ")", "if", "controller", ".", "locked", "and", "controller", ".", "id", "in", "keys", ":", "click", ".", "echo", "(", "'The password for this YubiKey is remembered by ykman.'", ")", "if", "ctx", ".", "obj", "[", "'dev'", "]", ".", "is_fips", ":", "click", ".", "echo", "(", "'FIPS Approved Mode: {}'", ".", "format", "(", "'Yes'", "if", "controller", ".", "is_in_fips_mode", "else", "'No'", ")", ")" ]
Display status of OATH application.
[ "Display", "status", "of", "OATH", "application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L120-L137
9,041
Yubico/yubikey-manager
ykman/cli/oath.py
reset
def reset(ctx): """ Reset all OATH data. This action will wipe all credentials and reset factory settings for the OATH application on the YubiKey. """ controller = ctx.obj['controller'] click.echo('Resetting OATH data...') old_id = controller.id controller.reset() settings = ctx.obj['settings'] keys = settings.setdefault('keys', {}) if old_id in keys: del keys[old_id] settings.write() click.echo( 'Success! All OATH credentials have been cleared from your YubiKey.')
python
def reset(ctx): """ Reset all OATH data. This action will wipe all credentials and reset factory settings for the OATH application on the YubiKey. """ controller = ctx.obj['controller'] click.echo('Resetting OATH data...') old_id = controller.id controller.reset() settings = ctx.obj['settings'] keys = settings.setdefault('keys', {}) if old_id in keys: del keys[old_id] settings.write() click.echo( 'Success! All OATH credentials have been cleared from your YubiKey.')
[ "def", "reset", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "click", ".", "echo", "(", "'Resetting OATH data...'", ")", "old_id", "=", "controller", ".", "id", "controller", ".", "reset", "(", ")", "settings", "=", "ctx", ".", "obj", "[", "'settings'", "]", "keys", "=", "settings", ".", "setdefault", "(", "'keys'", ",", "{", "}", ")", "if", "old_id", "in", "keys", ":", "del", "keys", "[", "old_id", "]", "settings", ".", "write", "(", ")", "click", ".", "echo", "(", "'Success! All OATH credentials have been cleared from your YubiKey.'", ")" ]
Reset all OATH data. This action will wipe all credentials and reset factory settings for the OATH application on the YubiKey.
[ "Reset", "all", "OATH", "data", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L145-L165
9,042
Yubico/yubikey-manager
ykman/cli/oath.py
add
def add(ctx, secret, name, issuer, period, oath_type, digits, touch, algorithm, counter, force): """ Add a new credential. This will add a new credential to your YubiKey. """ oath_type = OATH_TYPE[oath_type] algorithm = ALGO[algorithm] digits = int(digits) if not secret: while True: secret = click.prompt('Enter a secret key (base32)', err=True) try: secret = parse_b32_key(secret) break except Exception as e: click.echo(e) ensure_validated(ctx) _add_cred(ctx, CredentialData(secret, issuer, name, oath_type, algorithm, digits, period, counter, touch), force)
python
def add(ctx, secret, name, issuer, period, oath_type, digits, touch, algorithm, counter, force): """ Add a new credential. This will add a new credential to your YubiKey. """ oath_type = OATH_TYPE[oath_type] algorithm = ALGO[algorithm] digits = int(digits) if not secret: while True: secret = click.prompt('Enter a secret key (base32)', err=True) try: secret = parse_b32_key(secret) break except Exception as e: click.echo(e) ensure_validated(ctx) _add_cred(ctx, CredentialData(secret, issuer, name, oath_type, algorithm, digits, period, counter, touch), force)
[ "def", "add", "(", "ctx", ",", "secret", ",", "name", ",", "issuer", ",", "period", ",", "oath_type", ",", "digits", ",", "touch", ",", "algorithm", ",", "counter", ",", "force", ")", ":", "oath_type", "=", "OATH_TYPE", "[", "oath_type", "]", "algorithm", "=", "ALGO", "[", "algorithm", "]", "digits", "=", "int", "(", "digits", ")", "if", "not", "secret", ":", "while", "True", ":", "secret", "=", "click", ".", "prompt", "(", "'Enter a secret key (base32)'", ",", "err", "=", "True", ")", "try", ":", "secret", "=", "parse_b32_key", "(", "secret", ")", "break", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "e", ")", "ensure_validated", "(", "ctx", ")", "_add_cred", "(", "ctx", ",", "CredentialData", "(", "secret", ",", "issuer", ",", "name", ",", "oath_type", ",", "algorithm", ",", "digits", ",", "period", ",", "counter", ",", "touch", ")", ",", "force", ")" ]
Add a new credential. This will add a new credential to your YubiKey.
[ "Add", "a", "new", "credential", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L192-L216
9,043
Yubico/yubikey-manager
ykman/cli/oath.py
uri
def uri(ctx, uri, touch, force): """ Add a new credential from URI. Use a URI to add a new credential to your YubiKey. """ if not uri: while True: uri = click.prompt('Enter an OATH URI', err=True) try: uri = CredentialData.from_uri(uri) break except Exception as e: click.echo(e) ensure_validated(ctx) data = uri # Steam is a special case where we allow the otpauth # URI to contain a 'digits' value of '5'. if data.digits == 5 and data.issuer == 'Steam': data.digits = 6 data.touch = touch _add_cred(ctx, data, force=force)
python
def uri(ctx, uri, touch, force): """ Add a new credential from URI. Use a URI to add a new credential to your YubiKey. """ if not uri: while True: uri = click.prompt('Enter an OATH URI', err=True) try: uri = CredentialData.from_uri(uri) break except Exception as e: click.echo(e) ensure_validated(ctx) data = uri # Steam is a special case where we allow the otpauth # URI to contain a 'digits' value of '5'. if data.digits == 5 and data.issuer == 'Steam': data.digits = 6 data.touch = touch _add_cred(ctx, data, force=force)
[ "def", "uri", "(", "ctx", ",", "uri", ",", "touch", ",", "force", ")", ":", "if", "not", "uri", ":", "while", "True", ":", "uri", "=", "click", ".", "prompt", "(", "'Enter an OATH URI'", ",", "err", "=", "True", ")", "try", ":", "uri", "=", "CredentialData", ".", "from_uri", "(", "uri", ")", "break", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "e", ")", "ensure_validated", "(", "ctx", ")", "data", "=", "uri", "# Steam is a special case where we allow the otpauth", "# URI to contain a 'digits' value of '5'.", "if", "data", ".", "digits", "==", "5", "and", "data", ".", "issuer", "==", "'Steam'", ":", "data", ".", "digits", "=", "6", "data", ".", "touch", "=", "touch", "_add_cred", "(", "ctx", ",", "data", ",", "force", "=", "force", ")" ]
Add a new credential from URI. Use a URI to add a new credential to your YubiKey.
[ "Add", "a", "new", "credential", "from", "URI", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L224-L250
9,044
Yubico/yubikey-manager
ykman/cli/oath.py
list
def list(ctx, show_hidden, oath_type, period): """ List all credentials. List all credentials stored on your YubiKey. """ ensure_validated(ctx) controller = ctx.obj['controller'] creds = [cred for cred in controller.list() if show_hidden or not cred.is_hidden ] creds.sort() for cred in creds: click.echo(cred.printable_key, nl=False) if oath_type: click.echo(u', {}'.format(cred.oath_type.name), nl=False) if period: click.echo(', {}'.format(cred.period), nl=False) click.echo()
python
def list(ctx, show_hidden, oath_type, period): """ List all credentials. List all credentials stored on your YubiKey. """ ensure_validated(ctx) controller = ctx.obj['controller'] creds = [cred for cred in controller.list() if show_hidden or not cred.is_hidden ] creds.sort() for cred in creds: click.echo(cred.printable_key, nl=False) if oath_type: click.echo(u', {}'.format(cred.oath_type.name), nl=False) if period: click.echo(', {}'.format(cred.period), nl=False) click.echo()
[ "def", "list", "(", "ctx", ",", "show_hidden", ",", "oath_type", ",", "period", ")", ":", "ensure_validated", "(", "ctx", ")", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "creds", "=", "[", "cred", "for", "cred", "in", "controller", ".", "list", "(", ")", "if", "show_hidden", "or", "not", "cred", ".", "is_hidden", "]", "creds", ".", "sort", "(", ")", "for", "cred", "in", "creds", ":", "click", ".", "echo", "(", "cred", ".", "printable_key", ",", "nl", "=", "False", ")", "if", "oath_type", ":", "click", ".", "echo", "(", "u', {}'", ".", "format", "(", "cred", ".", "oath_type", ".", "name", ")", ",", "nl", "=", "False", ")", "if", "period", ":", "click", ".", "echo", "(", "', {}'", ".", "format", "(", "cred", ".", "period", ")", ",", "nl", "=", "False", ")", "click", ".", "echo", "(", ")" ]
List all credentials. List all credentials stored on your YubiKey.
[ "List", "all", "credentials", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L307-L326
9,045
Yubico/yubikey-manager
ykman/cli/oath.py
code
def code(ctx, show_hidden, query, single): """ Generate codes. Generate codes from credentials stored on your YubiKey. Provide a query string to match one or more specific credentials. Touch and HOTP credentials require a single match to be triggered. """ ensure_validated(ctx) controller = ctx.obj['controller'] creds = [(cr, c) for (cr, c) in controller.calculate_all() if show_hidden or not cr.is_hidden ] creds = _search(creds, query) if len(creds) == 1: cred, code = creds[0] if cred.touch: prompt_for_touch() try: if cred.oath_type == OATH_TYPE.HOTP: # HOTP might require touch, we don't know. # Assume yes after 500ms. hotp_touch_timer = Timer(0.500, prompt_for_touch) hotp_touch_timer.start() creds = [(cred, controller.calculate(cred))] hotp_touch_timer.cancel() elif code is None: creds = [(cred, controller.calculate(cred))] except APDUError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: ctx.fail('Touch credential timed out!') elif single: _error_multiple_hits(ctx, [cr for cr, c in creds]) if single: click.echo(creds[0][1].value) else: creds.sort() outputs = [ ( cr.printable_key, c.value if c else '[Touch Credential]' if cr.touch else '[HOTP Credential]' if cr.oath_type == OATH_TYPE.HOTP else '' ) for (cr, c) in creds ] longest_name = max(len(n) for (n, c) in outputs) if outputs else 0 longest_code = max(len(c) for (n, c) in outputs) if outputs else 0 format_str = u'{:<%d} {:>%d}' % (longest_name, longest_code) for name, result in outputs: click.echo(format_str.format(name, result))
python
def code(ctx, show_hidden, query, single): """ Generate codes. Generate codes from credentials stored on your YubiKey. Provide a query string to match one or more specific credentials. Touch and HOTP credentials require a single match to be triggered. """ ensure_validated(ctx) controller = ctx.obj['controller'] creds = [(cr, c) for (cr, c) in controller.calculate_all() if show_hidden or not cr.is_hidden ] creds = _search(creds, query) if len(creds) == 1: cred, code = creds[0] if cred.touch: prompt_for_touch() try: if cred.oath_type == OATH_TYPE.HOTP: # HOTP might require touch, we don't know. # Assume yes after 500ms. hotp_touch_timer = Timer(0.500, prompt_for_touch) hotp_touch_timer.start() creds = [(cred, controller.calculate(cred))] hotp_touch_timer.cancel() elif code is None: creds = [(cred, controller.calculate(cred))] except APDUError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: ctx.fail('Touch credential timed out!') elif single: _error_multiple_hits(ctx, [cr for cr, c in creds]) if single: click.echo(creds[0][1].value) else: creds.sort() outputs = [ ( cr.printable_key, c.value if c else '[Touch Credential]' if cr.touch else '[HOTP Credential]' if cr.oath_type == OATH_TYPE.HOTP else '' ) for (cr, c) in creds ] longest_name = max(len(n) for (n, c) in outputs) if outputs else 0 longest_code = max(len(c) for (n, c) in outputs) if outputs else 0 format_str = u'{:<%d} {:>%d}' % (longest_name, longest_code) for name, result in outputs: click.echo(format_str.format(name, result))
[ "def", "code", "(", "ctx", ",", "show_hidden", ",", "query", ",", "single", ")", ":", "ensure_validated", "(", "ctx", ")", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "creds", "=", "[", "(", "cr", ",", "c", ")", "for", "(", "cr", ",", "c", ")", "in", "controller", ".", "calculate_all", "(", ")", "if", "show_hidden", "or", "not", "cr", ".", "is_hidden", "]", "creds", "=", "_search", "(", "creds", ",", "query", ")", "if", "len", "(", "creds", ")", "==", "1", ":", "cred", ",", "code", "=", "creds", "[", "0", "]", "if", "cred", ".", "touch", ":", "prompt_for_touch", "(", ")", "try", ":", "if", "cred", ".", "oath_type", "==", "OATH_TYPE", ".", "HOTP", ":", "# HOTP might require touch, we don't know.", "# Assume yes after 500ms.", "hotp_touch_timer", "=", "Timer", "(", "0.500", ",", "prompt_for_touch", ")", "hotp_touch_timer", ".", "start", "(", ")", "creds", "=", "[", "(", "cred", ",", "controller", ".", "calculate", "(", "cred", ")", ")", "]", "hotp_touch_timer", ".", "cancel", "(", ")", "elif", "code", "is", "None", ":", "creds", "=", "[", "(", "cred", ",", "controller", ".", "calculate", "(", "cred", ")", ")", "]", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "SECURITY_CONDITION_NOT_SATISFIED", ":", "ctx", ".", "fail", "(", "'Touch credential timed out!'", ")", "elif", "single", ":", "_error_multiple_hits", "(", "ctx", ",", "[", "cr", "for", "cr", ",", "c", "in", "creds", "]", ")", "if", "single", ":", "click", ".", "echo", "(", "creds", "[", "0", "]", "[", "1", "]", ".", "value", ")", "else", ":", "creds", ".", "sort", "(", ")", "outputs", "=", "[", "(", "cr", ".", "printable_key", ",", "c", ".", "value", "if", "c", "else", "'[Touch Credential]'", "if", "cr", ".", "touch", "else", "'[HOTP Credential]'", "if", "cr", ".", "oath_type", "==", "OATH_TYPE", ".", "HOTP", "else", "''", ")", "for", "(", "cr", ",", "c", ")", "in", "creds", "]", "longest_name", "=", "max", "(", "len", "(", "n", ")", "for", "(", "n", ",", "c", ")", "in", "outputs", ")", "if", "outputs", "else", "0", "longest_code", "=", "max", "(", "len", "(", "c", ")", "for", "(", "n", ",", "c", ")", "in", "outputs", ")", "if", "outputs", "else", "0", "format_str", "=", "u'{:<%d} {:>%d}'", "%", "(", "longest_name", ",", "longest_code", ")", "for", "name", ",", "result", "in", "outputs", ":", "click", ".", "echo", "(", "format_str", ".", "format", "(", "name", ",", "result", ")", ")" ]
Generate codes. Generate codes from credentials stored on your YubiKey. Provide a query string to match one or more specific credentials. Touch and HOTP credentials require a single match to be triggered.
[ "Generate", "codes", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L335-L395
9,046
Yubico/yubikey-manager
ykman/cli/oath.py
delete
def delete(ctx, query, force): """ Delete a credential. Delete a credential from your YubiKey. Provide a query string to match the credential to delete. """ ensure_validated(ctx) controller = ctx.obj['controller'] creds = controller.list() hits = _search(creds, query) if len(hits) == 0: click.echo('No matches, nothing to be done.') elif len(hits) == 1: cred = hits[0] if force or (click.confirm( u'Delete credential: {} ?'.format(cred.printable_key), default=False, err=True )): controller.delete(cred) click.echo(u'Deleted {}.'.format(cred.printable_key)) else: click.echo('Deletion aborted by user.') else: _error_multiple_hits(ctx, hits)
python
def delete(ctx, query, force): """ Delete a credential. Delete a credential from your YubiKey. Provide a query string to match the credential to delete. """ ensure_validated(ctx) controller = ctx.obj['controller'] creds = controller.list() hits = _search(creds, query) if len(hits) == 0: click.echo('No matches, nothing to be done.') elif len(hits) == 1: cred = hits[0] if force or (click.confirm( u'Delete credential: {} ?'.format(cred.printable_key), default=False, err=True )): controller.delete(cred) click.echo(u'Deleted {}.'.format(cred.printable_key)) else: click.echo('Deletion aborted by user.') else: _error_multiple_hits(ctx, hits)
[ "def", "delete", "(", "ctx", ",", "query", ",", "force", ")", ":", "ensure_validated", "(", "ctx", ")", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "creds", "=", "controller", ".", "list", "(", ")", "hits", "=", "_search", "(", "creds", ",", "query", ")", "if", "len", "(", "hits", ")", "==", "0", ":", "click", ".", "echo", "(", "'No matches, nothing to be done.'", ")", "elif", "len", "(", "hits", ")", "==", "1", ":", "cred", "=", "hits", "[", "0", "]", "if", "force", "or", "(", "click", ".", "confirm", "(", "u'Delete credential: {} ?'", ".", "format", "(", "cred", ".", "printable_key", ")", ",", "default", "=", "False", ",", "err", "=", "True", ")", ")", ":", "controller", ".", "delete", "(", "cred", ")", "click", ".", "echo", "(", "u'Deleted {}.'", ".", "format", "(", "cred", ".", "printable_key", ")", ")", "else", ":", "click", ".", "echo", "(", "'Deletion aborted by user.'", ")", "else", ":", "_error_multiple_hits", "(", "ctx", ",", "hits", ")" ]
Delete a credential. Delete a credential from your YubiKey. Provide a query string to match the credential to delete.
[ "Delete", "a", "credential", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L403-L429
9,047
Yubico/yubikey-manager
ykman/cli/oath.py
set_password
def set_password(ctx, new_password, remember): """ Password protect the OATH credentials. Allows you to set a password that will be required to access the OATH credentials stored on your YubiKey. """ ensure_validated(ctx, prompt='Enter your current password') if not new_password: new_password = click.prompt( 'Enter your new password', hide_input=True, confirmation_prompt=True, err=True) controller = ctx.obj['controller'] settings = ctx.obj['settings'] keys = settings.setdefault('keys', {}) key = controller.set_password(new_password) click.echo('Password updated.') if remember: keys[controller.id] = b2a_hex(key).decode() settings.write() click.echo('Password remembered') elif controller.id in keys: del keys[controller.id] settings.write()
python
def set_password(ctx, new_password, remember): """ Password protect the OATH credentials. Allows you to set a password that will be required to access the OATH credentials stored on your YubiKey. """ ensure_validated(ctx, prompt='Enter your current password') if not new_password: new_password = click.prompt( 'Enter your new password', hide_input=True, confirmation_prompt=True, err=True) controller = ctx.obj['controller'] settings = ctx.obj['settings'] keys = settings.setdefault('keys', {}) key = controller.set_password(new_password) click.echo('Password updated.') if remember: keys[controller.id] = b2a_hex(key).decode() settings.write() click.echo('Password remembered') elif controller.id in keys: del keys[controller.id] settings.write()
[ "def", "set_password", "(", "ctx", ",", "new_password", ",", "remember", ")", ":", "ensure_validated", "(", "ctx", ",", "prompt", "=", "'Enter your current password'", ")", "if", "not", "new_password", ":", "new_password", "=", "click", ".", "prompt", "(", "'Enter your new password'", ",", "hide_input", "=", "True", ",", "confirmation_prompt", "=", "True", ",", "err", "=", "True", ")", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "settings", "=", "ctx", ".", "obj", "[", "'settings'", "]", "keys", "=", "settings", ".", "setdefault", "(", "'keys'", ",", "{", "}", ")", "key", "=", "controller", ".", "set_password", "(", "new_password", ")", "click", ".", "echo", "(", "'Password updated.'", ")", "if", "remember", ":", "keys", "[", "controller", ".", "id", "]", "=", "b2a_hex", "(", "key", ")", ".", "decode", "(", ")", "settings", ".", "write", "(", ")", "click", ".", "echo", "(", "'Password remembered'", ")", "elif", "controller", ".", "id", "in", "keys", ":", "del", "keys", "[", "controller", ".", "id", "]", "settings", ".", "write", "(", ")" ]
Password protect the OATH credentials. Allows you to set a password that will be required to access the OATH credentials stored on your YubiKey.
[ "Password", "protect", "the", "OATH", "credentials", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L442-L468
9,048
Yubico/yubikey-manager
ykman/cli/oath.py
remember_password
def remember_password(ctx, forget, clear_all): """ Manage local password storage. Store your YubiKeys password on this computer to avoid having to enter it on each use, or delete stored passwords. """ controller = ctx.obj['controller'] settings = ctx.obj['settings'] keys = settings.setdefault('keys', {}) if clear_all: del settings['keys'] settings.write() click.echo('All passwords have been cleared.') elif forget: if controller.id in keys: del keys[controller.id] settings.write() click.echo('Password forgotten.') else: ensure_validated(ctx, remember=True)
python
def remember_password(ctx, forget, clear_all): """ Manage local password storage. Store your YubiKeys password on this computer to avoid having to enter it on each use, or delete stored passwords. """ controller = ctx.obj['controller'] settings = ctx.obj['settings'] keys = settings.setdefault('keys', {}) if clear_all: del settings['keys'] settings.write() click.echo('All passwords have been cleared.') elif forget: if controller.id in keys: del keys[controller.id] settings.write() click.echo('Password forgotten.') else: ensure_validated(ctx, remember=True)
[ "def", "remember_password", "(", "ctx", ",", "forget", ",", "clear_all", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "settings", "=", "ctx", ".", "obj", "[", "'settings'", "]", "keys", "=", "settings", ".", "setdefault", "(", "'keys'", ",", "{", "}", ")", "if", "clear_all", ":", "del", "settings", "[", "'keys'", "]", "settings", ".", "write", "(", ")", "click", ".", "echo", "(", "'All passwords have been cleared.'", ")", "elif", "forget", ":", "if", "controller", ".", "id", "in", "keys", ":", "del", "keys", "[", "controller", ".", "id", "]", "settings", ".", "write", "(", ")", "click", ".", "echo", "(", "'Password forgotten.'", ")", "else", ":", "ensure_validated", "(", "ctx", ",", "remember", "=", "True", ")" ]
Manage local password storage. Store your YubiKeys password on this computer to avoid having to enter it on each use, or delete stored passwords.
[ "Manage", "local", "password", "storage", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L476-L496
9,049
chaimleib/intervaltree
intervaltree/node.py
Node.refresh_balance
def refresh_balance(self): """ Recalculate self.balance and self.depth based on child node values. """ left_depth = self.left_node.depth if self.left_node else 0 right_depth = self.right_node.depth if self.right_node else 0 self.depth = 1 + max(left_depth, right_depth) self.balance = right_depth - left_depth
python
def refresh_balance(self): """ Recalculate self.balance and self.depth based on child node values. """ left_depth = self.left_node.depth if self.left_node else 0 right_depth = self.right_node.depth if self.right_node else 0 self.depth = 1 + max(left_depth, right_depth) self.balance = right_depth - left_depth
[ "def", "refresh_balance", "(", "self", ")", ":", "left_depth", "=", "self", ".", "left_node", ".", "depth", "if", "self", ".", "left_node", "else", "0", "right_depth", "=", "self", ".", "right_node", ".", "depth", "if", "self", ".", "right_node", "else", "0", "self", ".", "depth", "=", "1", "+", "max", "(", "left_depth", ",", "right_depth", ")", "self", ".", "balance", "=", "right_depth", "-", "left_depth" ]
Recalculate self.balance and self.depth based on child node values.
[ "Recalculate", "self", ".", "balance", "and", "self", ".", "depth", "based", "on", "child", "node", "values", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L100-L107
9,050
chaimleib/intervaltree
intervaltree/node.py
Node.compute_depth
def compute_depth(self): """ Recursively computes true depth of the subtree. Should only be needed for debugging. Unless something is wrong, the depth field should reflect the correct depth of the subtree. """ left_depth = self.left_node.compute_depth() if self.left_node else 0 right_depth = self.right_node.compute_depth() if self.right_node else 0 return 1 + max(left_depth, right_depth)
python
def compute_depth(self): """ Recursively computes true depth of the subtree. Should only be needed for debugging. Unless something is wrong, the depth field should reflect the correct depth of the subtree. """ left_depth = self.left_node.compute_depth() if self.left_node else 0 right_depth = self.right_node.compute_depth() if self.right_node else 0 return 1 + max(left_depth, right_depth)
[ "def", "compute_depth", "(", "self", ")", ":", "left_depth", "=", "self", ".", "left_node", ".", "compute_depth", "(", ")", "if", "self", ".", "left_node", "else", "0", "right_depth", "=", "self", ".", "right_node", ".", "compute_depth", "(", ")", "if", "self", ".", "right_node", "else", "0", "return", "1", "+", "max", "(", "left_depth", ",", "right_depth", ")" ]
Recursively computes true depth of the subtree. Should only be needed for debugging. Unless something is wrong, the depth field should reflect the correct depth of the subtree.
[ "Recursively", "computes", "true", "depth", "of", "the", "subtree", ".", "Should", "only", "be", "needed", "for", "debugging", ".", "Unless", "something", "is", "wrong", "the", "depth", "field", "should", "reflect", "the", "correct", "depth", "of", "the", "subtree", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L109-L117
9,051
chaimleib/intervaltree
intervaltree/node.py
Node.rotate
def rotate(self): """ Does rotating, if necessary, to balance this node, and returns the new top node. """ self.refresh_balance() if abs(self.balance) < 2: return self # balance > 0 is the heavy side my_heavy = self.balance > 0 child_heavy = self[my_heavy].balance > 0 if my_heavy == child_heavy or self[my_heavy].balance == 0: ## Heavy sides same # self save # save -> 1 self # 1 # ## Heavy side balanced # self save save # save -> 1 self -> 1 self.rot() # 1 2 2 return self.srotate() else: return self.drotate()
python
def rotate(self): """ Does rotating, if necessary, to balance this node, and returns the new top node. """ self.refresh_balance() if abs(self.balance) < 2: return self # balance > 0 is the heavy side my_heavy = self.balance > 0 child_heavy = self[my_heavy].balance > 0 if my_heavy == child_heavy or self[my_heavy].balance == 0: ## Heavy sides same # self save # save -> 1 self # 1 # ## Heavy side balanced # self save save # save -> 1 self -> 1 self.rot() # 1 2 2 return self.srotate() else: return self.drotate()
[ "def", "rotate", "(", "self", ")", ":", "self", ".", "refresh_balance", "(", ")", "if", "abs", "(", "self", ".", "balance", ")", "<", "2", ":", "return", "self", "# balance > 0 is the heavy side", "my_heavy", "=", "self", ".", "balance", ">", "0", "child_heavy", "=", "self", "[", "my_heavy", "]", ".", "balance", ">", "0", "if", "my_heavy", "==", "child_heavy", "or", "self", "[", "my_heavy", "]", ".", "balance", "==", "0", ":", "## Heavy sides same", "# self save", "# save -> 1 self", "# 1", "#", "## Heavy side balanced", "# self save save", "# save -> 1 self -> 1 self.rot()", "# 1 2 2", "return", "self", ".", "srotate", "(", ")", "else", ":", "return", "self", ".", "drotate", "(", ")" ]
Does rotating, if necessary, to balance this node, and returns the new top node.
[ "Does", "rotating", "if", "necessary", "to", "balance", "this", "node", "and", "returns", "the", "new", "top", "node", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L119-L142
9,052
chaimleib/intervaltree
intervaltree/node.py
Node.srotate
def srotate(self): """Single rotation. Assumes that balance is +-2.""" # self save save # save 3 -> 1 self -> 1 self.rot() # 1 2 2 3 # # self save save # 3 save -> self 1 -> self.rot() 1 # 2 1 3 2 #assert(self.balance != 0) heavy = self.balance > 0 light = not heavy save = self[heavy] #print("srotate: bal={},{}".format(self.balance, save.balance)) #self.print_structure() self[heavy] = save[light] # 2 #assert(save[light]) save[light] = self.rotate() # Needed to ensure the 2 and 3 are balanced under new subnode # Some intervals may overlap both self.x_center and save.x_center # Promote those to the new tip of the tree promotees = [iv for iv in save[light].s_center if save.center_hit(iv)] if promotees: for iv in promotees: save[light] = save[light].remove(iv) # may trigger pruning # TODO: Use Node.add() here, to simplify future balancing improvements. # For now, this is the same as augmenting save.s_center, but that may # change. save.s_center.update(promotees) save.refresh_balance() return save
python
def srotate(self): """Single rotation. Assumes that balance is +-2.""" # self save save # save 3 -> 1 self -> 1 self.rot() # 1 2 2 3 # # self save save # 3 save -> self 1 -> self.rot() 1 # 2 1 3 2 #assert(self.balance != 0) heavy = self.balance > 0 light = not heavy save = self[heavy] #print("srotate: bal={},{}".format(self.balance, save.balance)) #self.print_structure() self[heavy] = save[light] # 2 #assert(save[light]) save[light] = self.rotate() # Needed to ensure the 2 and 3 are balanced under new subnode # Some intervals may overlap both self.x_center and save.x_center # Promote those to the new tip of the tree promotees = [iv for iv in save[light].s_center if save.center_hit(iv)] if promotees: for iv in promotees: save[light] = save[light].remove(iv) # may trigger pruning # TODO: Use Node.add() here, to simplify future balancing improvements. # For now, this is the same as augmenting save.s_center, but that may # change. save.s_center.update(promotees) save.refresh_balance() return save
[ "def", "srotate", "(", "self", ")", ":", "# self save save", "# save 3 -> 1 self -> 1 self.rot()", "# 1 2 2 3", "#", "# self save save", "# 3 save -> self 1 -> self.rot() 1", "# 2 1 3 2", "#assert(self.balance != 0)", "heavy", "=", "self", ".", "balance", ">", "0", "light", "=", "not", "heavy", "save", "=", "self", "[", "heavy", "]", "#print(\"srotate: bal={},{}\".format(self.balance, save.balance))", "#self.print_structure()", "self", "[", "heavy", "]", "=", "save", "[", "light", "]", "# 2", "#assert(save[light])", "save", "[", "light", "]", "=", "self", ".", "rotate", "(", ")", "# Needed to ensure the 2 and 3 are balanced under new subnode", "# Some intervals may overlap both self.x_center and save.x_center", "# Promote those to the new tip of the tree", "promotees", "=", "[", "iv", "for", "iv", "in", "save", "[", "light", "]", ".", "s_center", "if", "save", ".", "center_hit", "(", "iv", ")", "]", "if", "promotees", ":", "for", "iv", "in", "promotees", ":", "save", "[", "light", "]", "=", "save", "[", "light", "]", ".", "remove", "(", "iv", ")", "# may trigger pruning", "# TODO: Use Node.add() here, to simplify future balancing improvements.", "# For now, this is the same as augmenting save.s_center, but that may", "# change.", "save", ".", "s_center", ".", "update", "(", "promotees", ")", "save", ".", "refresh_balance", "(", ")", "return", "save" ]
Single rotation. Assumes that balance is +-2.
[ "Single", "rotation", ".", "Assumes", "that", "balance", "is", "+", "-", "2", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L144-L175
9,053
chaimleib/intervaltree
intervaltree/node.py
Node.add
def add(self, interval): """ Returns self after adding the interval and balancing. """ if self.center_hit(interval): self.s_center.add(interval) return self else: direction = self.hit_branch(interval) if not self[direction]: self[direction] = Node.from_interval(interval) self.refresh_balance() return self else: self[direction] = self[direction].add(interval) return self.rotate()
python
def add(self, interval): """ Returns self after adding the interval and balancing. """ if self.center_hit(interval): self.s_center.add(interval) return self else: direction = self.hit_branch(interval) if not self[direction]: self[direction] = Node.from_interval(interval) self.refresh_balance() return self else: self[direction] = self[direction].add(interval) return self.rotate()
[ "def", "add", "(", "self", ",", "interval", ")", ":", "if", "self", ".", "center_hit", "(", "interval", ")", ":", "self", ".", "s_center", ".", "add", "(", "interval", ")", "return", "self", "else", ":", "direction", "=", "self", ".", "hit_branch", "(", "interval", ")", "if", "not", "self", "[", "direction", "]", ":", "self", "[", "direction", "]", "=", "Node", ".", "from_interval", "(", "interval", ")", "self", ".", "refresh_balance", "(", ")", "return", "self", "else", ":", "self", "[", "direction", "]", "=", "self", "[", "direction", "]", ".", "add", "(", "interval", ")", "return", "self", ".", "rotate", "(", ")" ]
Returns self after adding the interval and balancing.
[ "Returns", "self", "after", "adding", "the", "interval", "and", "balancing", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L188-L203
9,054
chaimleib/intervaltree
intervaltree/node.py
Node.remove
def remove(self, interval): """ Returns self after removing the interval and balancing. If interval is not present, raise ValueError. """ # since this is a list, called methods can set this to [1], # making it true done = [] return self.remove_interval_helper(interval, done, should_raise_error=True)
python
def remove(self, interval): """ Returns self after removing the interval and balancing. If interval is not present, raise ValueError. """ # since this is a list, called methods can set this to [1], # making it true done = [] return self.remove_interval_helper(interval, done, should_raise_error=True)
[ "def", "remove", "(", "self", ",", "interval", ")", ":", "# since this is a list, called methods can set this to [1],", "# making it true", "done", "=", "[", "]", "return", "self", ".", "remove_interval_helper", "(", "interval", ",", "done", ",", "should_raise_error", "=", "True", ")" ]
Returns self after removing the interval and balancing. If interval is not present, raise ValueError.
[ "Returns", "self", "after", "removing", "the", "interval", "and", "balancing", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L205-L214
9,055
chaimleib/intervaltree
intervaltree/node.py
Node.discard
def discard(self, interval): """ Returns self after removing interval and balancing. If interval is not present, do nothing. """ done = [] return self.remove_interval_helper(interval, done, should_raise_error=False)
python
def discard(self, interval): """ Returns self after removing interval and balancing. If interval is not present, do nothing. """ done = [] return self.remove_interval_helper(interval, done, should_raise_error=False)
[ "def", "discard", "(", "self", ",", "interval", ")", ":", "done", "=", "[", "]", "return", "self", ".", "remove_interval_helper", "(", "interval", ",", "done", ",", "should_raise_error", "=", "False", ")" ]
Returns self after removing interval and balancing. If interval is not present, do nothing.
[ "Returns", "self", "after", "removing", "interval", "and", "balancing", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L216-L223
9,056
chaimleib/intervaltree
intervaltree/node.py
Node.remove_interval_helper
def remove_interval_helper(self, interval, done, should_raise_error): """ Returns self after removing interval and balancing. If interval doesn't exist, raise ValueError. This method may set done to [1] to tell all callers that rebalancing has completed. See Eternally Confuzzled's jsw_remove_r function (lines 1-32) in his AVL tree article for reference. """ #trace = interval.begin == 347 and interval.end == 353 #if trace: print('\nRemoving from {} interval {}'.format( # self.x_center, interval)) if self.center_hit(interval): #if trace: print('Hit at {}'.format(self.x_center)) if not should_raise_error and interval not in self.s_center: done.append(1) #if trace: print('Doing nothing.') return self try: # raises error if interval not present - this is # desired. self.s_center.remove(interval) except: self.print_structure() raise KeyError(interval) if self.s_center: # keep this node done.append(1) # no rebalancing necessary #if trace: print('Removed, no rebalancing.') return self # If we reach here, no intervals are left in self.s_center. # So, prune self. return self.prune() else: # interval not in s_center direction = self.hit_branch(interval) if not self[direction]: if should_raise_error: raise ValueError done.append(1) return self #if trace: # print('Descending to {} branch'.format( # ['left', 'right'][direction] # )) self[direction] = self[direction].remove_interval_helper(interval, done, should_raise_error) # Clean up if not done: #if trace: # print('Rotating {}'.format(self.x_center)) # self.print_structure() return self.rotate() return self
python
def remove_interval_helper(self, interval, done, should_raise_error): """ Returns self after removing interval and balancing. If interval doesn't exist, raise ValueError. This method may set done to [1] to tell all callers that rebalancing has completed. See Eternally Confuzzled's jsw_remove_r function (lines 1-32) in his AVL tree article for reference. """ #trace = interval.begin == 347 and interval.end == 353 #if trace: print('\nRemoving from {} interval {}'.format( # self.x_center, interval)) if self.center_hit(interval): #if trace: print('Hit at {}'.format(self.x_center)) if not should_raise_error and interval not in self.s_center: done.append(1) #if trace: print('Doing nothing.') return self try: # raises error if interval not present - this is # desired. self.s_center.remove(interval) except: self.print_structure() raise KeyError(interval) if self.s_center: # keep this node done.append(1) # no rebalancing necessary #if trace: print('Removed, no rebalancing.') return self # If we reach here, no intervals are left in self.s_center. # So, prune self. return self.prune() else: # interval not in s_center direction = self.hit_branch(interval) if not self[direction]: if should_raise_error: raise ValueError done.append(1) return self #if trace: # print('Descending to {} branch'.format( # ['left', 'right'][direction] # )) self[direction] = self[direction].remove_interval_helper(interval, done, should_raise_error) # Clean up if not done: #if trace: # print('Rotating {}'.format(self.x_center)) # self.print_structure() return self.rotate() return self
[ "def", "remove_interval_helper", "(", "self", ",", "interval", ",", "done", ",", "should_raise_error", ")", ":", "#trace = interval.begin == 347 and interval.end == 353", "#if trace: print('\\nRemoving from {} interval {}'.format(", "# self.x_center, interval))", "if", "self", ".", "center_hit", "(", "interval", ")", ":", "#if trace: print('Hit at {}'.format(self.x_center))", "if", "not", "should_raise_error", "and", "interval", "not", "in", "self", ".", "s_center", ":", "done", ".", "append", "(", "1", ")", "#if trace: print('Doing nothing.')", "return", "self", "try", ":", "# raises error if interval not present - this is", "# desired.", "self", ".", "s_center", ".", "remove", "(", "interval", ")", "except", ":", "self", ".", "print_structure", "(", ")", "raise", "KeyError", "(", "interval", ")", "if", "self", ".", "s_center", ":", "# keep this node", "done", ".", "append", "(", "1", ")", "# no rebalancing necessary", "#if trace: print('Removed, no rebalancing.')", "return", "self", "# If we reach here, no intervals are left in self.s_center.", "# So, prune self.", "return", "self", ".", "prune", "(", ")", "else", ":", "# interval not in s_center", "direction", "=", "self", ".", "hit_branch", "(", "interval", ")", "if", "not", "self", "[", "direction", "]", ":", "if", "should_raise_error", ":", "raise", "ValueError", "done", ".", "append", "(", "1", ")", "return", "self", "#if trace:", "# print('Descending to {} branch'.format(", "# ['left', 'right'][direction]", "# ))", "self", "[", "direction", "]", "=", "self", "[", "direction", "]", ".", "remove_interval_helper", "(", "interval", ",", "done", ",", "should_raise_error", ")", "# Clean up", "if", "not", "done", ":", "#if trace:", "# print('Rotating {}'.format(self.x_center))", "# self.print_structure()", "return", "self", ".", "rotate", "(", ")", "return", "self" ]
Returns self after removing interval and balancing. If interval doesn't exist, raise ValueError. This method may set done to [1] to tell all callers that rebalancing has completed. See Eternally Confuzzled's jsw_remove_r function (lines 1-32) in his AVL tree article for reference.
[ "Returns", "self", "after", "removing", "interval", "and", "balancing", ".", "If", "interval", "doesn", "t", "exist", "raise", "ValueError", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L225-L281
9,057
chaimleib/intervaltree
intervaltree/node.py
Node.search_overlap
def search_overlap(self, point_list): """ Returns all intervals that overlap the point_list. """ result = set() for j in point_list: self.search_point(j, result) return result
python
def search_overlap(self, point_list): """ Returns all intervals that overlap the point_list. """ result = set() for j in point_list: self.search_point(j, result) return result
[ "def", "search_overlap", "(", "self", ",", "point_list", ")", ":", "result", "=", "set", "(", ")", "for", "j", "in", "point_list", ":", "self", ".", "search_point", "(", "j", ",", "result", ")", "return", "result" ]
Returns all intervals that overlap the point_list.
[ "Returns", "all", "intervals", "that", "overlap", "the", "point_list", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L283-L290
9,058
chaimleib/intervaltree
intervaltree/node.py
Node.search_point
def search_point(self, point, result): """ Returns all intervals that contain point. """ for k in self.s_center: if k.begin <= point < k.end: result.add(k) if point < self.x_center and self[0]: return self[0].search_point(point, result) elif point > self.x_center and self[1]: return self[1].search_point(point, result) return result
python
def search_point(self, point, result): """ Returns all intervals that contain point. """ for k in self.s_center: if k.begin <= point < k.end: result.add(k) if point < self.x_center and self[0]: return self[0].search_point(point, result) elif point > self.x_center and self[1]: return self[1].search_point(point, result) return result
[ "def", "search_point", "(", "self", ",", "point", ",", "result", ")", ":", "for", "k", "in", "self", ".", "s_center", ":", "if", "k", ".", "begin", "<=", "point", "<", "k", ".", "end", ":", "result", ".", "add", "(", "k", ")", "if", "point", "<", "self", ".", "x_center", "and", "self", "[", "0", "]", ":", "return", "self", "[", "0", "]", ".", "search_point", "(", "point", ",", "result", ")", "elif", "point", ">", "self", ".", "x_center", "and", "self", "[", "1", "]", ":", "return", "self", "[", "1", "]", ".", "search_point", "(", "point", ",", "result", ")", "return", "result" ]
Returns all intervals that contain point.
[ "Returns", "all", "intervals", "that", "contain", "point", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L292-L303
9,059
chaimleib/intervaltree
intervaltree/node.py
Node.prune
def prune(self): """ On a subtree where the root node's s_center is empty, return a new subtree with no empty s_centers. """ if not self[0] or not self[1]: # if I have an empty branch direction = not self[0] # graft the other branch here #if trace: # print('Grafting {} branch'.format( # 'right' if direction else 'left')) result = self[direction] #if result: result.verify() return result else: # Replace the root node with the greatest predecessor. heir, self[0] = self[0].pop_greatest_child() #if trace: # print('Replacing {} with {}.'.format( # self.x_center, heir.x_center # )) # print('Removed greatest predecessor:') # self.print_structure() #if self[0]: self[0].verify() #if self[1]: self[1].verify() # Set up the heir as the new root node (heir[0], heir[1]) = (self[0], self[1]) #if trace: print('Setting up the heir:') #if trace: heir.print_structure() # popping the predecessor may have unbalanced this node; # fix it heir.refresh_balance() heir = heir.rotate() #heir.verify() #if trace: print('Rotated the heir:') #if trace: heir.print_structure() return heir
python
def prune(self): """ On a subtree where the root node's s_center is empty, return a new subtree with no empty s_centers. """ if not self[0] or not self[1]: # if I have an empty branch direction = not self[0] # graft the other branch here #if trace: # print('Grafting {} branch'.format( # 'right' if direction else 'left')) result = self[direction] #if result: result.verify() return result else: # Replace the root node with the greatest predecessor. heir, self[0] = self[0].pop_greatest_child() #if trace: # print('Replacing {} with {}.'.format( # self.x_center, heir.x_center # )) # print('Removed greatest predecessor:') # self.print_structure() #if self[0]: self[0].verify() #if self[1]: self[1].verify() # Set up the heir as the new root node (heir[0], heir[1]) = (self[0], self[1]) #if trace: print('Setting up the heir:') #if trace: heir.print_structure() # popping the predecessor may have unbalanced this node; # fix it heir.refresh_balance() heir = heir.rotate() #heir.verify() #if trace: print('Rotated the heir:') #if trace: heir.print_structure() return heir
[ "def", "prune", "(", "self", ")", ":", "if", "not", "self", "[", "0", "]", "or", "not", "self", "[", "1", "]", ":", "# if I have an empty branch", "direction", "=", "not", "self", "[", "0", "]", "# graft the other branch here", "#if trace:", "# print('Grafting {} branch'.format(", "# 'right' if direction else 'left'))", "result", "=", "self", "[", "direction", "]", "#if result: result.verify()", "return", "result", "else", ":", "# Replace the root node with the greatest predecessor.", "heir", ",", "self", "[", "0", "]", "=", "self", "[", "0", "]", ".", "pop_greatest_child", "(", ")", "#if trace:", "# print('Replacing {} with {}.'.format(", "# self.x_center, heir.x_center", "# ))", "# print('Removed greatest predecessor:')", "# self.print_structure()", "#if self[0]: self[0].verify()", "#if self[1]: self[1].verify()", "# Set up the heir as the new root node", "(", "heir", "[", "0", "]", ",", "heir", "[", "1", "]", ")", "=", "(", "self", "[", "0", "]", ",", "self", "[", "1", "]", ")", "#if trace: print('Setting up the heir:')", "#if trace: heir.print_structure()", "# popping the predecessor may have unbalanced this node;", "# fix it", "heir", ".", "refresh_balance", "(", ")", "heir", "=", "heir", ".", "rotate", "(", ")", "#heir.verify()", "#if trace: print('Rotated the heir:')", "#if trace: heir.print_structure()", "return", "heir" ]
On a subtree where the root node's s_center is empty, return a new subtree with no empty s_centers.
[ "On", "a", "subtree", "where", "the", "root", "node", "s", "s_center", "is", "empty", "return", "a", "new", "subtree", "with", "no", "empty", "s_centers", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L305-L344
9,060
chaimleib/intervaltree
intervaltree/node.py
Node.contains_point
def contains_point(self, p): """ Returns whether this node or a child overlaps p. """ for iv in self.s_center: if iv.contains_point(p): return True branch = self[p > self.x_center] return branch and branch.contains_point(p)
python
def contains_point(self, p): """ Returns whether this node or a child overlaps p. """ for iv in self.s_center: if iv.contains_point(p): return True branch = self[p > self.x_center] return branch and branch.contains_point(p)
[ "def", "contains_point", "(", "self", ",", "p", ")", ":", "for", "iv", "in", "self", ".", "s_center", ":", "if", "iv", ".", "contains_point", "(", "p", ")", ":", "return", "True", "branch", "=", "self", "[", "p", ">", "self", ".", "x_center", "]", "return", "branch", "and", "branch", ".", "contains_point", "(", "p", ")" ]
Returns whether this node or a child overlaps p.
[ "Returns", "whether", "this", "node", "or", "a", "child", "overlaps", "p", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L425-L433
9,061
chaimleib/intervaltree
intervaltree/node.py
Node.print_structure
def print_structure(self, indent=0, tostring=False): """ For debugging. """ nl = '\n' sp = indent * ' ' rlist = [str(self) + nl] if self.s_center: for iv in sorted(self.s_center): rlist.append(sp + ' ' + repr(iv) + nl) if self.left_node: rlist.append(sp + '<: ') # no CR rlist.append(self.left_node.print_structure(indent + 1, True)) if self.right_node: rlist.append(sp + '>: ') # no CR rlist.append(self.right_node.print_structure(indent + 1, True)) result = ''.join(rlist) if tostring: return result else: print(result)
python
def print_structure(self, indent=0, tostring=False): """ For debugging. """ nl = '\n' sp = indent * ' ' rlist = [str(self) + nl] if self.s_center: for iv in sorted(self.s_center): rlist.append(sp + ' ' + repr(iv) + nl) if self.left_node: rlist.append(sp + '<: ') # no CR rlist.append(self.left_node.print_structure(indent + 1, True)) if self.right_node: rlist.append(sp + '>: ') # no CR rlist.append(self.right_node.print_structure(indent + 1, True)) result = ''.join(rlist) if tostring: return result else: print(result)
[ "def", "print_structure", "(", "self", ",", "indent", "=", "0", ",", "tostring", "=", "False", ")", ":", "nl", "=", "'\\n'", "sp", "=", "indent", "*", "' '", "rlist", "=", "[", "str", "(", "self", ")", "+", "nl", "]", "if", "self", ".", "s_center", ":", "for", "iv", "in", "sorted", "(", "self", ".", "s_center", ")", ":", "rlist", ".", "append", "(", "sp", "+", "' '", "+", "repr", "(", "iv", ")", "+", "nl", ")", "if", "self", ".", "left_node", ":", "rlist", ".", "append", "(", "sp", "+", "'<: '", ")", "# no CR", "rlist", ".", "append", "(", "self", ".", "left_node", ".", "print_structure", "(", "indent", "+", "1", ",", "True", ")", ")", "if", "self", ".", "right_node", ":", "rlist", ".", "append", "(", "sp", "+", "'>: '", ")", "# no CR", "rlist", ".", "append", "(", "self", ".", "right_node", ".", "print_structure", "(", "indent", "+", "1", ",", "True", ")", ")", "result", "=", "''", ".", "join", "(", "rlist", ")", "if", "tostring", ":", "return", "result", "else", ":", "print", "(", "result", ")" ]
For debugging.
[ "For", "debugging", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L572-L593
9,062
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.from_tuples
def from_tuples(cls, tups): """ Create a new IntervalTree from an iterable of 2- or 3-tuples, where the tuple lists begin, end, and optionally data. """ ivs = [Interval(*t) for t in tups] return IntervalTree(ivs)
python
def from_tuples(cls, tups): """ Create a new IntervalTree from an iterable of 2- or 3-tuples, where the tuple lists begin, end, and optionally data. """ ivs = [Interval(*t) for t in tups] return IntervalTree(ivs)
[ "def", "from_tuples", "(", "cls", ",", "tups", ")", ":", "ivs", "=", "[", "Interval", "(", "*", "t", ")", "for", "t", "in", "tups", "]", "return", "IntervalTree", "(", "ivs", ")" ]
Create a new IntervalTree from an iterable of 2- or 3-tuples, where the tuple lists begin, end, and optionally data.
[ "Create", "a", "new", "IntervalTree", "from", "an", "iterable", "of", "2", "-", "or", "3", "-", "tuples", "where", "the", "tuple", "lists", "begin", "end", "and", "optionally", "data", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L244-L250
9,063
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree._add_boundaries
def _add_boundaries(self, interval): """ Records the boundaries of the interval in the boundary table. """ begin = interval.begin end = interval.end if begin in self.boundary_table: self.boundary_table[begin] += 1 else: self.boundary_table[begin] = 1 if end in self.boundary_table: self.boundary_table[end] += 1 else: self.boundary_table[end] = 1
python
def _add_boundaries(self, interval): """ Records the boundaries of the interval in the boundary table. """ begin = interval.begin end = interval.end if begin in self.boundary_table: self.boundary_table[begin] += 1 else: self.boundary_table[begin] = 1 if end in self.boundary_table: self.boundary_table[end] += 1 else: self.boundary_table[end] = 1
[ "def", "_add_boundaries", "(", "self", ",", "interval", ")", ":", "begin", "=", "interval", ".", "begin", "end", "=", "interval", ".", "end", "if", "begin", "in", "self", ".", "boundary_table", ":", "self", ".", "boundary_table", "[", "begin", "]", "+=", "1", "else", ":", "self", ".", "boundary_table", "[", "begin", "]", "=", "1", "if", "end", "in", "self", ".", "boundary_table", ":", "self", ".", "boundary_table", "[", "end", "]", "+=", "1", "else", ":", "self", ".", "boundary_table", "[", "end", "]", "=", "1" ]
Records the boundaries of the interval in the boundary table.
[ "Records", "the", "boundaries", "of", "the", "interval", "in", "the", "boundary", "table", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L282-L296
9,064
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree._remove_boundaries
def _remove_boundaries(self, interval): """ Removes the boundaries of the interval from the boundary table. """ begin = interval.begin end = interval.end if self.boundary_table[begin] == 1: del self.boundary_table[begin] else: self.boundary_table[begin] -= 1 if self.boundary_table[end] == 1: del self.boundary_table[end] else: self.boundary_table[end] -= 1
python
def _remove_boundaries(self, interval): """ Removes the boundaries of the interval from the boundary table. """ begin = interval.begin end = interval.end if self.boundary_table[begin] == 1: del self.boundary_table[begin] else: self.boundary_table[begin] -= 1 if self.boundary_table[end] == 1: del self.boundary_table[end] else: self.boundary_table[end] -= 1
[ "def", "_remove_boundaries", "(", "self", ",", "interval", ")", ":", "begin", "=", "interval", ".", "begin", "end", "=", "interval", ".", "end", "if", "self", ".", "boundary_table", "[", "begin", "]", "==", "1", ":", "del", "self", ".", "boundary_table", "[", "begin", "]", "else", ":", "self", ".", "boundary_table", "[", "begin", "]", "-=", "1", "if", "self", ".", "boundary_table", "[", "end", "]", "==", "1", ":", "del", "self", ".", "boundary_table", "[", "end", "]", "else", ":", "self", ".", "boundary_table", "[", "end", "]", "-=", "1" ]
Removes the boundaries of the interval from the boundary table.
[ "Removes", "the", "boundaries", "of", "the", "interval", "from", "the", "boundary", "table", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L298-L312
9,065
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.add
def add(self, interval): """ Adds an interval to the tree, if not already present. Completes in O(log n) time. """ if interval in self: return if interval.is_null(): raise ValueError( "IntervalTree: Null Interval objects not allowed in IntervalTree:" " {0}".format(interval) ) if not self.top_node: self.top_node = Node.from_interval(interval) else: self.top_node = self.top_node.add(interval) self.all_intervals.add(interval) self._add_boundaries(interval)
python
def add(self, interval): """ Adds an interval to the tree, if not already present. Completes in O(log n) time. """ if interval in self: return if interval.is_null(): raise ValueError( "IntervalTree: Null Interval objects not allowed in IntervalTree:" " {0}".format(interval) ) if not self.top_node: self.top_node = Node.from_interval(interval) else: self.top_node = self.top_node.add(interval) self.all_intervals.add(interval) self._add_boundaries(interval)
[ "def", "add", "(", "self", ",", "interval", ")", ":", "if", "interval", "in", "self", ":", "return", "if", "interval", ".", "is_null", "(", ")", ":", "raise", "ValueError", "(", "\"IntervalTree: Null Interval objects not allowed in IntervalTree:\"", "\" {0}\"", ".", "format", "(", "interval", ")", ")", "if", "not", "self", ".", "top_node", ":", "self", ".", "top_node", "=", "Node", ".", "from_interval", "(", "interval", ")", "else", ":", "self", ".", "top_node", "=", "self", ".", "top_node", ".", "add", "(", "interval", ")", "self", ".", "all_intervals", ".", "add", "(", "interval", ")", "self", ".", "_add_boundaries", "(", "interval", ")" ]
Adds an interval to the tree, if not already present. Completes in O(log n) time.
[ "Adds", "an", "interval", "to", "the", "tree", "if", "not", "already", "present", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L314-L334
9,066
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.remove
def remove(self, interval): """ Removes an interval from the tree, if present. If not, raises ValueError. Completes in O(log n) time. """ #self.verify() if interval not in self: #print(self.all_intervals) raise ValueError self.top_node = self.top_node.remove(interval) self.all_intervals.remove(interval) self._remove_boundaries(interval)
python
def remove(self, interval): """ Removes an interval from the tree, if present. If not, raises ValueError. Completes in O(log n) time. """ #self.verify() if interval not in self: #print(self.all_intervals) raise ValueError self.top_node = self.top_node.remove(interval) self.all_intervals.remove(interval) self._remove_boundaries(interval)
[ "def", "remove", "(", "self", ",", "interval", ")", ":", "#self.verify()", "if", "interval", "not", "in", "self", ":", "#print(self.all_intervals)", "raise", "ValueError", "self", ".", "top_node", "=", "self", ".", "top_node", ".", "remove", "(", "interval", ")", "self", ".", "all_intervals", ".", "remove", "(", "interval", ")", "self", ".", "_remove_boundaries", "(", "interval", ")" ]
Removes an interval from the tree, if present. If not, raises ValueError. Completes in O(log n) time.
[ "Removes", "an", "interval", "from", "the", "tree", "if", "present", ".", "If", "not", "raises", "ValueError", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L356-L369
9,067
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.discard
def discard(self, interval): """ Removes an interval from the tree, if present. If not, does nothing. Completes in O(log n) time. """ if interval not in self: return self.all_intervals.discard(interval) self.top_node = self.top_node.discard(interval) self._remove_boundaries(interval)
python
def discard(self, interval): """ Removes an interval from the tree, if present. If not, does nothing. Completes in O(log n) time. """ if interval not in self: return self.all_intervals.discard(interval) self.top_node = self.top_node.discard(interval) self._remove_boundaries(interval)
[ "def", "discard", "(", "self", ",", "interval", ")", ":", "if", "interval", "not", "in", "self", ":", "return", "self", ".", "all_intervals", ".", "discard", "(", "interval", ")", "self", ".", "top_node", "=", "self", ".", "top_node", ".", "discard", "(", "interval", ")", "self", ".", "_remove_boundaries", "(", "interval", ")" ]
Removes an interval from the tree, if present. If not, does nothing. Completes in O(log n) time.
[ "Removes", "an", "interval", "from", "the", "tree", "if", "present", ".", "If", "not", "does", "nothing", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L380-L391
9,068
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.difference
def difference(self, other): """ Returns a new tree, comprising all intervals in self but not in other. """ ivs = set() for iv in self: if iv not in other: ivs.add(iv) return IntervalTree(ivs)
python
def difference(self, other): """ Returns a new tree, comprising all intervals in self but not in other. """ ivs = set() for iv in self: if iv not in other: ivs.add(iv) return IntervalTree(ivs)
[ "def", "difference", "(", "self", ",", "other", ")", ":", "ivs", "=", "set", "(", ")", "for", "iv", "in", "self", ":", "if", "iv", "not", "in", "other", ":", "ivs", ".", "add", "(", "iv", ")", "return", "IntervalTree", "(", "ivs", ")" ]
Returns a new tree, comprising all intervals in self but not in other.
[ "Returns", "a", "new", "tree", "comprising", "all", "intervals", "in", "self", "but", "not", "in", "other", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L401-L410
9,069
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.intersection
def intersection(self, other): """ Returns a new tree of all intervals common to both self and other. """ ivs = set() shorter, longer = sorted([self, other], key=len) for iv in shorter: if iv in longer: ivs.add(iv) return IntervalTree(ivs)
python
def intersection(self, other): """ Returns a new tree of all intervals common to both self and other. """ ivs = set() shorter, longer = sorted([self, other], key=len) for iv in shorter: if iv in longer: ivs.add(iv) return IntervalTree(ivs)
[ "def", "intersection", "(", "self", ",", "other", ")", ":", "ivs", "=", "set", "(", ")", "shorter", ",", "longer", "=", "sorted", "(", "[", "self", ",", "other", "]", ",", "key", "=", "len", ")", "for", "iv", "in", "shorter", ":", "if", "iv", "in", "longer", ":", "ivs", ".", "add", "(", "iv", ")", "return", "IntervalTree", "(", "ivs", ")" ]
Returns a new tree of all intervals common to both self and other.
[ "Returns", "a", "new", "tree", "of", "all", "intervals", "common", "to", "both", "self", "and", "other", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L426-L436
9,070
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.intersection_update
def intersection_update(self, other): """ Removes intervals from self unless they also exist in other. """ ivs = list(self) for iv in ivs: if iv not in other: self.remove(iv)
python
def intersection_update(self, other): """ Removes intervals from self unless they also exist in other. """ ivs = list(self) for iv in ivs: if iv not in other: self.remove(iv)
[ "def", "intersection_update", "(", "self", ",", "other", ")", ":", "ivs", "=", "list", "(", "self", ")", "for", "iv", "in", "ivs", ":", "if", "iv", "not", "in", "other", ":", "self", ".", "remove", "(", "iv", ")" ]
Removes intervals from self unless they also exist in other.
[ "Removes", "intervals", "from", "self", "unless", "they", "also", "exist", "in", "other", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L438-L445
9,071
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.symmetric_difference
def symmetric_difference(self, other): """ Return a tree with elements only in self or other but not both. """ if not isinstance(other, set): other = set(other) me = set(self) ivs = me.difference(other).union(other.difference(me)) return IntervalTree(ivs)
python
def symmetric_difference(self, other): """ Return a tree with elements only in self or other but not both. """ if not isinstance(other, set): other = set(other) me = set(self) ivs = me.difference(other).union(other.difference(me)) return IntervalTree(ivs)
[ "def", "symmetric_difference", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "set", ")", ":", "other", "=", "set", "(", "other", ")", "me", "=", "set", "(", "self", ")", "ivs", "=", "me", ".", "difference", "(", "other", ")", ".", "union", "(", "other", ".", "difference", "(", "me", ")", ")", "return", "IntervalTree", "(", "ivs", ")" ]
Return a tree with elements only in self or other but not both.
[ "Return", "a", "tree", "with", "elements", "only", "in", "self", "or", "other", "but", "not", "both", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L447-L455
9,072
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.symmetric_difference_update
def symmetric_difference_update(self, other): """ Throws out all intervals except those only in self or other, not both. """ other = set(other) ivs = list(self) for iv in ivs: if iv in other: self.remove(iv) other.remove(iv) self.update(other)
python
def symmetric_difference_update(self, other): """ Throws out all intervals except those only in self or other, not both. """ other = set(other) ivs = list(self) for iv in ivs: if iv in other: self.remove(iv) other.remove(iv) self.update(other)
[ "def", "symmetric_difference_update", "(", "self", ",", "other", ")", ":", "other", "=", "set", "(", "other", ")", "ivs", "=", "list", "(", "self", ")", "for", "iv", "in", "ivs", ":", "if", "iv", "in", "other", ":", "self", ".", "remove", "(", "iv", ")", "other", ".", "remove", "(", "iv", ")", "self", ".", "update", "(", "other", ")" ]
Throws out all intervals except those only in self or other, not both.
[ "Throws", "out", "all", "intervals", "except", "those", "only", "in", "self", "or", "other", "not", "both", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L457-L468
9,073
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.remove_overlap
def remove_overlap(self, begin, end=None): """ Removes all intervals overlapping the given point or range. Completes in O((r+m)*log n) time, where: * n = size of the tree * m = number of matches * r = size of the search range (this is 1 for a point) """ hitlist = self.at(begin) if end is None else self.overlap(begin, end) for iv in hitlist: self.remove(iv)
python
def remove_overlap(self, begin, end=None): """ Removes all intervals overlapping the given point or range. Completes in O((r+m)*log n) time, where: * n = size of the tree * m = number of matches * r = size of the search range (this is 1 for a point) """ hitlist = self.at(begin) if end is None else self.overlap(begin, end) for iv in hitlist: self.remove(iv)
[ "def", "remove_overlap", "(", "self", ",", "begin", ",", "end", "=", "None", ")", ":", "hitlist", "=", "self", ".", "at", "(", "begin", ")", "if", "end", "is", "None", "else", "self", ".", "overlap", "(", "begin", ",", "end", ")", "for", "iv", "in", "hitlist", ":", "self", ".", "remove", "(", "iv", ")" ]
Removes all intervals overlapping the given point or range. Completes in O((r+m)*log n) time, where: * n = size of the tree * m = number of matches * r = size of the search range (this is 1 for a point)
[ "Removes", "all", "intervals", "overlapping", "the", "given", "point", "or", "range", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L470-L481
9,074
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.remove_envelop
def remove_envelop(self, begin, end): """ Removes all intervals completely enveloped in the given range. Completes in O((r+m)*log n) time, where: * n = size of the tree * m = number of matches * r = size of the search range """ hitlist = self.envelop(begin, end) for iv in hitlist: self.remove(iv)
python
def remove_envelop(self, begin, end): """ Removes all intervals completely enveloped in the given range. Completes in O((r+m)*log n) time, where: * n = size of the tree * m = number of matches * r = size of the search range """ hitlist = self.envelop(begin, end) for iv in hitlist: self.remove(iv)
[ "def", "remove_envelop", "(", "self", ",", "begin", ",", "end", ")", ":", "hitlist", "=", "self", ".", "envelop", "(", "begin", ",", "end", ")", "for", "iv", "in", "hitlist", ":", "self", ".", "remove", "(", "iv", ")" ]
Removes all intervals completely enveloped in the given range. Completes in O((r+m)*log n) time, where: * n = size of the tree * m = number of matches * r = size of the search range
[ "Removes", "all", "intervals", "completely", "enveloped", "in", "the", "given", "range", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L483-L494
9,075
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.find_nested
def find_nested(self): """ Returns a dictionary mapping parent intervals to sets of intervals overlapped by and contained in the parent. Completes in O(n^2) time. :rtype: dict of [Interval, set of Interval] """ result = {} def add_if_nested(): if parent.contains_interval(child): if parent not in result: result[parent] = set() result[parent].add(child) long_ivs = sorted(self.all_intervals, key=Interval.length, reverse=True) for i, parent in enumerate(long_ivs): for child in long_ivs[i + 1:]: add_if_nested() return result
python
def find_nested(self): """ Returns a dictionary mapping parent intervals to sets of intervals overlapped by and contained in the parent. Completes in O(n^2) time. :rtype: dict of [Interval, set of Interval] """ result = {} def add_if_nested(): if parent.contains_interval(child): if parent not in result: result[parent] = set() result[parent].add(child) long_ivs = sorted(self.all_intervals, key=Interval.length, reverse=True) for i, parent in enumerate(long_ivs): for child in long_ivs[i + 1:]: add_if_nested() return result
[ "def", "find_nested", "(", "self", ")", ":", "result", "=", "{", "}", "def", "add_if_nested", "(", ")", ":", "if", "parent", ".", "contains_interval", "(", "child", ")", ":", "if", "parent", "not", "in", "result", ":", "result", "[", "parent", "]", "=", "set", "(", ")", "result", "[", "parent", "]", ".", "add", "(", "child", ")", "long_ivs", "=", "sorted", "(", "self", ".", "all_intervals", ",", "key", "=", "Interval", ".", "length", ",", "reverse", "=", "True", ")", "for", "i", ",", "parent", "in", "enumerate", "(", "long_ivs", ")", ":", "for", "child", "in", "long_ivs", "[", "i", "+", "1", ":", "]", ":", "add_if_nested", "(", ")", "return", "result" ]
Returns a dictionary mapping parent intervals to sets of intervals overlapped by and contained in the parent. Completes in O(n^2) time. :rtype: dict of [Interval, set of Interval]
[ "Returns", "a", "dictionary", "mapping", "parent", "intervals", "to", "sets", "of", "intervals", "overlapped", "by", "and", "contained", "in", "the", "parent", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L551-L571
9,076
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.overlaps
def overlaps(self, begin, end=None): """ Returns whether some interval in the tree overlaps the given point or range. Completes in O(r*log n) time, where r is the size of the search range. :rtype: bool """ if end is not None: return self.overlaps_range(begin, end) elif isinstance(begin, Number): return self.overlaps_point(begin) else: return self.overlaps_range(begin.begin, begin.end)
python
def overlaps(self, begin, end=None): """ Returns whether some interval in the tree overlaps the given point or range. Completes in O(r*log n) time, where r is the size of the search range. :rtype: bool """ if end is not None: return self.overlaps_range(begin, end) elif isinstance(begin, Number): return self.overlaps_point(begin) else: return self.overlaps_range(begin.begin, begin.end)
[ "def", "overlaps", "(", "self", ",", "begin", ",", "end", "=", "None", ")", ":", "if", "end", "is", "not", "None", ":", "return", "self", ".", "overlaps_range", "(", "begin", ",", "end", ")", "elif", "isinstance", "(", "begin", ",", "Number", ")", ":", "return", "self", ".", "overlaps_point", "(", "begin", ")", "else", ":", "return", "self", ".", "overlaps_range", "(", "begin", ".", "begin", ",", "begin", ".", "end", ")" ]
Returns whether some interval in the tree overlaps the given point or range. Completes in O(r*log n) time, where r is the size of the search range. :rtype: bool
[ "Returns", "whether", "some", "interval", "in", "the", "tree", "overlaps", "the", "given", "point", "or", "range", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L573-L587
9,077
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.overlaps_point
def overlaps_point(self, p): """ Returns whether some interval in the tree overlaps p. Completes in O(log n) time. :rtype: bool """ if self.is_empty(): return False return bool(self.top_node.contains_point(p))
python
def overlaps_point(self, p): """ Returns whether some interval in the tree overlaps p. Completes in O(log n) time. :rtype: bool """ if self.is_empty(): return False return bool(self.top_node.contains_point(p))
[ "def", "overlaps_point", "(", "self", ",", "p", ")", ":", "if", "self", ".", "is_empty", "(", ")", ":", "return", "False", "return", "bool", "(", "self", ".", "top_node", ".", "contains_point", "(", "p", ")", ")" ]
Returns whether some interval in the tree overlaps p. Completes in O(log n) time. :rtype: bool
[ "Returns", "whether", "some", "interval", "in", "the", "tree", "overlaps", "p", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L589-L598
9,078
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.overlaps_range
def overlaps_range(self, begin, end): """ Returns whether some interval in the tree overlaps the given range. Returns False if given a null interval over which to test. Completes in O(r*log n) time, where r is the range length and n is the table size. :rtype: bool """ if self.is_empty(): return False elif begin >= end: return False elif self.overlaps_point(begin): return True return any( self.overlaps_point(bound) for bound in self.boundary_table if begin < bound < end )
python
def overlaps_range(self, begin, end): """ Returns whether some interval in the tree overlaps the given range. Returns False if given a null interval over which to test. Completes in O(r*log n) time, where r is the range length and n is the table size. :rtype: bool """ if self.is_empty(): return False elif begin >= end: return False elif self.overlaps_point(begin): return True return any( self.overlaps_point(bound) for bound in self.boundary_table if begin < bound < end )
[ "def", "overlaps_range", "(", "self", ",", "begin", ",", "end", ")", ":", "if", "self", ".", "is_empty", "(", ")", ":", "return", "False", "elif", "begin", ">=", "end", ":", "return", "False", "elif", "self", ".", "overlaps_point", "(", "begin", ")", ":", "return", "True", "return", "any", "(", "self", ".", "overlaps_point", "(", "bound", ")", "for", "bound", "in", "self", ".", "boundary_table", "if", "begin", "<", "bound", "<", "end", ")" ]
Returns whether some interval in the tree overlaps the given range. Returns False if given a null interval over which to test. Completes in O(r*log n) time, where r is the range length and n is the table size. :rtype: bool
[ "Returns", "whether", "some", "interval", "in", "the", "tree", "overlaps", "the", "given", "range", ".", "Returns", "False", "if", "given", "a", "null", "interval", "over", "which", "to", "test", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L600-L620
9,079
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.split_overlaps
def split_overlaps(self): """ Finds all intervals with overlapping ranges and splits them along the range boundaries. Completes in worst-case O(n^2*log n) time (many interval boundaries are inside many intervals), best-case O(n*log n) time (small number of overlaps << n per interval). """ if not self: return if len(self.boundary_table) == 2: return bounds = sorted(self.boundary_table) # get bound locations new_ivs = set() for lbound, ubound in zip(bounds[:-1], bounds[1:]): for iv in self[lbound]: new_ivs.add(Interval(lbound, ubound, iv.data)) self.__init__(new_ivs)
python
def split_overlaps(self): """ Finds all intervals with overlapping ranges and splits them along the range boundaries. Completes in worst-case O(n^2*log n) time (many interval boundaries are inside many intervals), best-case O(n*log n) time (small number of overlaps << n per interval). """ if not self: return if len(self.boundary_table) == 2: return bounds = sorted(self.boundary_table) # get bound locations new_ivs = set() for lbound, ubound in zip(bounds[:-1], bounds[1:]): for iv in self[lbound]: new_ivs.add(Interval(lbound, ubound, iv.data)) self.__init__(new_ivs)
[ "def", "split_overlaps", "(", "self", ")", ":", "if", "not", "self", ":", "return", "if", "len", "(", "self", ".", "boundary_table", ")", "==", "2", ":", "return", "bounds", "=", "sorted", "(", "self", ".", "boundary_table", ")", "# get bound locations", "new_ivs", "=", "set", "(", ")", "for", "lbound", ",", "ubound", "in", "zip", "(", "bounds", "[", ":", "-", "1", "]", ",", "bounds", "[", "1", ":", "]", ")", ":", "for", "iv", "in", "self", "[", "lbound", "]", ":", "new_ivs", ".", "add", "(", "Interval", "(", "lbound", ",", "ubound", ",", "iv", ".", "data", ")", ")", "self", ".", "__init__", "(", "new_ivs", ")" ]
Finds all intervals with overlapping ranges and splits them along the range boundaries. Completes in worst-case O(n^2*log n) time (many interval boundaries are inside many intervals), best-case O(n*log n) time (small number of overlaps << n per interval).
[ "Finds", "all", "intervals", "with", "overlapping", "ranges", "and", "splits", "them", "along", "the", "range", "boundaries", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L622-L643
9,080
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.at
def at(self, p): """ Returns the set of all intervals that contain p. Completes in O(m + log n) time, where: * n = size of the tree * m = number of matches :rtype: set of Interval """ root = self.top_node if not root: return set() return root.search_point(p, set())
python
def at(self, p): """ Returns the set of all intervals that contain p. Completes in O(m + log n) time, where: * n = size of the tree * m = number of matches :rtype: set of Interval """ root = self.top_node if not root: return set() return root.search_point(p, set())
[ "def", "at", "(", "self", ",", "p", ")", ":", "root", "=", "self", ".", "top_node", "if", "not", "root", ":", "return", "set", "(", ")", "return", "root", ".", "search_point", "(", "p", ",", "set", "(", ")", ")" ]
Returns the set of all intervals that contain p. Completes in O(m + log n) time, where: * n = size of the tree * m = number of matches :rtype: set of Interval
[ "Returns", "the", "set", "of", "all", "intervals", "that", "contain", "p", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L788-L800
9,081
chaimleib/intervaltree
intervaltree/intervaltree.py
IntervalTree.envelop
def envelop(self, begin, end=None): """ Returns the set of all intervals fully contained in the range [begin, end). Completes in O(m + k*log n) time, where: * n = size of the tree * m = number of matches * k = size of the search range :rtype: set of Interval """ root = self.top_node if not root: return set() if end is None: iv = begin return self.envelop(iv.begin, iv.end) elif begin >= end: return set() result = root.search_point(begin, set()) # bound_begin might be greater boundary_table = self.boundary_table bound_begin = boundary_table.bisect_left(begin) bound_end = boundary_table.bisect_left(end) # up to, but not including end result.update(root.search_overlap( # slice notation is slightly slower boundary_table.keys()[index] for index in xrange(bound_begin, bound_end) )) # TODO: improve envelop() to use node info instead of less-efficient filtering result = set( iv for iv in result if iv.begin >= begin and iv.end <= end ) return result
python
def envelop(self, begin, end=None): """ Returns the set of all intervals fully contained in the range [begin, end). Completes in O(m + k*log n) time, where: * n = size of the tree * m = number of matches * k = size of the search range :rtype: set of Interval """ root = self.top_node if not root: return set() if end is None: iv = begin return self.envelop(iv.begin, iv.end) elif begin >= end: return set() result = root.search_point(begin, set()) # bound_begin might be greater boundary_table = self.boundary_table bound_begin = boundary_table.bisect_left(begin) bound_end = boundary_table.bisect_left(end) # up to, but not including end result.update(root.search_overlap( # slice notation is slightly slower boundary_table.keys()[index] for index in xrange(bound_begin, bound_end) )) # TODO: improve envelop() to use node info instead of less-efficient filtering result = set( iv for iv in result if iv.begin >= begin and iv.end <= end ) return result
[ "def", "envelop", "(", "self", ",", "begin", ",", "end", "=", "None", ")", ":", "root", "=", "self", ".", "top_node", "if", "not", "root", ":", "return", "set", "(", ")", "if", "end", "is", "None", ":", "iv", "=", "begin", "return", "self", ".", "envelop", "(", "iv", ".", "begin", ",", "iv", ".", "end", ")", "elif", "begin", ">=", "end", ":", "return", "set", "(", ")", "result", "=", "root", ".", "search_point", "(", "begin", ",", "set", "(", ")", ")", "# bound_begin might be greater", "boundary_table", "=", "self", ".", "boundary_table", "bound_begin", "=", "boundary_table", ".", "bisect_left", "(", "begin", ")", "bound_end", "=", "boundary_table", ".", "bisect_left", "(", "end", ")", "# up to, but not including end", "result", ".", "update", "(", "root", ".", "search_overlap", "(", "# slice notation is slightly slower", "boundary_table", ".", "keys", "(", ")", "[", "index", "]", "for", "index", "in", "xrange", "(", "bound_begin", ",", "bound_end", ")", ")", ")", "# TODO: improve envelop() to use node info instead of less-efficient filtering", "result", "=", "set", "(", "iv", "for", "iv", "in", "result", "if", "iv", ".", "begin", ">=", "begin", "and", "iv", ".", "end", "<=", "end", ")", "return", "result" ]
Returns the set of all intervals fully contained in the range [begin, end). Completes in O(m + k*log n) time, where: * n = size of the tree * m = number of matches * k = size of the search range :rtype: set of Interval
[ "Returns", "the", "set", "of", "all", "intervals", "fully", "contained", "in", "the", "range", "[", "begin", "end", ")", "." ]
ffb2b1667f8b832e89324a75a175be8440504c9d
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L802-L835
9,082
jazzband/inflect
inflect.py
engine.defnoun
def defnoun(self, singular, plural): """ Set the noun plural of singular to plural. """ self.checkpat(singular) self.checkpatplural(plural) self.pl_sb_user_defined.extend((singular, plural)) self.si_sb_user_defined.extend((plural, singular)) return 1
python
def defnoun(self, singular, plural): """ Set the noun plural of singular to plural. """ self.checkpat(singular) self.checkpatplural(plural) self.pl_sb_user_defined.extend((singular, plural)) self.si_sb_user_defined.extend((plural, singular)) return 1
[ "def", "defnoun", "(", "self", ",", "singular", ",", "plural", ")", ":", "self", ".", "checkpat", "(", "singular", ")", "self", ".", "checkpatplural", "(", "plural", ")", "self", ".", "pl_sb_user_defined", ".", "extend", "(", "(", "singular", ",", "plural", ")", ")", "self", ".", "si_sb_user_defined", ".", "extend", "(", "(", "plural", ",", "singular", ")", ")", "return", "1" ]
Set the noun plural of singular to plural.
[ "Set", "the", "noun", "plural", "of", "singular", "to", "plural", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L1951-L1960
9,083
jazzband/inflect
inflect.py
engine.defverb
def defverb(self, s1, p1, s2, p2, s3, p3): """ Set the verb plurals for s1, s2 and s3 to p1, p2 and p3 respectively. Where 1, 2 and 3 represent the 1st, 2nd and 3rd person forms of the verb. """ self.checkpat(s1) self.checkpat(s2) self.checkpat(s3) self.checkpatplural(p1) self.checkpatplural(p2) self.checkpatplural(p3) self.pl_v_user_defined.extend((s1, p1, s2, p2, s3, p3)) return 1
python
def defverb(self, s1, p1, s2, p2, s3, p3): """ Set the verb plurals for s1, s2 and s3 to p1, p2 and p3 respectively. Where 1, 2 and 3 represent the 1st, 2nd and 3rd person forms of the verb. """ self.checkpat(s1) self.checkpat(s2) self.checkpat(s3) self.checkpatplural(p1) self.checkpatplural(p2) self.checkpatplural(p3) self.pl_v_user_defined.extend((s1, p1, s2, p2, s3, p3)) return 1
[ "def", "defverb", "(", "self", ",", "s1", ",", "p1", ",", "s2", ",", "p2", ",", "s3", ",", "p3", ")", ":", "self", ".", "checkpat", "(", "s1", ")", "self", ".", "checkpat", "(", "s2", ")", "self", ".", "checkpat", "(", "s3", ")", "self", ".", "checkpatplural", "(", "p1", ")", "self", ".", "checkpatplural", "(", "p2", ")", "self", ".", "checkpatplural", "(", "p3", ")", "self", ".", "pl_v_user_defined", ".", "extend", "(", "(", "s1", ",", "p1", ",", "s2", ",", "p2", ",", "s3", ",", "p3", ")", ")", "return", "1" ]
Set the verb plurals for s1, s2 and s3 to p1, p2 and p3 respectively. Where 1, 2 and 3 represent the 1st, 2nd and 3rd person forms of the verb.
[ "Set", "the", "verb", "plurals", "for", "s1", "s2", "and", "s3", "to", "p1", "p2", "and", "p3", "respectively", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L1962-L1976
9,084
jazzband/inflect
inflect.py
engine.defadj
def defadj(self, singular, plural): """ Set the adjective plural of singular to plural. """ self.checkpat(singular) self.checkpatplural(plural) self.pl_adj_user_defined.extend((singular, plural)) return 1
python
def defadj(self, singular, plural): """ Set the adjective plural of singular to plural. """ self.checkpat(singular) self.checkpatplural(plural) self.pl_adj_user_defined.extend((singular, plural)) return 1
[ "def", "defadj", "(", "self", ",", "singular", ",", "plural", ")", ":", "self", ".", "checkpat", "(", "singular", ")", "self", ".", "checkpatplural", "(", "plural", ")", "self", ".", "pl_adj_user_defined", ".", "extend", "(", "(", "singular", ",", "plural", ")", ")", "return", "1" ]
Set the adjective plural of singular to plural.
[ "Set", "the", "adjective", "plural", "of", "singular", "to", "plural", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L1978-L1986
9,085
jazzband/inflect
inflect.py
engine.defa
def defa(self, pattern): """ Define the indefinate article as 'a' for words matching pattern. """ self.checkpat(pattern) self.A_a_user_defined.extend((pattern, "a")) return 1
python
def defa(self, pattern): """ Define the indefinate article as 'a' for words matching pattern. """ self.checkpat(pattern) self.A_a_user_defined.extend((pattern, "a")) return 1
[ "def", "defa", "(", "self", ",", "pattern", ")", ":", "self", ".", "checkpat", "(", "pattern", ")", "self", ".", "A_a_user_defined", ".", "extend", "(", "(", "pattern", ",", "\"a\"", ")", ")", "return", "1" ]
Define the indefinate article as 'a' for words matching pattern.
[ "Define", "the", "indefinate", "article", "as", "a", "for", "words", "matching", "pattern", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L1988-L1995
9,086
jazzband/inflect
inflect.py
engine.defan
def defan(self, pattern): """ Define the indefinate article as 'an' for words matching pattern. """ self.checkpat(pattern) self.A_a_user_defined.extend((pattern, "an")) return 1
python
def defan(self, pattern): """ Define the indefinate article as 'an' for words matching pattern. """ self.checkpat(pattern) self.A_a_user_defined.extend((pattern, "an")) return 1
[ "def", "defan", "(", "self", ",", "pattern", ")", ":", "self", ".", "checkpat", "(", "pattern", ")", "self", ".", "A_a_user_defined", ".", "extend", "(", "(", "pattern", ",", "\"an\"", ")", ")", "return", "1" ]
Define the indefinate article as 'an' for words matching pattern.
[ "Define", "the", "indefinate", "article", "as", "an", "for", "words", "matching", "pattern", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L1997-L2004
9,087
jazzband/inflect
inflect.py
engine.checkpat
def checkpat(self, pattern): """ check for errors in a regex pattern """ if pattern is None: return try: re.match(pattern, "") except re.error: print3("\nBad user-defined singular pattern:\n\t%s\n" % pattern) raise BadUserDefinedPatternError
python
def checkpat(self, pattern): """ check for errors in a regex pattern """ if pattern is None: return try: re.match(pattern, "") except re.error: print3("\nBad user-defined singular pattern:\n\t%s\n" % pattern) raise BadUserDefinedPatternError
[ "def", "checkpat", "(", "self", ",", "pattern", ")", ":", "if", "pattern", "is", "None", ":", "return", "try", ":", "re", ".", "match", "(", "pattern", ",", "\"\"", ")", "except", "re", ".", "error", ":", "print3", "(", "\"\\nBad user-defined singular pattern:\\n\\t%s\\n\"", "%", "pattern", ")", "raise", "BadUserDefinedPatternError" ]
check for errors in a regex pattern
[ "check", "for", "errors", "in", "a", "regex", "pattern" ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2006-L2016
9,088
jazzband/inflect
inflect.py
engine.classical
def classical(self, **kwargs): """ turn classical mode on and off for various categories turn on all classical modes: classical() classical(all=True) turn on or off specific claassical modes: e.g. classical(herd=True) classical(names=False) By default all classical modes are off except names. unknown value in args or key in kwargs rasies exception: UnknownClasicalModeError """ classical_mode = list(def_classical.keys()) if not kwargs: self.classical_dict = all_classical.copy() return if "all" in kwargs: if kwargs["all"]: self.classical_dict = all_classical.copy() else: self.classical_dict = no_classical.copy() for k, v in list(kwargs.items()): if k in classical_mode: self.classical_dict[k] = v else: raise UnknownClassicalModeError
python
def classical(self, **kwargs): """ turn classical mode on and off for various categories turn on all classical modes: classical() classical(all=True) turn on or off specific claassical modes: e.g. classical(herd=True) classical(names=False) By default all classical modes are off except names. unknown value in args or key in kwargs rasies exception: UnknownClasicalModeError """ classical_mode = list(def_classical.keys()) if not kwargs: self.classical_dict = all_classical.copy() return if "all" in kwargs: if kwargs["all"]: self.classical_dict = all_classical.copy() else: self.classical_dict = no_classical.copy() for k, v in list(kwargs.items()): if k in classical_mode: self.classical_dict[k] = v else: raise UnknownClassicalModeError
[ "def", "classical", "(", "self", ",", "*", "*", "kwargs", ")", ":", "classical_mode", "=", "list", "(", "def_classical", ".", "keys", "(", ")", ")", "if", "not", "kwargs", ":", "self", ".", "classical_dict", "=", "all_classical", ".", "copy", "(", ")", "return", "if", "\"all\"", "in", "kwargs", ":", "if", "kwargs", "[", "\"all\"", "]", ":", "self", ".", "classical_dict", "=", "all_classical", ".", "copy", "(", ")", "else", ":", "self", ".", "classical_dict", "=", "no_classical", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "list", "(", "kwargs", ".", "items", "(", ")", ")", ":", "if", "k", "in", "classical_mode", ":", "self", ".", "classical_dict", "[", "k", "]", "=", "v", "else", ":", "raise", "UnknownClassicalModeError" ]
turn classical mode on and off for various categories turn on all classical modes: classical() classical(all=True) turn on or off specific claassical modes: e.g. classical(herd=True) classical(names=False) By default all classical modes are off except names. unknown value in args or key in kwargs rasies exception: UnknownClasicalModeError
[ "turn", "classical", "mode", "on", "and", "off", "for", "various", "categories" ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2036-L2069
9,089
jazzband/inflect
inflect.py
engine.num
def num(self, count=None, show=None): # (;$count,$show) """ Set the number to be used in other method calls. Returns count. Set show to False to return '' instead. """ if count is not None: try: self.persistent_count = int(count) except ValueError: raise BadNumValueError if (show is None) or show: return str(count) else: self.persistent_count = None return ""
python
def num(self, count=None, show=None): # (;$count,$show) """ Set the number to be used in other method calls. Returns count. Set show to False to return '' instead. """ if count is not None: try: self.persistent_count = int(count) except ValueError: raise BadNumValueError if (show is None) or show: return str(count) else: self.persistent_count = None return ""
[ "def", "num", "(", "self", ",", "count", "=", "None", ",", "show", "=", "None", ")", ":", "# (;$count,$show)", "if", "count", "is", "not", "None", ":", "try", ":", "self", ".", "persistent_count", "=", "int", "(", "count", ")", "except", "ValueError", ":", "raise", "BadNumValueError", "if", "(", "show", "is", "None", ")", "or", "show", ":", "return", "str", "(", "count", ")", "else", ":", "self", ".", "persistent_count", "=", "None", "return", "\"\"" ]
Set the number to be used in other method calls. Returns count. Set show to False to return '' instead.
[ "Set", "the", "number", "to", "be", "used", "in", "other", "method", "calls", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2071-L2089
9,090
jazzband/inflect
inflect.py
engine._get_value_from_ast
def _get_value_from_ast(self, obj): """ Return the value of the ast object. """ if isinstance(obj, ast.Num): return obj.n elif isinstance(obj, ast.Str): return obj.s elif isinstance(obj, ast.List): return [self._get_value_from_ast(e) for e in obj.elts] elif isinstance(obj, ast.Tuple): return tuple([self._get_value_from_ast(e) for e in obj.elts]) # None, True and False are NameConstants in Py3.4 and above. elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant): return obj.value # For python versions below 3.4 elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]): return string_to_constant[obj.id] # Probably passed a variable name. # Or passed a single word without wrapping it in quotes as an argument # ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')") raise NameError("name '%s' is not defined" % obj.id)
python
def _get_value_from_ast(self, obj): """ Return the value of the ast object. """ if isinstance(obj, ast.Num): return obj.n elif isinstance(obj, ast.Str): return obj.s elif isinstance(obj, ast.List): return [self._get_value_from_ast(e) for e in obj.elts] elif isinstance(obj, ast.Tuple): return tuple([self._get_value_from_ast(e) for e in obj.elts]) # None, True and False are NameConstants in Py3.4 and above. elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant): return obj.value # For python versions below 3.4 elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]): return string_to_constant[obj.id] # Probably passed a variable name. # Or passed a single word without wrapping it in quotes as an argument # ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')") raise NameError("name '%s' is not defined" % obj.id)
[ "def", "_get_value_from_ast", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "ast", ".", "Num", ")", ":", "return", "obj", ".", "n", "elif", "isinstance", "(", "obj", ",", "ast", ".", "Str", ")", ":", "return", "obj", ".", "s", "elif", "isinstance", "(", "obj", ",", "ast", ".", "List", ")", ":", "return", "[", "self", ".", "_get_value_from_ast", "(", "e", ")", "for", "e", "in", "obj", ".", "elts", "]", "elif", "isinstance", "(", "obj", ",", "ast", ".", "Tuple", ")", ":", "return", "tuple", "(", "[", "self", ".", "_get_value_from_ast", "(", "e", ")", "for", "e", "in", "obj", ".", "elts", "]", ")", "# None, True and False are NameConstants in Py3.4 and above.", "elif", "sys", ".", "version_info", ".", "major", ">=", "3", "and", "isinstance", "(", "obj", ",", "ast", ".", "NameConstant", ")", ":", "return", "obj", ".", "value", "# For python versions below 3.4", "elif", "isinstance", "(", "obj", ",", "ast", ".", "Name", ")", "and", "(", "obj", ".", "id", "in", "[", "\"True\"", ",", "\"False\"", ",", "\"None\"", "]", ")", ":", "return", "string_to_constant", "[", "obj", ".", "id", "]", "# Probably passed a variable name.", "# Or passed a single word without wrapping it in quotes as an argument", "# ex: p.inflect(\"I plural(see)\") instead of p.inflect(\"I plural('see')\")", "raise", "NameError", "(", "\"name '%s' is not defined\"", "%", "obj", ".", "id", ")" ]
Return the value of the ast object.
[ "Return", "the", "value", "of", "the", "ast", "object", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2108-L2132
9,091
jazzband/inflect
inflect.py
engine._string_to_substitute
def _string_to_substitute(self, mo, methods_dict): """ Return the string to be substituted for the match. """ matched_text, f_name = mo.groups() # matched_text is the complete match string. e.g. plural_noun(cat) # f_name is the function name. e.g. plural_noun # Return matched_text if function name is not in methods_dict if f_name not in methods_dict: return matched_text # Parse the matched text a_tree = ast.parse(matched_text) # get the args and kwargs from ast objects args_list = [self._get_value_from_ast(a) for a in a_tree.body[0].value.args] kwargs_list = { kw.arg: self._get_value_from_ast(kw.value) for kw in a_tree.body[0].value.keywords } # Call the corresponding function return methods_dict[f_name](*args_list, **kwargs_list)
python
def _string_to_substitute(self, mo, methods_dict): """ Return the string to be substituted for the match. """ matched_text, f_name = mo.groups() # matched_text is the complete match string. e.g. plural_noun(cat) # f_name is the function name. e.g. plural_noun # Return matched_text if function name is not in methods_dict if f_name not in methods_dict: return matched_text # Parse the matched text a_tree = ast.parse(matched_text) # get the args and kwargs from ast objects args_list = [self._get_value_from_ast(a) for a in a_tree.body[0].value.args] kwargs_list = { kw.arg: self._get_value_from_ast(kw.value) for kw in a_tree.body[0].value.keywords } # Call the corresponding function return methods_dict[f_name](*args_list, **kwargs_list)
[ "def", "_string_to_substitute", "(", "self", ",", "mo", ",", "methods_dict", ")", ":", "matched_text", ",", "f_name", "=", "mo", ".", "groups", "(", ")", "# matched_text is the complete match string. e.g. plural_noun(cat)", "# f_name is the function name. e.g. plural_noun", "# Return matched_text if function name is not in methods_dict", "if", "f_name", "not", "in", "methods_dict", ":", "return", "matched_text", "# Parse the matched text", "a_tree", "=", "ast", ".", "parse", "(", "matched_text", ")", "# get the args and kwargs from ast objects", "args_list", "=", "[", "self", ".", "_get_value_from_ast", "(", "a", ")", "for", "a", "in", "a_tree", ".", "body", "[", "0", "]", ".", "value", ".", "args", "]", "kwargs_list", "=", "{", "kw", ".", "arg", ":", "self", ".", "_get_value_from_ast", "(", "kw", ".", "value", ")", "for", "kw", "in", "a_tree", ".", "body", "[", "0", "]", ".", "value", ".", "keywords", "}", "# Call the corresponding function", "return", "methods_dict", "[", "f_name", "]", "(", "*", "args_list", ",", "*", "*", "kwargs_list", ")" ]
Return the string to be substituted for the match.
[ "Return", "the", "string", "to", "be", "substituted", "for", "the", "match", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2134-L2157
9,092
jazzband/inflect
inflect.py
engine.inflect
def inflect(self, text): """ Perform inflections in a string. e.g. inflect('The plural of cat is plural(cat)') returns 'The plural of cat is cats' can use plural, plural_noun, plural_verb, plural_adj, singular_noun, a, an, no, ordinal, number_to_words, and prespart """ save_persistent_count = self.persistent_count # Dictionary of allowed methods methods_dict = { "plural": self.plural, "plural_adj": self.plural_adj, "plural_noun": self.plural_noun, "plural_verb": self.plural_verb, "singular_noun": self.singular_noun, "a": self.a, "an": self.a, "no": self.no, "ordinal": self.ordinal, "number_to_words": self.number_to_words, "present_participle": self.present_participle, "num": self.num, } # Regular expression to find Python's function call syntax functions_re = re.compile(r"((\w+)\([^)]*\)*)", re.IGNORECASE) output = functions_re.sub( lambda mo: self._string_to_substitute(mo, methods_dict), text ) self.persistent_count = save_persistent_count return output
python
def inflect(self, text): """ Perform inflections in a string. e.g. inflect('The plural of cat is plural(cat)') returns 'The plural of cat is cats' can use plural, plural_noun, plural_verb, plural_adj, singular_noun, a, an, no, ordinal, number_to_words, and prespart """ save_persistent_count = self.persistent_count # Dictionary of allowed methods methods_dict = { "plural": self.plural, "plural_adj": self.plural_adj, "plural_noun": self.plural_noun, "plural_verb": self.plural_verb, "singular_noun": self.singular_noun, "a": self.a, "an": self.a, "no": self.no, "ordinal": self.ordinal, "number_to_words": self.number_to_words, "present_participle": self.present_participle, "num": self.num, } # Regular expression to find Python's function call syntax functions_re = re.compile(r"((\w+)\([^)]*\)*)", re.IGNORECASE) output = functions_re.sub( lambda mo: self._string_to_substitute(mo, methods_dict), text ) self.persistent_count = save_persistent_count return output
[ "def", "inflect", "(", "self", ",", "text", ")", ":", "save_persistent_count", "=", "self", ".", "persistent_count", "# Dictionary of allowed methods", "methods_dict", "=", "{", "\"plural\"", ":", "self", ".", "plural", ",", "\"plural_adj\"", ":", "self", ".", "plural_adj", ",", "\"plural_noun\"", ":", "self", ".", "plural_noun", ",", "\"plural_verb\"", ":", "self", ".", "plural_verb", ",", "\"singular_noun\"", ":", "self", ".", "singular_noun", ",", "\"a\"", ":", "self", ".", "a", ",", "\"an\"", ":", "self", ".", "a", ",", "\"no\"", ":", "self", ".", "no", ",", "\"ordinal\"", ":", "self", ".", "ordinal", ",", "\"number_to_words\"", ":", "self", ".", "number_to_words", ",", "\"present_participle\"", ":", "self", ".", "present_participle", ",", "\"num\"", ":", "self", ".", "num", ",", "}", "# Regular expression to find Python's function call syntax", "functions_re", "=", "re", ".", "compile", "(", "r\"((\\w+)\\([^)]*\\)*)\"", ",", "re", ".", "IGNORECASE", ")", "output", "=", "functions_re", ".", "sub", "(", "lambda", "mo", ":", "self", ".", "_string_to_substitute", "(", "mo", ",", "methods_dict", ")", ",", "text", ")", "self", ".", "persistent_count", "=", "save_persistent_count", "return", "output" ]
Perform inflections in a string. e.g. inflect('The plural of cat is plural(cat)') returns 'The plural of cat is cats' can use plural, plural_noun, plural_verb, plural_adj, singular_noun, a, an, no, ordinal, number_to_words, and prespart
[ "Perform", "inflections", "in", "a", "string", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2161-L2197
9,093
jazzband/inflect
inflect.py
engine.plural
def plural(self, text, count=None): """ Return the plural of text. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess( word, self._pl_special_adjective(word, count) or self._pl_special_verb(word, count) or self._plnoun(word, count), ) return "{}{}{}".format(pre, plural, post)
python
def plural(self, text, count=None): """ Return the plural of text. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess( word, self._pl_special_adjective(word, count) or self._pl_special_verb(word, count) or self._plnoun(word, count), ) return "{}{}{}".format(pre, plural, post)
[ "def", "plural", "(", "self", ",", "text", ",", "count", "=", "None", ")", ":", "pre", ",", "word", ",", "post", "=", "self", ".", "partition_word", "(", "text", ")", "if", "not", "word", ":", "return", "text", "plural", "=", "self", ".", "postprocess", "(", "word", ",", "self", ".", "_pl_special_adjective", "(", "word", ",", "count", ")", "or", "self", ".", "_pl_special_verb", "(", "word", ",", "count", ")", "or", "self", ".", "_plnoun", "(", "word", ",", "count", ")", ",", ")", "return", "\"{}{}{}\"", ".", "format", "(", "pre", ",", "plural", ",", "post", ")" ]
Return the plural of text. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved.
[ "Return", "the", "plural", "of", "text", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2226-L2246
9,094
jazzband/inflect
inflect.py
engine.plural_noun
def plural_noun(self, text, count=None): """ Return the plural of text, where text is a noun. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess(word, self._plnoun(word, count)) return "{}{}{}".format(pre, plural, post)
python
def plural_noun(self, text, count=None): """ Return the plural of text, where text is a noun. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess(word, self._plnoun(word, count)) return "{}{}{}".format(pre, plural, post)
[ "def", "plural_noun", "(", "self", ",", "text", ",", "count", "=", "None", ")", ":", "pre", ",", "word", ",", "post", "=", "self", ".", "partition_word", "(", "text", ")", "if", "not", "word", ":", "return", "text", "plural", "=", "self", ".", "postprocess", "(", "word", ",", "self", ".", "_plnoun", "(", "word", ",", "count", ")", ")", "return", "\"{}{}{}\"", ".", "format", "(", "pre", ",", "plural", ",", "post", ")" ]
Return the plural of text, where text is a noun. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved.
[ "Return", "the", "plural", "of", "text", "where", "text", "is", "a", "noun", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2248-L2263
9,095
jazzband/inflect
inflect.py
engine.plural_verb
def plural_verb(self, text, count=None): """ Return the plural of text, where text is a verb. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess( word, self._pl_special_verb(word, count) or self._pl_general_verb(word, count), ) return "{}{}{}".format(pre, plural, post)
python
def plural_verb(self, text, count=None): """ Return the plural of text, where text is a verb. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess( word, self._pl_special_verb(word, count) or self._pl_general_verb(word, count), ) return "{}{}{}".format(pre, plural, post)
[ "def", "plural_verb", "(", "self", ",", "text", ",", "count", "=", "None", ")", ":", "pre", ",", "word", ",", "post", "=", "self", ".", "partition_word", "(", "text", ")", "if", "not", "word", ":", "return", "text", "plural", "=", "self", ".", "postprocess", "(", "word", ",", "self", ".", "_pl_special_verb", "(", "word", ",", "count", ")", "or", "self", ".", "_pl_general_verb", "(", "word", ",", "count", ")", ",", ")", "return", "\"{}{}{}\"", ".", "format", "(", "pre", ",", "plural", ",", "post", ")" ]
Return the plural of text, where text is a verb. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved.
[ "Return", "the", "plural", "of", "text", "where", "text", "is", "a", "verb", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2265-L2283
9,096
jazzband/inflect
inflect.py
engine.plural_adj
def plural_adj(self, text, count=None): """ Return the plural of text, where text is an adjective. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess(word, self._pl_special_adjective(word, count) or word) return "{}{}{}".format(pre, plural, post)
python
def plural_adj(self, text, count=None): """ Return the plural of text, where text is an adjective. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess(word, self._pl_special_adjective(word, count) or word) return "{}{}{}".format(pre, plural, post)
[ "def", "plural_adj", "(", "self", ",", "text", ",", "count", "=", "None", ")", ":", "pre", ",", "word", ",", "post", "=", "self", ".", "partition_word", "(", "text", ")", "if", "not", "word", ":", "return", "text", "plural", "=", "self", ".", "postprocess", "(", "word", ",", "self", ".", "_pl_special_adjective", "(", "word", ",", "count", ")", "or", "word", ")", "return", "\"{}{}{}\"", ".", "format", "(", "pre", ",", "plural", ",", "post", ")" ]
Return the plural of text, where text is an adjective. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved.
[ "Return", "the", "plural", "of", "text", "where", "text", "is", "an", "adjective", "." ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2285-L2300
9,097
jazzband/inflect
inflect.py
engine.compare
def compare(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise """ return ( self._plequal(word1, word2, self.plural_noun) or self._plequal(word1, word2, self.plural_verb) or self._plequal(word1, word2, self.plural_adj) )
python
def compare(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise """ return ( self._plequal(word1, word2, self.plural_noun) or self._plequal(word1, word2, self.plural_verb) or self._plequal(word1, word2, self.plural_adj) )
[ "def", "compare", "(", "self", ",", "word1", ",", "word2", ")", ":", "return", "(", "self", ".", "_plequal", "(", "word1", ",", "word2", ",", "self", ".", "plural_noun", ")", "or", "self", ".", "_plequal", "(", "word1", ",", "word2", ",", "self", ".", "plural_verb", ")", "or", "self", ".", "_plequal", "(", "word1", ",", "word2", ",", "self", ".", "plural_adj", ")", ")" ]
compare word1 and word2 for equality regardless of plurality return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise
[ "compare", "word1", "and", "word2", "for", "equality", "regardless", "of", "plurality" ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2302-L2318
9,098
jazzband/inflect
inflect.py
engine.compare_nouns
def compare_nouns(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as nouns return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise """ return self._plequal(word1, word2, self.plural_noun)
python
def compare_nouns(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as nouns return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise """ return self._plequal(word1, word2, self.plural_noun)
[ "def", "compare_nouns", "(", "self", ",", "word1", ",", "word2", ")", ":", "return", "self", ".", "_plequal", "(", "word1", ",", "word2", ",", "self", ".", "plural_noun", ")" ]
compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as nouns return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise
[ "compare", "word1", "and", "word2", "for", "equality", "regardless", "of", "plurality", "word1", "and", "word2", "are", "to", "be", "treated", "as", "nouns" ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2320-L2333
9,099
jazzband/inflect
inflect.py
engine.compare_verbs
def compare_verbs(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as verbs return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise """ return self._plequal(word1, word2, self.plural_verb)
python
def compare_verbs(self, word1, word2): """ compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as verbs return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise """ return self._plequal(word1, word2, self.plural_verb)
[ "def", "compare_verbs", "(", "self", ",", "word1", ",", "word2", ")", ":", "return", "self", ".", "_plequal", "(", "word1", ",", "word2", ",", "self", ".", "plural_verb", ")" ]
compare word1 and word2 for equality regardless of plurality word1 and word2 are to be treated as verbs return values: eq - the strings are equal p:s - word1 is the plural of word2 s:p - word2 is the plural of word1 p:p - word1 and word2 are two different plural forms of the one word False - otherwise
[ "compare", "word1", "and", "word2", "for", "equality", "regardless", "of", "plurality", "word1", "and", "word2", "are", "to", "be", "treated", "as", "verbs" ]
c2a3df74725990c195a5d7f37199de56873962e9
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2335-L2348