repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
oasis-open/cti-stix-validator
stix2validator/output.py
print_file_results
def print_file_results(file_result): """Print the results of validating a file. Args: file_result: A FileValidationResults instance. """ print_results_header(file_result.filepath, file_result.is_valid) for object_result in file_result.object_results: if object_result.warnings: print_warning_results(object_result, 1) if object_result.errors: print_schema_results(object_result, 1) if file_result.fatal: print_fatal_results(file_result.fatal, 1)
python
def print_file_results(file_result): """Print the results of validating a file. Args: file_result: A FileValidationResults instance. """ print_results_header(file_result.filepath, file_result.is_valid) for object_result in file_result.object_results: if object_result.warnings: print_warning_results(object_result, 1) if object_result.errors: print_schema_results(object_result, 1) if file_result.fatal: print_fatal_results(file_result.fatal, 1)
[ "def", "print_file_results", "(", "file_result", ")", ":", "print_results_header", "(", "file_result", ".", "filepath", ",", "file_result", ".", "is_valid", ")", "for", "object_result", "in", "file_result", ".", "object_results", ":", "if", "object_result", ".", "warnings", ":", "print_warning_results", "(", "object_result", ",", "1", ")", "if", "object_result", ".", "errors", ":", "print_schema_results", "(", "object_result", ",", "1", ")", "if", "file_result", ".", "fatal", ":", "print_fatal_results", "(", "file_result", ".", "fatal", ",", "1", ")" ]
Print the results of validating a file. Args: file_result: A FileValidationResults instance.
[ "Print", "the", "results", "of", "validating", "a", "file", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L172-L188
train
oasis-open/cti-stix-validator
stix2validator/output.py
print_results
def print_results(results): """Print `results` (the results of validation) to stdout. Args: results: A list of FileValidationResults or ObjectValidationResults instances. """ if not isinstance(results, list): results = [results] for r in results: try: r.log() except AttributeError: raise ValueError('Argument to print_results() must be a list of ' 'FileValidationResults or ObjectValidationResults.')
python
def print_results(results): """Print `results` (the results of validation) to stdout. Args: results: A list of FileValidationResults or ObjectValidationResults instances. """ if not isinstance(results, list): results = [results] for r in results: try: r.log() except AttributeError: raise ValueError('Argument to print_results() must be a list of ' 'FileValidationResults or ObjectValidationResults.')
[ "def", "print_results", "(", "results", ")", ":", "if", "not", "isinstance", "(", "results", ",", "list", ")", ":", "results", "=", "[", "results", "]", "for", "r", "in", "results", ":", "try", ":", "r", ".", "log", "(", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", "'Argument to print_results() must be a list of '", "'FileValidationResults or ObjectValidationResults.'", ")" ]
Print `results` (the results of validation) to stdout. Args: results: A list of FileValidationResults or ObjectValidationResults instances.
[ "Print", "results", "(", "the", "results", "of", "validation", ")", "to", "stdout", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L191-L207
train
oasis-open/cti-stix-validator
stix2validator/v20/shoulds.py
vocab_encryption_algo
def vocab_encryption_algo(instance): """Ensure file objects' 'encryption_algorithm' property is from the encryption-algo-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: enc_algo = obj['encryption_algorithm'] except KeyError: continue if enc_algo not in enums.ENCRYPTION_ALGO_OV: yield JSONError("Object '%s' has an 'encryption_algorithm' of " "'%s', which is not a value in the " "encryption-algo-ov vocabulary." % (key, enc_algo), instance['id'], 'encryption-algo')
python
def vocab_encryption_algo(instance): """Ensure file objects' 'encryption_algorithm' property is from the encryption-algo-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: enc_algo = obj['encryption_algorithm'] except KeyError: continue if enc_algo not in enums.ENCRYPTION_ALGO_OV: yield JSONError("Object '%s' has an 'encryption_algorithm' of " "'%s', which is not a value in the " "encryption-algo-ov vocabulary." % (key, enc_algo), instance['id'], 'encryption-algo')
[ "def", "vocab_encryption_algo", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'file'", ":", "try", ":", "enc_algo", "=", "obj", "[", "'encryption_algorithm'", "]", "except", "KeyError", ":", "continue", "if", "enc_algo", "not", "in", "enums", ".", "ENCRYPTION_ALGO_OV", ":", "yield", "JSONError", "(", "\"Object '%s' has an 'encryption_algorithm' of \"", "\"'%s', which is not a value in the \"", "\"encryption-algo-ov vocabulary.\"", "%", "(", "key", ",", "enc_algo", ")", ",", "instance", "[", "'id'", "]", ",", "'encryption-algo'", ")" ]
Ensure file objects' 'encryption_algorithm' property is from the encryption-algo-ov vocabulary.
[ "Ensure", "file", "objects", "encryption_algorithm", "property", "is", "from", "the", "encryption", "-", "algo", "-", "ov", "vocabulary", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/shoulds.py#L426-L441
train
oasis-open/cti-stix-validator
stix2validator/v20/shoulds.py
enforce_relationship_refs
def enforce_relationship_refs(instance): """Ensures that all SDOs being referenced by the SRO are contained within the same bundle""" if instance['type'] != 'bundle' or 'objects' not in instance: return rel_references = set() """Find and store all ids""" for obj in instance['objects']: if obj['type'] != 'relationship': rel_references.add(obj['id']) """Check if id has been encountered""" for obj in instance['objects']: if obj['type'] == 'relationship': if obj['source_ref'] not in rel_references: yield JSONError("Relationship object %s makes reference to %s " "Which is not found in current bundle " % (obj['id'], obj['source_ref']), 'enforce-relationship-refs') if obj['target_ref'] not in rel_references: yield JSONError("Relationship object %s makes reference to %s " "Which is not found in current bundle " % (obj['id'], obj['target_ref']), 'enforce-relationship-refs')
python
def enforce_relationship_refs(instance): """Ensures that all SDOs being referenced by the SRO are contained within the same bundle""" if instance['type'] != 'bundle' or 'objects' not in instance: return rel_references = set() """Find and store all ids""" for obj in instance['objects']: if obj['type'] != 'relationship': rel_references.add(obj['id']) """Check if id has been encountered""" for obj in instance['objects']: if obj['type'] == 'relationship': if obj['source_ref'] not in rel_references: yield JSONError("Relationship object %s makes reference to %s " "Which is not found in current bundle " % (obj['id'], obj['source_ref']), 'enforce-relationship-refs') if obj['target_ref'] not in rel_references: yield JSONError("Relationship object %s makes reference to %s " "Which is not found in current bundle " % (obj['id'], obj['target_ref']), 'enforce-relationship-refs')
[ "def", "enforce_relationship_refs", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'bundle'", "or", "'objects'", "not", "in", "instance", ":", "return", "rel_references", "=", "set", "(", ")", "\"\"\"Find and store all ids\"\"\"", "for", "obj", "in", "instance", "[", "'objects'", "]", ":", "if", "obj", "[", "'type'", "]", "!=", "'relationship'", ":", "rel_references", ".", "add", "(", "obj", "[", "'id'", "]", ")", "\"\"\"Check if id has been encountered\"\"\"", "for", "obj", "in", "instance", "[", "'objects'", "]", ":", "if", "obj", "[", "'type'", "]", "==", "'relationship'", ":", "if", "obj", "[", "'source_ref'", "]", "not", "in", "rel_references", ":", "yield", "JSONError", "(", "\"Relationship object %s makes reference to %s \"", "\"Which is not found in current bundle \"", "%", "(", "obj", "[", "'id'", "]", ",", "obj", "[", "'source_ref'", "]", ")", ",", "'enforce-relationship-refs'", ")", "if", "obj", "[", "'target_ref'", "]", "not", "in", "rel_references", ":", "yield", "JSONError", "(", "\"Relationship object %s makes reference to %s \"", "\"Which is not found in current bundle \"", "%", "(", "obj", "[", "'id'", "]", ",", "obj", "[", "'target_ref'", "]", ")", ",", "'enforce-relationship-refs'", ")" ]
Ensures that all SDOs being referenced by the SRO are contained within the same bundle
[ "Ensures", "that", "all", "SDOs", "being", "referenced", "by", "the", "SRO", "are", "contained", "within", "the", "same", "bundle" ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/shoulds.py#L1036-L1060
train
oasis-open/cti-stix-validator
stix2validator/v21/musts.py
timestamp_compare
def timestamp_compare(instance): """Ensure timestamp properties with a comparison requirement are valid. E.g. `modified` must be later or equal to `created`. """ compares = [('modified', 'ge', 'created')] additional_compares = enums.TIMESTAMP_COMPARE.get(instance.get('type', ''), []) compares.extend(additional_compares) for first, op, second in compares: comp = getattr(operator, op) comp_str = get_comparison_string(op) if first in instance and second in instance and \ not comp(instance[first], instance[second]): msg = "'%s' (%s) must be %s '%s' (%s)" yield JSONError(msg % (first, instance[first], comp_str, second, instance[second]), instance['id'])
python
def timestamp_compare(instance): """Ensure timestamp properties with a comparison requirement are valid. E.g. `modified` must be later or equal to `created`. """ compares = [('modified', 'ge', 'created')] additional_compares = enums.TIMESTAMP_COMPARE.get(instance.get('type', ''), []) compares.extend(additional_compares) for first, op, second in compares: comp = getattr(operator, op) comp_str = get_comparison_string(op) if first in instance and second in instance and \ not comp(instance[first], instance[second]): msg = "'%s' (%s) must be %s '%s' (%s)" yield JSONError(msg % (first, instance[first], comp_str, second, instance[second]), instance['id'])
[ "def", "timestamp_compare", "(", "instance", ")", ":", "compares", "=", "[", "(", "'modified'", ",", "'ge'", ",", "'created'", ")", "]", "additional_compares", "=", "enums", ".", "TIMESTAMP_COMPARE", ".", "get", "(", "instance", ".", "get", "(", "'type'", ",", "''", ")", ",", "[", "]", ")", "compares", ".", "extend", "(", "additional_compares", ")", "for", "first", ",", "op", ",", "second", "in", "compares", ":", "comp", "=", "getattr", "(", "operator", ",", "op", ")", "comp_str", "=", "get_comparison_string", "(", "op", ")", "if", "first", "in", "instance", "and", "second", "in", "instance", "and", "not", "comp", "(", "instance", "[", "first", "]", ",", "instance", "[", "second", "]", ")", ":", "msg", "=", "\"'%s' (%s) must be %s '%s' (%s)\"", "yield", "JSONError", "(", "msg", "%", "(", "first", ",", "instance", "[", "first", "]", ",", "comp_str", ",", "second", ",", "instance", "[", "second", "]", ")", ",", "instance", "[", "'id'", "]", ")" ]
Ensure timestamp properties with a comparison requirement are valid. E.g. `modified` must be later or equal to `created`.
[ "Ensure", "timestamp", "properties", "with", "a", "comparison", "requirement", "are", "valid", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/musts.py#L87-L104
train
oasis-open/cti-stix-validator
stix2validator/v21/musts.py
observable_timestamp_compare
def observable_timestamp_compare(instance): """Ensure cyber observable timestamp properties with a comparison requirement are valid. """ for key, obj in instance['objects'].items(): compares = enums.TIMESTAMP_COMPARE_OBSERVABLE.get(obj.get('type', ''), []) print(compares) for first, op, second in compares: comp = getattr(operator, op) comp_str = get_comparison_string(op) if first in obj and second in obj and \ not comp(obj[first], obj[second]): msg = "In object '%s', '%s' (%s) must be %s '%s' (%s)" yield JSONError(msg % (key, first, obj[first], comp_str, second, obj[second]), instance['id'])
python
def observable_timestamp_compare(instance): """Ensure cyber observable timestamp properties with a comparison requirement are valid. """ for key, obj in instance['objects'].items(): compares = enums.TIMESTAMP_COMPARE_OBSERVABLE.get(obj.get('type', ''), []) print(compares) for first, op, second in compares: comp = getattr(operator, op) comp_str = get_comparison_string(op) if first in obj and second in obj and \ not comp(obj[first], obj[second]): msg = "In object '%s', '%s' (%s) must be %s '%s' (%s)" yield JSONError(msg % (key, first, obj[first], comp_str, second, obj[second]), instance['id'])
[ "def", "observable_timestamp_compare", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "compares", "=", "enums", ".", "TIMESTAMP_COMPARE_OBSERVABLE", ".", "get", "(", "obj", ".", "get", "(", "'type'", ",", "''", ")", ",", "[", "]", ")", "print", "(", "compares", ")", "for", "first", ",", "op", ",", "second", "in", "compares", ":", "comp", "=", "getattr", "(", "operator", ",", "op", ")", "comp_str", "=", "get_comparison_string", "(", "op", ")", "if", "first", "in", "obj", "and", "second", "in", "obj", "and", "not", "comp", "(", "obj", "[", "first", "]", ",", "obj", "[", "second", "]", ")", ":", "msg", "=", "\"In object '%s', '%s' (%s) must be %s '%s' (%s)\"", "yield", "JSONError", "(", "msg", "%", "(", "key", ",", "first", ",", "obj", "[", "first", "]", ",", "comp_str", ",", "second", ",", "obj", "[", "second", "]", ")", ",", "instance", "[", "'id'", "]", ")" ]
Ensure cyber observable timestamp properties with a comparison requirement are valid.
[ "Ensure", "cyber", "observable", "timestamp", "properties", "with", "a", "comparison", "requirement", "are", "valid", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/musts.py#L108-L123
train
oasis-open/cti-stix-validator
stix2validator/v21/musts.py
language_contents
def language_contents(instance): """Ensure keys in Language Content's 'contents' dictionary are valid language codes, and that the keys in the sub-dictionaries match the rules for object property names. """ if instance['type'] != 'language-content' or 'contents' not in instance: return for key, value in instance['contents'].items(): if key not in enums.LANG_CODES: yield JSONError("Invalid key '%s' in 'contents' property must be" " an RFC 5646 code" % key, instance['id']) for subkey, subvalue in value.items(): if not PROPERTY_FORMAT_RE.match(subkey): yield JSONError("'%s' in '%s' of the 'contents' property is " "invalid and must match a valid property name" % (subkey, key), instance['id'], 'observable-dictionary-keys')
python
def language_contents(instance): """Ensure keys in Language Content's 'contents' dictionary are valid language codes, and that the keys in the sub-dictionaries match the rules for object property names. """ if instance['type'] != 'language-content' or 'contents' not in instance: return for key, value in instance['contents'].items(): if key not in enums.LANG_CODES: yield JSONError("Invalid key '%s' in 'contents' property must be" " an RFC 5646 code" % key, instance['id']) for subkey, subvalue in value.items(): if not PROPERTY_FORMAT_RE.match(subkey): yield JSONError("'%s' in '%s' of the 'contents' property is " "invalid and must match a valid property name" % (subkey, key), instance['id'], 'observable-dictionary-keys')
[ "def", "language_contents", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'language-content'", "or", "'contents'", "not", "in", "instance", ":", "return", "for", "key", ",", "value", "in", "instance", "[", "'contents'", "]", ".", "items", "(", ")", ":", "if", "key", "not", "in", "enums", ".", "LANG_CODES", ":", "yield", "JSONError", "(", "\"Invalid key '%s' in 'contents' property must be\"", "\" an RFC 5646 code\"", "%", "key", ",", "instance", "[", "'id'", "]", ")", "for", "subkey", ",", "subvalue", "in", "value", ".", "items", "(", ")", ":", "if", "not", "PROPERTY_FORMAT_RE", ".", "match", "(", "subkey", ")", ":", "yield", "JSONError", "(", "\"'%s' in '%s' of the 'contents' property is \"", "\"invalid and must match a valid property name\"", "%", "(", "subkey", ",", "key", ")", ",", "instance", "[", "'id'", "]", ",", "'observable-dictionary-keys'", ")" ]
Ensure keys in Language Content's 'contents' dictionary are valid language codes, and that the keys in the sub-dictionaries match the rules for object property names.
[ "Ensure", "keys", "in", "Language", "Content", "s", "contents", "dictionary", "are", "valid", "language", "codes", "and", "that", "the", "keys", "in", "the", "sub", "-", "dictionaries", "match", "the", "rules", "for", "object", "property", "names", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/musts.py#L521-L537
train
oasis-open/cti-stix-validator
stix2validator/v21/musts.py
list_musts
def list_musts(options): """Construct the list of 'MUST' validators to be run by the validator. """ validator_list = [ timestamp, timestamp_compare, observable_timestamp_compare, object_marking_circular_refs, granular_markings_circular_refs, marking_selector_syntax, observable_object_references, artifact_mime_type, character_set, language, software_language, patterns, language_contents, ] # --strict-types if options.strict_types: validator_list.append(types_strict) # --strict-properties if options.strict_properties: validator_list.append(properties_strict) return validator_list
python
def list_musts(options): """Construct the list of 'MUST' validators to be run by the validator. """ validator_list = [ timestamp, timestamp_compare, observable_timestamp_compare, object_marking_circular_refs, granular_markings_circular_refs, marking_selector_syntax, observable_object_references, artifact_mime_type, character_set, language, software_language, patterns, language_contents, ] # --strict-types if options.strict_types: validator_list.append(types_strict) # --strict-properties if options.strict_properties: validator_list.append(properties_strict) return validator_list
[ "def", "list_musts", "(", "options", ")", ":", "validator_list", "=", "[", "timestamp", ",", "timestamp_compare", ",", "observable_timestamp_compare", ",", "object_marking_circular_refs", ",", "granular_markings_circular_refs", ",", "marking_selector_syntax", ",", "observable_object_references", ",", "artifact_mime_type", ",", "character_set", ",", "language", ",", "software_language", ",", "patterns", ",", "language_contents", ",", "]", "# --strict-types", "if", "options", ".", "strict_types", ":", "validator_list", ".", "append", "(", "types_strict", ")", "# --strict-properties", "if", "options", ".", "strict_properties", ":", "validator_list", ".", "append", "(", "properties_strict", ")", "return", "validator_list" ]
Construct the list of 'MUST' validators to be run by the validator.
[ "Construct", "the", "list", "of", "MUST", "validators", "to", "be", "run", "by", "the", "validator", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/musts.py#L540-L567
train
oasis-open/cti-stix-validator
stix2validator/codes.py
get_code
def get_code(results): """Determines the exit status code to be returned from a script by inspecting the results returned from validating file(s). Status codes are binary OR'd together, so exit codes can communicate multiple error conditions. """ status = EXIT_SUCCESS for file_result in results: error = any(object_result.errors for object_result in file_result.object_results) fatal = file_result.fatal if error: status |= EXIT_SCHEMA_INVALID if fatal: status |= EXIT_VALIDATION_ERROR return status
python
def get_code(results): """Determines the exit status code to be returned from a script by inspecting the results returned from validating file(s). Status codes are binary OR'd together, so exit codes can communicate multiple error conditions. """ status = EXIT_SUCCESS for file_result in results: error = any(object_result.errors for object_result in file_result.object_results) fatal = file_result.fatal if error: status |= EXIT_SCHEMA_INVALID if fatal: status |= EXIT_VALIDATION_ERROR return status
[ "def", "get_code", "(", "results", ")", ":", "status", "=", "EXIT_SUCCESS", "for", "file_result", "in", "results", ":", "error", "=", "any", "(", "object_result", ".", "errors", "for", "object_result", "in", "file_result", ".", "object_results", ")", "fatal", "=", "file_result", ".", "fatal", "if", "error", ":", "status", "|=", "EXIT_SCHEMA_INVALID", "if", "fatal", ":", "status", "|=", "EXIT_VALIDATION_ERROR", "return", "status" ]
Determines the exit status code to be returned from a script by inspecting the results returned from validating file(s). Status codes are binary OR'd together, so exit codes can communicate multiple error conditions.
[ "Determines", "the", "exit", "status", "code", "to", "be", "returned", "from", "a", "script", "by", "inspecting", "the", "results", "returned", "from", "validating", "file", "(", "s", ")", ".", "Status", "codes", "are", "binary", "OR", "d", "together", "so", "exit", "codes", "can", "communicate", "multiple", "error", "conditions", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/codes.py#L22-L41
train
oasis-open/cti-stix-validator
stix2validator/util.py
parse_args
def parse_args(cmd_args, is_script=False): """Parses a list of command line arguments into a ValidationOptions object. Args: cmd_args (list of str): The list of command line arguments to be parsed. is_script: Whether the arguments are intended for use in a stand-alone script or imported into another tool. Returns: Instance of ``ValidationOptions`` """ parser = argparse.ArgumentParser( description=__doc__, formatter_class=NewlinesHelpFormatter, epilog=CODES_TABLE ) # Input options if is_script: parser.add_argument( "files", metavar="FILES", nargs="*", default=sys.stdin, help="A whitespace separated list of STIX files or directories of " "STIX files to validate. If none given, stdin will be used." ) parser.add_argument( "-r", "--recursive", dest="recursive", action="store_true", default=True, help="Recursively descend into input directories." ) parser.add_argument( "-s", "--schemas", dest="schema_dir", help="Custom schema directory. If provided, input will be validated " "against these schemas in addition to the STIX schemas bundled " "with this script." ) parser.add_argument( "--version", dest="version", default=DEFAULT_VER, help="The version of the STIX specification to validate against (e.g. " "\"2.0\")." ) # Output options parser.add_argument( "-v", "--verbose", dest="verbose", action="store_true", default=False, help="Print informational notes and more verbose error messages." ) parser.add_argument( "-q", "--silent", dest="silent", action="store_true", default=False, help="Silence all output to stdout." ) parser.add_argument( "-d", "--disable", "--ignore", dest="disabled", default="", help="A comma-separated list of recommended best practice checks to " "skip. By default, no checks are disabled. \n\n" "Example: --disable 202,210" ) parser.add_argument( "-e", "--enable", "--select", dest="enabled", default="", help="A comma-separated list of recommended best practice checks to " "enable. If the --disable option is not used, no other checks " "will be run. By default, all checks are enabled.\n\n" "Example: --enable 218" ) parser.add_argument( "--strict", dest="strict", action="store_true", default=False, help="Treat warnings as errors and fail validation if any are found." ) parser.add_argument( "--strict-types", dest="strict_types", action="store_true", default=False, help="Ensure that no custom object types are used, only those defined" " in the STIX specification." ) parser.add_argument( "--strict-properties", dest="strict_properties", action="store_true", default=False, help="Ensure that no custom properties are used, only those defined" " in the STIX specification." ) parser.add_argument( "--no-cache", dest="no_cache", action="store_true", default=False, help="Disable the caching of external source values." ) parser.add_argument( "--refresh-cache", dest="refresh_cache", action="store_true", default=False, help="Clears the cache of external source values, then " "during validation downloads them again." ) parser.add_argument( "--clear-cache", dest="clear_cache", action="store_true", default=False, help="Clear the cache of external source values after validation." ) parser.add_argument( "--enforce-refs", dest="enforce_refs", action="store_true", default=False, help="Ensures that all SDOs being referenced by SROs are contained " "within the same bundle." ) args = parser.parse_args(cmd_args) if not is_script: args.files = "" if not args.version: args.version = DEFAULT_VER return ValidationOptions(args)
python
def parse_args(cmd_args, is_script=False): """Parses a list of command line arguments into a ValidationOptions object. Args: cmd_args (list of str): The list of command line arguments to be parsed. is_script: Whether the arguments are intended for use in a stand-alone script or imported into another tool. Returns: Instance of ``ValidationOptions`` """ parser = argparse.ArgumentParser( description=__doc__, formatter_class=NewlinesHelpFormatter, epilog=CODES_TABLE ) # Input options if is_script: parser.add_argument( "files", metavar="FILES", nargs="*", default=sys.stdin, help="A whitespace separated list of STIX files or directories of " "STIX files to validate. If none given, stdin will be used." ) parser.add_argument( "-r", "--recursive", dest="recursive", action="store_true", default=True, help="Recursively descend into input directories." ) parser.add_argument( "-s", "--schemas", dest="schema_dir", help="Custom schema directory. If provided, input will be validated " "against these schemas in addition to the STIX schemas bundled " "with this script." ) parser.add_argument( "--version", dest="version", default=DEFAULT_VER, help="The version of the STIX specification to validate against (e.g. " "\"2.0\")." ) # Output options parser.add_argument( "-v", "--verbose", dest="verbose", action="store_true", default=False, help="Print informational notes and more verbose error messages." ) parser.add_argument( "-q", "--silent", dest="silent", action="store_true", default=False, help="Silence all output to stdout." ) parser.add_argument( "-d", "--disable", "--ignore", dest="disabled", default="", help="A comma-separated list of recommended best practice checks to " "skip. By default, no checks are disabled. \n\n" "Example: --disable 202,210" ) parser.add_argument( "-e", "--enable", "--select", dest="enabled", default="", help="A comma-separated list of recommended best practice checks to " "enable. If the --disable option is not used, no other checks " "will be run. By default, all checks are enabled.\n\n" "Example: --enable 218" ) parser.add_argument( "--strict", dest="strict", action="store_true", default=False, help="Treat warnings as errors and fail validation if any are found." ) parser.add_argument( "--strict-types", dest="strict_types", action="store_true", default=False, help="Ensure that no custom object types are used, only those defined" " in the STIX specification." ) parser.add_argument( "--strict-properties", dest="strict_properties", action="store_true", default=False, help="Ensure that no custom properties are used, only those defined" " in the STIX specification." ) parser.add_argument( "--no-cache", dest="no_cache", action="store_true", default=False, help="Disable the caching of external source values." ) parser.add_argument( "--refresh-cache", dest="refresh_cache", action="store_true", default=False, help="Clears the cache of external source values, then " "during validation downloads them again." ) parser.add_argument( "--clear-cache", dest="clear_cache", action="store_true", default=False, help="Clear the cache of external source values after validation." ) parser.add_argument( "--enforce-refs", dest="enforce_refs", action="store_true", default=False, help="Ensures that all SDOs being referenced by SROs are contained " "within the same bundle." ) args = parser.parse_args(cmd_args) if not is_script: args.files = "" if not args.version: args.version = DEFAULT_VER return ValidationOptions(args)
[ "def", "parse_args", "(", "cmd_args", ",", "is_script", "=", "False", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "__doc__", ",", "formatter_class", "=", "NewlinesHelpFormatter", ",", "epilog", "=", "CODES_TABLE", ")", "# Input options", "if", "is_script", ":", "parser", ".", "add_argument", "(", "\"files\"", ",", "metavar", "=", "\"FILES\"", ",", "nargs", "=", "\"*\"", ",", "default", "=", "sys", ".", "stdin", ",", "help", "=", "\"A whitespace separated list of STIX files or directories of \"", "\"STIX files to validate. If none given, stdin will be used.\"", ")", "parser", ".", "add_argument", "(", "\"-r\"", ",", "\"--recursive\"", ",", "dest", "=", "\"recursive\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "True", ",", "help", "=", "\"Recursively descend into input directories.\"", ")", "parser", ".", "add_argument", "(", "\"-s\"", ",", "\"--schemas\"", ",", "dest", "=", "\"schema_dir\"", ",", "help", "=", "\"Custom schema directory. If provided, input will be validated \"", "\"against these schemas in addition to the STIX schemas bundled \"", "\"with this script.\"", ")", "parser", ".", "add_argument", "(", "\"--version\"", ",", "dest", "=", "\"version\"", ",", "default", "=", "DEFAULT_VER", ",", "help", "=", "\"The version of the STIX specification to validate against (e.g. \"", "\"\\\"2.0\\\").\"", ")", "# Output options", "parser", ".", "add_argument", "(", "\"-v\"", ",", "\"--verbose\"", ",", "dest", "=", "\"verbose\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Print informational notes and more verbose error messages.\"", ")", "parser", ".", "add_argument", "(", "\"-q\"", ",", "\"--silent\"", ",", "dest", "=", "\"silent\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Silence all output to stdout.\"", ")", "parser", ".", "add_argument", "(", "\"-d\"", ",", "\"--disable\"", ",", "\"--ignore\"", ",", "dest", "=", "\"disabled\"", ",", "default", "=", "\"\"", ",", "help", "=", "\"A comma-separated list of recommended best practice checks to \"", "\"skip. By default, no checks are disabled. \\n\\n\"", "\"Example: --disable 202,210\"", ")", "parser", ".", "add_argument", "(", "\"-e\"", ",", "\"--enable\"", ",", "\"--select\"", ",", "dest", "=", "\"enabled\"", ",", "default", "=", "\"\"", ",", "help", "=", "\"A comma-separated list of recommended best practice checks to \"", "\"enable. If the --disable option is not used, no other checks \"", "\"will be run. By default, all checks are enabled.\\n\\n\"", "\"Example: --enable 218\"", ")", "parser", ".", "add_argument", "(", "\"--strict\"", ",", "dest", "=", "\"strict\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Treat warnings as errors and fail validation if any are found.\"", ")", "parser", ".", "add_argument", "(", "\"--strict-types\"", ",", "dest", "=", "\"strict_types\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Ensure that no custom object types are used, only those defined\"", "\" in the STIX specification.\"", ")", "parser", ".", "add_argument", "(", "\"--strict-properties\"", ",", "dest", "=", "\"strict_properties\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Ensure that no custom properties are used, only those defined\"", "\" in the STIX specification.\"", ")", "parser", ".", "add_argument", "(", "\"--no-cache\"", ",", "dest", "=", "\"no_cache\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Disable the caching of external source values.\"", ")", "parser", ".", "add_argument", "(", "\"--refresh-cache\"", ",", "dest", "=", "\"refresh_cache\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Clears the cache of external source values, then \"", "\"during validation downloads them again.\"", ")", "parser", ".", "add_argument", "(", "\"--clear-cache\"", ",", "dest", "=", "\"clear_cache\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Clear the cache of external source values after validation.\"", ")", "parser", ".", "add_argument", "(", "\"--enforce-refs\"", ",", "dest", "=", "\"enforce_refs\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Ensures that all SDOs being referenced by SROs are contained \"", "\"within the same bundle.\"", ")", "args", "=", "parser", ".", "parse_args", "(", "cmd_args", ")", "if", "not", "is_script", ":", "args", ".", "files", "=", "\"\"", "if", "not", "args", ".", "version", ":", "args", ".", "version", "=", "DEFAULT_VER", "return", "ValidationOptions", "(", "args", ")" ]
Parses a list of command line arguments into a ValidationOptions object. Args: cmd_args (list of str): The list of command line arguments to be parsed. is_script: Whether the arguments are intended for use in a stand-alone script or imported into another tool. Returns: Instance of ``ValidationOptions``
[ "Parses", "a", "list", "of", "command", "line", "arguments", "into", "a", "ValidationOptions", "object", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/util.py#L125-L286
train
oasis-open/cti-stix-validator
stix2validator/util.py
cyber_observable_check
def cyber_observable_check(original_function): """Decorator for functions that require cyber observable data. """ def new_function(*args, **kwargs): if not has_cyber_observable_data(args[0]): return func = original_function(*args, **kwargs) if isinstance(func, Iterable): for x in original_function(*args, **kwargs): yield x new_function.__name__ = original_function.__name__ return new_function
python
def cyber_observable_check(original_function): """Decorator for functions that require cyber observable data. """ def new_function(*args, **kwargs): if not has_cyber_observable_data(args[0]): return func = original_function(*args, **kwargs) if isinstance(func, Iterable): for x in original_function(*args, **kwargs): yield x new_function.__name__ = original_function.__name__ return new_function
[ "def", "cyber_observable_check", "(", "original_function", ")", ":", "def", "new_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "has_cyber_observable_data", "(", "args", "[", "0", "]", ")", ":", "return", "func", "=", "original_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "func", ",", "Iterable", ")", ":", "for", "x", "in", "original_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "yield", "x", "new_function", ".", "__name__", "=", "original_function", ".", "__name__", "return", "new_function" ]
Decorator for functions that require cyber observable data.
[ "Decorator", "for", "functions", "that", "require", "cyber", "observable", "data", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/util.py#L405-L416
train
oasis-open/cti-stix-validator
stix2validator/util.py
init_requests_cache
def init_requests_cache(refresh_cache=False): """ Initializes a cache which the ``requests`` library will consult for responses, before making network requests. :param refresh_cache: Whether the cache should be cleared out """ # Cache data from external sources; used in some checks dirs = AppDirs("stix2-validator", "OASIS") # Create cache dir if doesn't exist try: os.makedirs(dirs.user_cache_dir) except OSError as e: if e.errno != errno.EEXIST: raise requests_cache.install_cache( cache_name=os.path.join(dirs.user_cache_dir, 'py{}cache'.format( sys.version_info[0])), expire_after=datetime.timedelta(weeks=1)) if refresh_cache: clear_requests_cache()
python
def init_requests_cache(refresh_cache=False): """ Initializes a cache which the ``requests`` library will consult for responses, before making network requests. :param refresh_cache: Whether the cache should be cleared out """ # Cache data from external sources; used in some checks dirs = AppDirs("stix2-validator", "OASIS") # Create cache dir if doesn't exist try: os.makedirs(dirs.user_cache_dir) except OSError as e: if e.errno != errno.EEXIST: raise requests_cache.install_cache( cache_name=os.path.join(dirs.user_cache_dir, 'py{}cache'.format( sys.version_info[0])), expire_after=datetime.timedelta(weeks=1)) if refresh_cache: clear_requests_cache()
[ "def", "init_requests_cache", "(", "refresh_cache", "=", "False", ")", ":", "# Cache data from external sources; used in some checks", "dirs", "=", "AppDirs", "(", "\"stix2-validator\"", ",", "\"OASIS\"", ")", "# Create cache dir if doesn't exist", "try", ":", "os", ".", "makedirs", "(", "dirs", ".", "user_cache_dir", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "requests_cache", ".", "install_cache", "(", "cache_name", "=", "os", ".", "path", ".", "join", "(", "dirs", ".", "user_cache_dir", ",", "'py{}cache'", ".", "format", "(", "sys", ".", "version_info", "[", "0", "]", ")", ")", ",", "expire_after", "=", "datetime", ".", "timedelta", "(", "weeks", "=", "1", ")", ")", "if", "refresh_cache", ":", "clear_requests_cache", "(", ")" ]
Initializes a cache which the ``requests`` library will consult for responses, before making network requests. :param refresh_cache: Whether the cache should be cleared out
[ "Initializes", "a", "cache", "which", "the", "requests", "library", "will", "consult", "for", "responses", "before", "making", "network", "requests", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/util.py#L419-L440
train
hellysmile/django-activeurl
django_activeurl/templatetags/activeurl.py
ActiveUrl.render_tag
def render_tag(self, context, kwargs, nodelist): '''render content with "active" urls logic''' # load configuration from passed options self.load_configuration(**kwargs) # get request from context request = context['request'] # get full path from request self.full_path = request.get_full_path() # render content of template tag context.push() content = nodelist.render(context) context.pop() # check content for "active" urls content = render_content( content, full_path=self.full_path, parent_tag=self.parent_tag, css_class=self.css_class, menu=self.menu, ignore_params=self.ignore_params, ) return content
python
def render_tag(self, context, kwargs, nodelist): '''render content with "active" urls logic''' # load configuration from passed options self.load_configuration(**kwargs) # get request from context request = context['request'] # get full path from request self.full_path = request.get_full_path() # render content of template tag context.push() content = nodelist.render(context) context.pop() # check content for "active" urls content = render_content( content, full_path=self.full_path, parent_tag=self.parent_tag, css_class=self.css_class, menu=self.menu, ignore_params=self.ignore_params, ) return content
[ "def", "render_tag", "(", "self", ",", "context", ",", "kwargs", ",", "nodelist", ")", ":", "# load configuration from passed options", "self", ".", "load_configuration", "(", "*", "*", "kwargs", ")", "# get request from context", "request", "=", "context", "[", "'request'", "]", "# get full path from request", "self", ".", "full_path", "=", "request", ".", "get_full_path", "(", ")", "# render content of template tag", "context", ".", "push", "(", ")", "content", "=", "nodelist", ".", "render", "(", "context", ")", "context", ".", "pop", "(", ")", "# check content for \"active\" urls", "content", "=", "render_content", "(", "content", ",", "full_path", "=", "self", ".", "full_path", ",", "parent_tag", "=", "self", ".", "parent_tag", ",", "css_class", "=", "self", ".", "css_class", ",", "menu", "=", "self", ".", "menu", ",", "ignore_params", "=", "self", ".", "ignore_params", ",", ")", "return", "content" ]
render content with "active" urls logic
[ "render", "content", "with", "active", "urls", "logic" ]
40d7f01b217641705fc5b7fe387e28e48ce332dc
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/templatetags/activeurl.py#L27-L53
train
hellysmile/django-activeurl
django_activeurl/ext/django_jinja.py
ActiveUrl.parse
def parse(self, parser): '''parse content of extension''' # line number of token that started the tag lineno = next(parser.stream).lineno # template context context = nodes.ContextReference() # parse keyword arguments kwargs = [] while parser.stream.look().type == lexer.TOKEN_ASSIGN: key = parser.stream.expect(lexer.TOKEN_NAME) next(parser.stream) kwargs.append( nodes.Keyword(key.value, parser.parse_expression()), ) parser.stream.skip_if('comma') # parse content of the activeurl block up to endactiveurl body = parser.parse_statements(['name:endactiveurl'], drop_needle=True) args = [context] call_method = self.call_method( 'render_tag', args=args, kwargs=kwargs, ) return nodes.CallBlock(call_method, [], [], body).set_lineno(lineno)
python
def parse(self, parser): '''parse content of extension''' # line number of token that started the tag lineno = next(parser.stream).lineno # template context context = nodes.ContextReference() # parse keyword arguments kwargs = [] while parser.stream.look().type == lexer.TOKEN_ASSIGN: key = parser.stream.expect(lexer.TOKEN_NAME) next(parser.stream) kwargs.append( nodes.Keyword(key.value, parser.parse_expression()), ) parser.stream.skip_if('comma') # parse content of the activeurl block up to endactiveurl body = parser.parse_statements(['name:endactiveurl'], drop_needle=True) args = [context] call_method = self.call_method( 'render_tag', args=args, kwargs=kwargs, ) return nodes.CallBlock(call_method, [], [], body).set_lineno(lineno)
[ "def", "parse", "(", "self", ",", "parser", ")", ":", "# line number of token that started the tag", "lineno", "=", "next", "(", "parser", ".", "stream", ")", ".", "lineno", "# template context", "context", "=", "nodes", ".", "ContextReference", "(", ")", "# parse keyword arguments", "kwargs", "=", "[", "]", "while", "parser", ".", "stream", ".", "look", "(", ")", ".", "type", "==", "lexer", ".", "TOKEN_ASSIGN", ":", "key", "=", "parser", ".", "stream", ".", "expect", "(", "lexer", ".", "TOKEN_NAME", ")", "next", "(", "parser", ".", "stream", ")", "kwargs", ".", "append", "(", "nodes", ".", "Keyword", "(", "key", ".", "value", ",", "parser", ".", "parse_expression", "(", ")", ")", ",", ")", "parser", ".", "stream", ".", "skip_if", "(", "'comma'", ")", "# parse content of the activeurl block up to endactiveurl", "body", "=", "parser", ".", "parse_statements", "(", "[", "'name:endactiveurl'", "]", ",", "drop_needle", "=", "True", ")", "args", "=", "[", "context", "]", "call_method", "=", "self", ".", "call_method", "(", "'render_tag'", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ",", ")", "return", "nodes", ".", "CallBlock", "(", "call_method", ",", "[", "]", ",", "[", "]", ",", "body", ")", ".", "set_lineno", "(", "lineno", ")" ]
parse content of extension
[ "parse", "content", "of", "extension" ]
40d7f01b217641705fc5b7fe387e28e48ce332dc
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/ext/django_jinja.py#L17-L46
train
hellysmile/django-activeurl
django_activeurl/ext/django_jinja.py
ActiveUrl.render_tag
def render_tag(self, context, caller, **kwargs): '''render content with "active" urls logic''' # load configuration from passed options self.load_configuration(**kwargs) # get request from context request = context['request'] # get full path from request self.full_path = request.get_full_path() # render content of extension content = caller() # check content for "active" urls content = render_content( content, full_path=self.full_path, parent_tag=self.parent_tag, css_class=self.css_class, menu=self.menu, ignore_params=self.ignore_params, ) return content
python
def render_tag(self, context, caller, **kwargs): '''render content with "active" urls logic''' # load configuration from passed options self.load_configuration(**kwargs) # get request from context request = context['request'] # get full path from request self.full_path = request.get_full_path() # render content of extension content = caller() # check content for "active" urls content = render_content( content, full_path=self.full_path, parent_tag=self.parent_tag, css_class=self.css_class, menu=self.menu, ignore_params=self.ignore_params, ) return content
[ "def", "render_tag", "(", "self", ",", "context", ",", "caller", ",", "*", "*", "kwargs", ")", ":", "# load configuration from passed options", "self", ".", "load_configuration", "(", "*", "*", "kwargs", ")", "# get request from context", "request", "=", "context", "[", "'request'", "]", "# get full path from request", "self", ".", "full_path", "=", "request", ".", "get_full_path", "(", ")", "# render content of extension", "content", "=", "caller", "(", ")", "# check content for \"active\" urls", "content", "=", "render_content", "(", "content", ",", "full_path", "=", "self", ".", "full_path", ",", "parent_tag", "=", "self", ".", "parent_tag", ",", "css_class", "=", "self", ".", "css_class", ",", "menu", "=", "self", ".", "menu", ",", "ignore_params", "=", "self", ".", "ignore_params", ",", ")", "return", "content" ]
render content with "active" urls logic
[ "render", "content", "with", "active", "urls", "logic" ]
40d7f01b217641705fc5b7fe387e28e48ce332dc
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/ext/django_jinja.py#L48-L72
train
hellysmile/django-activeurl
django_activeurl/utils.py
get_cache_key
def get_cache_key(content, **kwargs): '''generate cache key''' cache_key = '' for key in sorted(kwargs.keys()): cache_key = '{cache_key}.{key}:{value}'.format( cache_key=cache_key, key=key, value=kwargs[key], ) cache_key = '{content}{cache_key}'.format( content=content, cache_key=cache_key, ) # fix for non ascii symbols, ensure encoding, python3 hashlib fix cache_key = cache_key.encode('utf-8', 'ignore') cache_key = md5(cache_key).hexdigest() cache_key = '{prefix}.{version}.{language}.{cache_key}'.format( prefix=settings.ACTIVE_URL_CACHE_PREFIX, version=__version__, language=get_language(), cache_key=cache_key ) return cache_key
python
def get_cache_key(content, **kwargs): '''generate cache key''' cache_key = '' for key in sorted(kwargs.keys()): cache_key = '{cache_key}.{key}:{value}'.format( cache_key=cache_key, key=key, value=kwargs[key], ) cache_key = '{content}{cache_key}'.format( content=content, cache_key=cache_key, ) # fix for non ascii symbols, ensure encoding, python3 hashlib fix cache_key = cache_key.encode('utf-8', 'ignore') cache_key = md5(cache_key).hexdigest() cache_key = '{prefix}.{version}.{language}.{cache_key}'.format( prefix=settings.ACTIVE_URL_CACHE_PREFIX, version=__version__, language=get_language(), cache_key=cache_key ) return cache_key
[ "def", "get_cache_key", "(", "content", ",", "*", "*", "kwargs", ")", ":", "cache_key", "=", "''", "for", "key", "in", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", ":", "cache_key", "=", "'{cache_key}.{key}:{value}'", ".", "format", "(", "cache_key", "=", "cache_key", ",", "key", "=", "key", ",", "value", "=", "kwargs", "[", "key", "]", ",", ")", "cache_key", "=", "'{content}{cache_key}'", ".", "format", "(", "content", "=", "content", ",", "cache_key", "=", "cache_key", ",", ")", "# fix for non ascii symbols, ensure encoding, python3 hashlib fix", "cache_key", "=", "cache_key", ".", "encode", "(", "'utf-8'", ",", "'ignore'", ")", "cache_key", "=", "md5", "(", "cache_key", ")", ".", "hexdigest", "(", ")", "cache_key", "=", "'{prefix}.{version}.{language}.{cache_key}'", ".", "format", "(", "prefix", "=", "settings", ".", "ACTIVE_URL_CACHE_PREFIX", ",", "version", "=", "__version__", ",", "language", "=", "get_language", "(", ")", ",", "cache_key", "=", "cache_key", ")", "return", "cache_key" ]
generate cache key
[ "generate", "cache", "key" ]
40d7f01b217641705fc5b7fe387e28e48ce332dc
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L42-L68
train
hellysmile/django-activeurl
django_activeurl/utils.py
yesno_to_bool
def yesno_to_bool(value, varname): """Return True/False from "yes"/"no". :param value: template keyword argument value :type value: string :param varname: name of the variable, for use on exception raising :type varname: string :raises: :exc:`ImproperlyConfigured` Django > 1.5 template boolean/None variables feature. """ if isinstance(value, bool): if value: value = 'yes' else: value = 'no' elif value is None: value = 'no' # check value configuration, set boolean value if value.lower() in ('yes', 'true'): value = True elif value.lower() in ('no', 'false'): value = False else: raise ImproperlyConfigured( 'activeurl: malformed param value for %s' % varname ) return value
python
def yesno_to_bool(value, varname): """Return True/False from "yes"/"no". :param value: template keyword argument value :type value: string :param varname: name of the variable, for use on exception raising :type varname: string :raises: :exc:`ImproperlyConfigured` Django > 1.5 template boolean/None variables feature. """ if isinstance(value, bool): if value: value = 'yes' else: value = 'no' elif value is None: value = 'no' # check value configuration, set boolean value if value.lower() in ('yes', 'true'): value = True elif value.lower() in ('no', 'false'): value = False else: raise ImproperlyConfigured( 'activeurl: malformed param value for %s' % varname ) return value
[ "def", "yesno_to_bool", "(", "value", ",", "varname", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "if", "value", ":", "value", "=", "'yes'", "else", ":", "value", "=", "'no'", "elif", "value", "is", "None", ":", "value", "=", "'no'", "# check value configuration, set boolean value", "if", "value", ".", "lower", "(", ")", "in", "(", "'yes'", ",", "'true'", ")", ":", "value", "=", "True", "elif", "value", ".", "lower", "(", ")", "in", "(", "'no'", ",", "'false'", ")", ":", "value", "=", "False", "else", ":", "raise", "ImproperlyConfigured", "(", "'activeurl: malformed param value for %s'", "%", "varname", ")", "return", "value" ]
Return True/False from "yes"/"no". :param value: template keyword argument value :type value: string :param varname: name of the variable, for use on exception raising :type varname: string :raises: :exc:`ImproperlyConfigured` Django > 1.5 template boolean/None variables feature.
[ "Return", "True", "/", "False", "from", "yes", "/", "no", "." ]
40d7f01b217641705fc5b7fe387e28e48ce332dc
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L71-L99
train
hellysmile/django-activeurl
django_activeurl/utils.py
check_active
def check_active(url, element, **kwargs): '''check "active" url, apply css_class''' menu = yesno_to_bool(kwargs['menu'], 'menu') ignore_params = yesno_to_bool(kwargs['ignore_params'], 'ignore_params') # check missing href parameter if not url.attrib.get('href', None) is None: # get href attribute href = url.attrib['href'].strip() # href="#" is often used when links shouldn't be handled by browsers. # For example, Bootstrap uses this for expandable menus on # small screens, see # https://getbootstrap.com/docs/4.0/components/navs/#using-dropdowns if href == '#': return False # split into urlparse object href = urlparse.urlsplit(href) # cut off hashtag (anchor) href = href._replace(fragment='') # cut off get params (?key=var&etc=var2) if ignore_params: href = href._replace(query='') kwargs['full_path'] = urlparse.urlunsplit( urlparse.urlsplit( kwargs['full_path'] )._replace(query='') ) # build urlparse object back into string href = urlparse.urlunsplit(href) # check empty href if href == '': # replace href with current location href = kwargs['full_path'] # compare full_path with href according to menu configuration if menu: # try mark "root" (/) url as "active", in equals way if href == '/' == kwargs['full_path']: logic = True # skip "root" (/) url, otherwise it will be always "active" elif href != '/': # start with logic logic = ( kwargs['full_path'].startswith(href) or # maybe an urlquoted href was supplied urlquote(kwargs['full_path']).startswith(href) or kwargs['full_path'].startswith(urlquote(href)) ) else: logic = False else: # equals logic logic = ( kwargs['full_path'] == href or # maybe an urlquoted href was supplied urlquote(kwargs['full_path']) == href or kwargs['full_path'] == urlquote(href) ) # "active" url found if logic: # check parent tag has "class" attribute or it is empty if element.attrib.get('class'): # prevent multiple "class" attribute adding if kwargs['css_class'] not in element.attrib['class']: # append "active" class element.attrib['class'] += ' {css_class}'.format( css_class=kwargs['css_class'], ) else: # create or set (if empty) "class" attribute element.attrib['class'] = kwargs['css_class'] return True # no "active" urls found return False
python
def check_active(url, element, **kwargs): '''check "active" url, apply css_class''' menu = yesno_to_bool(kwargs['menu'], 'menu') ignore_params = yesno_to_bool(kwargs['ignore_params'], 'ignore_params') # check missing href parameter if not url.attrib.get('href', None) is None: # get href attribute href = url.attrib['href'].strip() # href="#" is often used when links shouldn't be handled by browsers. # For example, Bootstrap uses this for expandable menus on # small screens, see # https://getbootstrap.com/docs/4.0/components/navs/#using-dropdowns if href == '#': return False # split into urlparse object href = urlparse.urlsplit(href) # cut off hashtag (anchor) href = href._replace(fragment='') # cut off get params (?key=var&etc=var2) if ignore_params: href = href._replace(query='') kwargs['full_path'] = urlparse.urlunsplit( urlparse.urlsplit( kwargs['full_path'] )._replace(query='') ) # build urlparse object back into string href = urlparse.urlunsplit(href) # check empty href if href == '': # replace href with current location href = kwargs['full_path'] # compare full_path with href according to menu configuration if menu: # try mark "root" (/) url as "active", in equals way if href == '/' == kwargs['full_path']: logic = True # skip "root" (/) url, otherwise it will be always "active" elif href != '/': # start with logic logic = ( kwargs['full_path'].startswith(href) or # maybe an urlquoted href was supplied urlquote(kwargs['full_path']).startswith(href) or kwargs['full_path'].startswith(urlquote(href)) ) else: logic = False else: # equals logic logic = ( kwargs['full_path'] == href or # maybe an urlquoted href was supplied urlquote(kwargs['full_path']) == href or kwargs['full_path'] == urlquote(href) ) # "active" url found if logic: # check parent tag has "class" attribute or it is empty if element.attrib.get('class'): # prevent multiple "class" attribute adding if kwargs['css_class'] not in element.attrib['class']: # append "active" class element.attrib['class'] += ' {css_class}'.format( css_class=kwargs['css_class'], ) else: # create or set (if empty) "class" attribute element.attrib['class'] = kwargs['css_class'] return True # no "active" urls found return False
[ "def", "check_active", "(", "url", ",", "element", ",", "*", "*", "kwargs", ")", ":", "menu", "=", "yesno_to_bool", "(", "kwargs", "[", "'menu'", "]", ",", "'menu'", ")", "ignore_params", "=", "yesno_to_bool", "(", "kwargs", "[", "'ignore_params'", "]", ",", "'ignore_params'", ")", "# check missing href parameter", "if", "not", "url", ".", "attrib", ".", "get", "(", "'href'", ",", "None", ")", "is", "None", ":", "# get href attribute", "href", "=", "url", ".", "attrib", "[", "'href'", "]", ".", "strip", "(", ")", "# href=\"#\" is often used when links shouldn't be handled by browsers.", "# For example, Bootstrap uses this for expandable menus on", "# small screens, see", "# https://getbootstrap.com/docs/4.0/components/navs/#using-dropdowns", "if", "href", "==", "'#'", ":", "return", "False", "# split into urlparse object", "href", "=", "urlparse", ".", "urlsplit", "(", "href", ")", "# cut off hashtag (anchor)", "href", "=", "href", ".", "_replace", "(", "fragment", "=", "''", ")", "# cut off get params (?key=var&etc=var2)", "if", "ignore_params", ":", "href", "=", "href", ".", "_replace", "(", "query", "=", "''", ")", "kwargs", "[", "'full_path'", "]", "=", "urlparse", ".", "urlunsplit", "(", "urlparse", ".", "urlsplit", "(", "kwargs", "[", "'full_path'", "]", ")", ".", "_replace", "(", "query", "=", "''", ")", ")", "# build urlparse object back into string", "href", "=", "urlparse", ".", "urlunsplit", "(", "href", ")", "# check empty href", "if", "href", "==", "''", ":", "# replace href with current location", "href", "=", "kwargs", "[", "'full_path'", "]", "# compare full_path with href according to menu configuration", "if", "menu", ":", "# try mark \"root\" (/) url as \"active\", in equals way", "if", "href", "==", "'/'", "==", "kwargs", "[", "'full_path'", "]", ":", "logic", "=", "True", "# skip \"root\" (/) url, otherwise it will be always \"active\"", "elif", "href", "!=", "'/'", ":", "# start with logic", "logic", "=", "(", "kwargs", "[", "'full_path'", "]", ".", "startswith", "(", "href", ")", "or", "# maybe an urlquoted href was supplied", "urlquote", "(", "kwargs", "[", "'full_path'", "]", ")", ".", "startswith", "(", "href", ")", "or", "kwargs", "[", "'full_path'", "]", ".", "startswith", "(", "urlquote", "(", "href", ")", ")", ")", "else", ":", "logic", "=", "False", "else", ":", "# equals logic", "logic", "=", "(", "kwargs", "[", "'full_path'", "]", "==", "href", "or", "# maybe an urlquoted href was supplied", "urlquote", "(", "kwargs", "[", "'full_path'", "]", ")", "==", "href", "or", "kwargs", "[", "'full_path'", "]", "==", "urlquote", "(", "href", ")", ")", "# \"active\" url found", "if", "logic", ":", "# check parent tag has \"class\" attribute or it is empty", "if", "element", ".", "attrib", ".", "get", "(", "'class'", ")", ":", "# prevent multiple \"class\" attribute adding", "if", "kwargs", "[", "'css_class'", "]", "not", "in", "element", ".", "attrib", "[", "'class'", "]", ":", "# append \"active\" class", "element", ".", "attrib", "[", "'class'", "]", "+=", "' {css_class}'", ".", "format", "(", "css_class", "=", "kwargs", "[", "'css_class'", "]", ",", ")", "else", ":", "# create or set (if empty) \"class\" attribute", "element", ".", "attrib", "[", "'class'", "]", "=", "kwargs", "[", "'css_class'", "]", "return", "True", "# no \"active\" urls found", "return", "False" ]
check "active" url, apply css_class
[ "check", "active", "url", "apply", "css_class" ]
40d7f01b217641705fc5b7fe387e28e48ce332dc
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L102-L185
train
hellysmile/django-activeurl
django_activeurl/utils.py
check_content
def check_content(content, **kwargs): '''check content for "active" urls''' # valid html root tag try: # render elements tree from content tree = fragment_fromstring(content) # flag for prevent content rerendering, when no "active" urls found processed = False # django > 1.5 template boolean\None variables feature if isinstance(kwargs['parent_tag'], bool): if not kwargs['parent_tag']: kwargs['parent_tag'] = 'self' else: raise ImproperlyConfigured(''' parent_tag=True is not allowed ''') elif kwargs['parent_tag'] is None: kwargs['parent_tag'] = 'self' # if parent_tag is False\None\''\a\self # "active" status will be applied directly to "<a>" if kwargs['parent_tag'].lower() in ('a', 'self', ''): # xpath query to get all "<a>" urls = tree.xpath('.//a') # check "active" status for all urls for url in urls: if check_active(url, url, **kwargs): # mark flag for rerendering content processed = True # otherwise css_class must be applied to parent_tag else: # xpath query to get all parent tags elements = tree.xpath('.//{parent_tag}'.format( parent_tag=kwargs['parent_tag'], )) # check all elements for "active" "<a>" for element in elements: # xpath query to get all "<a>" urls = element.xpath('.//a') # check "active" status for all urls for url in urls: if check_active(url, element, **kwargs): # flag for rerendering content tree processed = True # stop checking other "<a>" break # do not rerender content if no "active" urls found if processed: # render content from tree return tostring(tree, encoding='unicode') # not valid html root tag except ParserError: # raise an exception with configuration example raise ImproperlyConfigured(''' content of {% activeurl %} must have valid html root tag for example {% activeurl %} <ul> <li> <a href="/page/">page</a> </li> <li> <a href="/other_page/">other_page</a> </li> </ul> {% endactiveurl %} in this case <ul> is valid content root tag ''') return content
python
def check_content(content, **kwargs): '''check content for "active" urls''' # valid html root tag try: # render elements tree from content tree = fragment_fromstring(content) # flag for prevent content rerendering, when no "active" urls found processed = False # django > 1.5 template boolean\None variables feature if isinstance(kwargs['parent_tag'], bool): if not kwargs['parent_tag']: kwargs['parent_tag'] = 'self' else: raise ImproperlyConfigured(''' parent_tag=True is not allowed ''') elif kwargs['parent_tag'] is None: kwargs['parent_tag'] = 'self' # if parent_tag is False\None\''\a\self # "active" status will be applied directly to "<a>" if kwargs['parent_tag'].lower() in ('a', 'self', ''): # xpath query to get all "<a>" urls = tree.xpath('.//a') # check "active" status for all urls for url in urls: if check_active(url, url, **kwargs): # mark flag for rerendering content processed = True # otherwise css_class must be applied to parent_tag else: # xpath query to get all parent tags elements = tree.xpath('.//{parent_tag}'.format( parent_tag=kwargs['parent_tag'], )) # check all elements for "active" "<a>" for element in elements: # xpath query to get all "<a>" urls = element.xpath('.//a') # check "active" status for all urls for url in urls: if check_active(url, element, **kwargs): # flag for rerendering content tree processed = True # stop checking other "<a>" break # do not rerender content if no "active" urls found if processed: # render content from tree return tostring(tree, encoding='unicode') # not valid html root tag except ParserError: # raise an exception with configuration example raise ImproperlyConfigured(''' content of {% activeurl %} must have valid html root tag for example {% activeurl %} <ul> <li> <a href="/page/">page</a> </li> <li> <a href="/other_page/">other_page</a> </li> </ul> {% endactiveurl %} in this case <ul> is valid content root tag ''') return content
[ "def", "check_content", "(", "content", ",", "*", "*", "kwargs", ")", ":", "# valid html root tag", "try", ":", "# render elements tree from content", "tree", "=", "fragment_fromstring", "(", "content", ")", "# flag for prevent content rerendering, when no \"active\" urls found", "processed", "=", "False", "# django > 1.5 template boolean\\None variables feature", "if", "isinstance", "(", "kwargs", "[", "'parent_tag'", "]", ",", "bool", ")", ":", "if", "not", "kwargs", "[", "'parent_tag'", "]", ":", "kwargs", "[", "'parent_tag'", "]", "=", "'self'", "else", ":", "raise", "ImproperlyConfigured", "(", "'''\n parent_tag=True is not allowed\n '''", ")", "elif", "kwargs", "[", "'parent_tag'", "]", "is", "None", ":", "kwargs", "[", "'parent_tag'", "]", "=", "'self'", "# if parent_tag is False\\None\\''\\a\\self", "# \"active\" status will be applied directly to \"<a>\"", "if", "kwargs", "[", "'parent_tag'", "]", ".", "lower", "(", ")", "in", "(", "'a'", ",", "'self'", ",", "''", ")", ":", "# xpath query to get all \"<a>\"", "urls", "=", "tree", ".", "xpath", "(", "'.//a'", ")", "# check \"active\" status for all urls", "for", "url", "in", "urls", ":", "if", "check_active", "(", "url", ",", "url", ",", "*", "*", "kwargs", ")", ":", "# mark flag for rerendering content", "processed", "=", "True", "# otherwise css_class must be applied to parent_tag", "else", ":", "# xpath query to get all parent tags", "elements", "=", "tree", ".", "xpath", "(", "'.//{parent_tag}'", ".", "format", "(", "parent_tag", "=", "kwargs", "[", "'parent_tag'", "]", ",", ")", ")", "# check all elements for \"active\" \"<a>\"", "for", "element", "in", "elements", ":", "# xpath query to get all \"<a>\"", "urls", "=", "element", ".", "xpath", "(", "'.//a'", ")", "# check \"active\" status for all urls", "for", "url", "in", "urls", ":", "if", "check_active", "(", "url", ",", "element", ",", "*", "*", "kwargs", ")", ":", "# flag for rerendering content tree", "processed", "=", "True", "# stop checking other \"<a>\"", "break", "# do not rerender content if no \"active\" urls found", "if", "processed", ":", "# render content from tree", "return", "tostring", "(", "tree", ",", "encoding", "=", "'unicode'", ")", "# not valid html root tag", "except", "ParserError", ":", "# raise an exception with configuration example", "raise", "ImproperlyConfigured", "(", "'''\n content of {% activeurl %} must have valid html root tag\n for example\n {% activeurl %}\n <ul>\n <li>\n <a href=\"/page/\">page</a>\n </li>\n <li>\n <a href=\"/other_page/\">other_page</a>\n </li>\n </ul>\n {% endactiveurl %}\n in this case <ul> is valid content root tag\n '''", ")", "return", "content" ]
check content for "active" urls
[ "check", "content", "for", "active", "urls" ]
40d7f01b217641705fc5b7fe387e28e48ce332dc
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L188-L255
train
hellysmile/django-activeurl
django_activeurl/utils.py
render_content
def render_content(content, **kwargs): '''check content for "active" urls, store results to django cache''' # try to take pre rendered content from django cache, if caching is enabled if settings.ACTIVE_URL_CACHE: cache_key = get_cache_key(content, **kwargs) # get cached content from django cache backend from_cache = cache.get(cache_key) # return pre rendered content if it exist in cache if from_cache is not None: return from_cache # render content with "active" logic content = check_content(content, **kwargs) # write rendered content to django cache backend, if caching is enabled if settings.ACTIVE_URL_CACHE: cache.set(cache_key, content, settings.ACTIVE_URL_CACHE_TIMEOUT) return content
python
def render_content(content, **kwargs): '''check content for "active" urls, store results to django cache''' # try to take pre rendered content from django cache, if caching is enabled if settings.ACTIVE_URL_CACHE: cache_key = get_cache_key(content, **kwargs) # get cached content from django cache backend from_cache = cache.get(cache_key) # return pre rendered content if it exist in cache if from_cache is not None: return from_cache # render content with "active" logic content = check_content(content, **kwargs) # write rendered content to django cache backend, if caching is enabled if settings.ACTIVE_URL_CACHE: cache.set(cache_key, content, settings.ACTIVE_URL_CACHE_TIMEOUT) return content
[ "def", "render_content", "(", "content", ",", "*", "*", "kwargs", ")", ":", "# try to take pre rendered content from django cache, if caching is enabled", "if", "settings", ".", "ACTIVE_URL_CACHE", ":", "cache_key", "=", "get_cache_key", "(", "content", ",", "*", "*", "kwargs", ")", "# get cached content from django cache backend", "from_cache", "=", "cache", ".", "get", "(", "cache_key", ")", "# return pre rendered content if it exist in cache", "if", "from_cache", "is", "not", "None", ":", "return", "from_cache", "# render content with \"active\" logic", "content", "=", "check_content", "(", "content", ",", "*", "*", "kwargs", ")", "# write rendered content to django cache backend, if caching is enabled", "if", "settings", ".", "ACTIVE_URL_CACHE", ":", "cache", ".", "set", "(", "cache_key", ",", "content", ",", "settings", ".", "ACTIVE_URL_CACHE_TIMEOUT", ")", "return", "content" ]
check content for "active" urls, store results to django cache
[ "check", "content", "for", "active", "urls", "store", "results", "to", "django", "cache" ]
40d7f01b217641705fc5b7fe387e28e48ce332dc
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L258-L278
train
hellysmile/django-activeurl
django_activeurl/utils.py
Configuration.load_configuration
def load_configuration(self, **kwargs): '''load configuration, merge with default settings''' # update passed arguments with default values for key in settings.ACTIVE_URL_KWARGS: kwargs.setdefault(key, settings.ACTIVE_URL_KWARGS[key]) # "active" html tag css class self.css_class = kwargs['css_class'] # "active" html tag self.parent_tag = kwargs['parent_tag'] # flipper for menu support self.menu = kwargs['menu'] # whether to ignore / chomp get_params self.ignore_params = kwargs['ignore_params']
python
def load_configuration(self, **kwargs): '''load configuration, merge with default settings''' # update passed arguments with default values for key in settings.ACTIVE_URL_KWARGS: kwargs.setdefault(key, settings.ACTIVE_URL_KWARGS[key]) # "active" html tag css class self.css_class = kwargs['css_class'] # "active" html tag self.parent_tag = kwargs['parent_tag'] # flipper for menu support self.menu = kwargs['menu'] # whether to ignore / chomp get_params self.ignore_params = kwargs['ignore_params']
[ "def", "load_configuration", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# update passed arguments with default values", "for", "key", "in", "settings", ".", "ACTIVE_URL_KWARGS", ":", "kwargs", ".", "setdefault", "(", "key", ",", "settings", ".", "ACTIVE_URL_KWARGS", "[", "key", "]", ")", "# \"active\" html tag css class", "self", ".", "css_class", "=", "kwargs", "[", "'css_class'", "]", "# \"active\" html tag", "self", ".", "parent_tag", "=", "kwargs", "[", "'parent_tag'", "]", "# flipper for menu support", "self", ".", "menu", "=", "kwargs", "[", "'menu'", "]", "# whether to ignore / chomp get_params", "self", ".", "ignore_params", "=", "kwargs", "[", "'ignore_params'", "]" ]
load configuration, merge with default settings
[ "load", "configuration", "merge", "with", "default", "settings" ]
40d7f01b217641705fc5b7fe387e28e48ce332dc
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L26-L39
train
thefactory/marathon-python
marathon/client.py
MarathonClient._parse_response
def _parse_response(response, clazz, is_list=False, resource_name=None): """Parse a Marathon response into an object or list of objects.""" target = response.json()[ resource_name] if resource_name else response.json() if is_list: return [clazz.from_json(resource) for resource in target] else: return clazz.from_json(target)
python
def _parse_response(response, clazz, is_list=False, resource_name=None): """Parse a Marathon response into an object or list of objects.""" target = response.json()[ resource_name] if resource_name else response.json() if is_list: return [clazz.from_json(resource) for resource in target] else: return clazz.from_json(target)
[ "def", "_parse_response", "(", "response", ",", "clazz", ",", "is_list", "=", "False", ",", "resource_name", "=", "None", ")", ":", "target", "=", "response", ".", "json", "(", ")", "[", "resource_name", "]", "if", "resource_name", "else", "response", ".", "json", "(", ")", "if", "is_list", ":", "return", "[", "clazz", ".", "from_json", "(", "resource", ")", "for", "resource", "in", "target", "]", "else", ":", "return", "clazz", ".", "from_json", "(", "target", ")" ]
Parse a Marathon response into an object or list of objects.
[ "Parse", "a", "Marathon", "response", "into", "an", "object", "or", "list", "of", "objects", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L67-L74
train
thefactory/marathon-python
marathon/client.py
MarathonClient._do_request
def _do_request(self, method, path, params=None, data=None): """Query Marathon server.""" headers = { 'Content-Type': 'application/json', 'Accept': 'application/json'} if self.auth_token: headers['Authorization'] = "token={}".format(self.auth_token) response = None servers = list(self.servers) while servers and response is None: server = servers.pop(0) url = ''.join([server.rstrip('/'), path]) try: response = self.session.request( method, url, params=params, data=data, headers=headers, auth=self.auth, timeout=self.timeout, verify=self.verify) marathon.log.info('Got response from %s', server) except requests.exceptions.RequestException as e: marathon.log.error( 'Error while calling %s: %s', url, str(e)) if response is None: raise NoResponseError('No remaining Marathon servers to try') if response.status_code >= 500: marathon.log.error('Got HTTP {code}: {body}'.format( code=response.status_code, body=response.text.encode('utf-8'))) raise InternalServerError(response) elif response.status_code >= 400: marathon.log.error('Got HTTP {code}: {body}'.format( code=response.status_code, body=response.text.encode('utf-8'))) if response.status_code == 404: raise NotFoundError(response) elif response.status_code == 409: raise ConflictError(response) else: raise MarathonHttpError(response) elif response.status_code >= 300: marathon.log.warn('Got HTTP {code}: {body}'.format( code=response.status_code, body=response.text.encode('utf-8'))) else: marathon.log.debug('Got HTTP {code}: {body}'.format( code=response.status_code, body=response.text.encode('utf-8'))) return response
python
def _do_request(self, method, path, params=None, data=None): """Query Marathon server.""" headers = { 'Content-Type': 'application/json', 'Accept': 'application/json'} if self.auth_token: headers['Authorization'] = "token={}".format(self.auth_token) response = None servers = list(self.servers) while servers and response is None: server = servers.pop(0) url = ''.join([server.rstrip('/'), path]) try: response = self.session.request( method, url, params=params, data=data, headers=headers, auth=self.auth, timeout=self.timeout, verify=self.verify) marathon.log.info('Got response from %s', server) except requests.exceptions.RequestException as e: marathon.log.error( 'Error while calling %s: %s', url, str(e)) if response is None: raise NoResponseError('No remaining Marathon servers to try') if response.status_code >= 500: marathon.log.error('Got HTTP {code}: {body}'.format( code=response.status_code, body=response.text.encode('utf-8'))) raise InternalServerError(response) elif response.status_code >= 400: marathon.log.error('Got HTTP {code}: {body}'.format( code=response.status_code, body=response.text.encode('utf-8'))) if response.status_code == 404: raise NotFoundError(response) elif response.status_code == 409: raise ConflictError(response) else: raise MarathonHttpError(response) elif response.status_code >= 300: marathon.log.warn('Got HTTP {code}: {body}'.format( code=response.status_code, body=response.text.encode('utf-8'))) else: marathon.log.debug('Got HTTP {code}: {body}'.format( code=response.status_code, body=response.text.encode('utf-8'))) return response
[ "def", "_do_request", "(", "self", ",", "method", ",", "path", ",", "params", "=", "None", ",", "data", "=", "None", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'Accept'", ":", "'application/json'", "}", "if", "self", ".", "auth_token", ":", "headers", "[", "'Authorization'", "]", "=", "\"token={}\"", ".", "format", "(", "self", ".", "auth_token", ")", "response", "=", "None", "servers", "=", "list", "(", "self", ".", "servers", ")", "while", "servers", "and", "response", "is", "None", ":", "server", "=", "servers", ".", "pop", "(", "0", ")", "url", "=", "''", ".", "join", "(", "[", "server", ".", "rstrip", "(", "'/'", ")", ",", "path", "]", ")", "try", ":", "response", "=", "self", ".", "session", ".", "request", "(", "method", ",", "url", ",", "params", "=", "params", ",", "data", "=", "data", ",", "headers", "=", "headers", ",", "auth", "=", "self", ".", "auth", ",", "timeout", "=", "self", ".", "timeout", ",", "verify", "=", "self", ".", "verify", ")", "marathon", ".", "log", ".", "info", "(", "'Got response from %s'", ",", "server", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "marathon", ".", "log", ".", "error", "(", "'Error while calling %s: %s'", ",", "url", ",", "str", "(", "e", ")", ")", "if", "response", "is", "None", ":", "raise", "NoResponseError", "(", "'No remaining Marathon servers to try'", ")", "if", "response", ".", "status_code", ">=", "500", ":", "marathon", ".", "log", ".", "error", "(", "'Got HTTP {code}: {body}'", ".", "format", "(", "code", "=", "response", ".", "status_code", ",", "body", "=", "response", ".", "text", ".", "encode", "(", "'utf-8'", ")", ")", ")", "raise", "InternalServerError", "(", "response", ")", "elif", "response", ".", "status_code", ">=", "400", ":", "marathon", ".", "log", ".", "error", "(", "'Got HTTP {code}: {body}'", ".", "format", "(", "code", "=", "response", ".", "status_code", ",", "body", "=", "response", ".", "text", ".", "encode", "(", "'utf-8'", ")", ")", ")", "if", "response", ".", "status_code", "==", "404", ":", "raise", "NotFoundError", "(", "response", ")", "elif", "response", ".", "status_code", "==", "409", ":", "raise", "ConflictError", "(", "response", ")", "else", ":", "raise", "MarathonHttpError", "(", "response", ")", "elif", "response", ".", "status_code", ">=", "300", ":", "marathon", ".", "log", ".", "warn", "(", "'Got HTTP {code}: {body}'", ".", "format", "(", "code", "=", "response", ".", "status_code", ",", "body", "=", "response", ".", "text", ".", "encode", "(", "'utf-8'", ")", ")", ")", "else", ":", "marathon", ".", "log", ".", "debug", "(", "'Got HTTP {code}: {body}'", ".", "format", "(", "code", "=", "response", ".", "status_code", ",", "body", "=", "response", ".", "text", ".", "encode", "(", "'utf-8'", ")", ")", ")", "return", "response" ]
Query Marathon server.
[ "Query", "Marathon", "server", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L76-L121
train
thefactory/marathon-python
marathon/client.py
MarathonClient._do_sse_request
def _do_sse_request(self, path, params=None): """Query Marathon server for events.""" urls = [''.join([server.rstrip('/'), path]) for server in self.servers] while urls: url = urls.pop() try: # Requests does not set the original Authorization header on cross origin # redirects. If set allow_redirects=True we may get a 401 response. response = self.sse_session.get( url, params=params, stream=True, headers={'Accept': 'text/event-stream'}, auth=self.auth, verify=self.verify, allow_redirects=False ) except Exception as e: marathon.log.error( 'Error while calling %s: %s', url, e.message) else: if response.is_redirect and response.next: urls.append(response.next.url) marathon.log.debug("Got redirect to {}".format(response.next.url)) elif response.ok: return response.iter_lines() raise MarathonError('No remaining Marathon servers to try')
python
def _do_sse_request(self, path, params=None): """Query Marathon server for events.""" urls = [''.join([server.rstrip('/'), path]) for server in self.servers] while urls: url = urls.pop() try: # Requests does not set the original Authorization header on cross origin # redirects. If set allow_redirects=True we may get a 401 response. response = self.sse_session.get( url, params=params, stream=True, headers={'Accept': 'text/event-stream'}, auth=self.auth, verify=self.verify, allow_redirects=False ) except Exception as e: marathon.log.error( 'Error while calling %s: %s', url, e.message) else: if response.is_redirect and response.next: urls.append(response.next.url) marathon.log.debug("Got redirect to {}".format(response.next.url)) elif response.ok: return response.iter_lines() raise MarathonError('No remaining Marathon servers to try')
[ "def", "_do_sse_request", "(", "self", ",", "path", ",", "params", "=", "None", ")", ":", "urls", "=", "[", "''", ".", "join", "(", "[", "server", ".", "rstrip", "(", "'/'", ")", ",", "path", "]", ")", "for", "server", "in", "self", ".", "servers", "]", "while", "urls", ":", "url", "=", "urls", ".", "pop", "(", ")", "try", ":", "# Requests does not set the original Authorization header on cross origin", "# redirects. If set allow_redirects=True we may get a 401 response.", "response", "=", "self", ".", "sse_session", ".", "get", "(", "url", ",", "params", "=", "params", ",", "stream", "=", "True", ",", "headers", "=", "{", "'Accept'", ":", "'text/event-stream'", "}", ",", "auth", "=", "self", ".", "auth", ",", "verify", "=", "self", ".", "verify", ",", "allow_redirects", "=", "False", ")", "except", "Exception", "as", "e", ":", "marathon", ".", "log", ".", "error", "(", "'Error while calling %s: %s'", ",", "url", ",", "e", ".", "message", ")", "else", ":", "if", "response", ".", "is_redirect", "and", "response", ".", "next", ":", "urls", ".", "append", "(", "response", ".", "next", ".", "url", ")", "marathon", ".", "log", ".", "debug", "(", "\"Got redirect to {}\"", ".", "format", "(", "response", ".", "next", ".", "url", ")", ")", "elif", "response", ".", "ok", ":", "return", "response", ".", "iter_lines", "(", ")", "raise", "MarathonError", "(", "'No remaining Marathon servers to try'", ")" ]
Query Marathon server for events.
[ "Query", "Marathon", "server", "for", "events", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L123-L150
train
thefactory/marathon-python
marathon/client.py
MarathonClient.create_app
def create_app(self, app_id, app, minimal=True): """Create and start an app. :param str app_id: application ID :param :class:`marathon.models.app.MarathonApp` app: the application to create :param bool minimal: ignore nulls and empty collections :returns: the created app (on success) :rtype: :class:`marathon.models.app.MarathonApp` or False """ app.id = app_id data = app.to_json(minimal=minimal) response = self._do_request('POST', '/v2/apps', data=data) if response.status_code == 201: return self._parse_response(response, MarathonApp) else: return False
python
def create_app(self, app_id, app, minimal=True): """Create and start an app. :param str app_id: application ID :param :class:`marathon.models.app.MarathonApp` app: the application to create :param bool minimal: ignore nulls and empty collections :returns: the created app (on success) :rtype: :class:`marathon.models.app.MarathonApp` or False """ app.id = app_id data = app.to_json(minimal=minimal) response = self._do_request('POST', '/v2/apps', data=data) if response.status_code == 201: return self._parse_response(response, MarathonApp) else: return False
[ "def", "create_app", "(", "self", ",", "app_id", ",", "app", ",", "minimal", "=", "True", ")", ":", "app", ".", "id", "=", "app_id", "data", "=", "app", ".", "to_json", "(", "minimal", "=", "minimal", ")", "response", "=", "self", ".", "_do_request", "(", "'POST'", ",", "'/v2/apps'", ",", "data", "=", "data", ")", "if", "response", ".", "status_code", "==", "201", ":", "return", "self", ".", "_parse_response", "(", "response", ",", "MarathonApp", ")", "else", ":", "return", "False" ]
Create and start an app. :param str app_id: application ID :param :class:`marathon.models.app.MarathonApp` app: the application to create :param bool minimal: ignore nulls and empty collections :returns: the created app (on success) :rtype: :class:`marathon.models.app.MarathonApp` or False
[ "Create", "and", "start", "an", "app", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L160-L176
train
thefactory/marathon-python
marathon/client.py
MarathonClient.list_apps
def list_apps(self, cmd=None, embed_tasks=False, embed_counts=False, embed_deployments=False, embed_readiness=False, embed_last_task_failure=False, embed_failures=False, embed_task_stats=False, app_id=None, label=None, **kwargs): """List all apps. :param str cmd: if passed, only show apps with a matching `cmd` :param bool embed_tasks: embed tasks in result :param bool embed_counts: embed all task counts :param bool embed_deployments: embed all deployment identifier :param bool embed_readiness: embed all readiness check results :param bool embed_last_task_failure: embeds the last task failure :param bool embed_failures: shorthand for embed_last_task_failure :param bool embed_task_stats: embed task stats in result :param str app_id: if passed, only show apps with an 'id' that matches or contains this value :param str label: if passed, only show apps with the selected labels :param kwargs: arbitrary search filters :returns: list of applications :rtype: list[:class:`marathon.models.app.MarathonApp`] """ params = {} if cmd: params['cmd'] = cmd if app_id: params['id'] = app_id if label: params['label'] = label embed_params = { 'app.tasks': embed_tasks, 'app.counts': embed_counts, 'app.deployments': embed_deployments, 'app.readiness': embed_readiness, 'app.lastTaskFailure': embed_last_task_failure, 'app.failures': embed_failures, 'app.taskStats': embed_task_stats } filtered_embed_params = [k for (k, v) in embed_params.items() if v] if filtered_embed_params: params['embed'] = filtered_embed_params response = self._do_request('GET', '/v2/apps', params=params) apps = self._parse_response( response, MarathonApp, is_list=True, resource_name='apps') for k, v in kwargs.items(): apps = [o for o in apps if getattr(o, k) == v] return apps
python
def list_apps(self, cmd=None, embed_tasks=False, embed_counts=False, embed_deployments=False, embed_readiness=False, embed_last_task_failure=False, embed_failures=False, embed_task_stats=False, app_id=None, label=None, **kwargs): """List all apps. :param str cmd: if passed, only show apps with a matching `cmd` :param bool embed_tasks: embed tasks in result :param bool embed_counts: embed all task counts :param bool embed_deployments: embed all deployment identifier :param bool embed_readiness: embed all readiness check results :param bool embed_last_task_failure: embeds the last task failure :param bool embed_failures: shorthand for embed_last_task_failure :param bool embed_task_stats: embed task stats in result :param str app_id: if passed, only show apps with an 'id' that matches or contains this value :param str label: if passed, only show apps with the selected labels :param kwargs: arbitrary search filters :returns: list of applications :rtype: list[:class:`marathon.models.app.MarathonApp`] """ params = {} if cmd: params['cmd'] = cmd if app_id: params['id'] = app_id if label: params['label'] = label embed_params = { 'app.tasks': embed_tasks, 'app.counts': embed_counts, 'app.deployments': embed_deployments, 'app.readiness': embed_readiness, 'app.lastTaskFailure': embed_last_task_failure, 'app.failures': embed_failures, 'app.taskStats': embed_task_stats } filtered_embed_params = [k for (k, v) in embed_params.items() if v] if filtered_embed_params: params['embed'] = filtered_embed_params response = self._do_request('GET', '/v2/apps', params=params) apps = self._parse_response( response, MarathonApp, is_list=True, resource_name='apps') for k, v in kwargs.items(): apps = [o for o in apps if getattr(o, k) == v] return apps
[ "def", "list_apps", "(", "self", ",", "cmd", "=", "None", ",", "embed_tasks", "=", "False", ",", "embed_counts", "=", "False", ",", "embed_deployments", "=", "False", ",", "embed_readiness", "=", "False", ",", "embed_last_task_failure", "=", "False", ",", "embed_failures", "=", "False", ",", "embed_task_stats", "=", "False", ",", "app_id", "=", "None", ",", "label", "=", "None", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "}", "if", "cmd", ":", "params", "[", "'cmd'", "]", "=", "cmd", "if", "app_id", ":", "params", "[", "'id'", "]", "=", "app_id", "if", "label", ":", "params", "[", "'label'", "]", "=", "label", "embed_params", "=", "{", "'app.tasks'", ":", "embed_tasks", ",", "'app.counts'", ":", "embed_counts", ",", "'app.deployments'", ":", "embed_deployments", ",", "'app.readiness'", ":", "embed_readiness", ",", "'app.lastTaskFailure'", ":", "embed_last_task_failure", ",", "'app.failures'", ":", "embed_failures", ",", "'app.taskStats'", ":", "embed_task_stats", "}", "filtered_embed_params", "=", "[", "k", "for", "(", "k", ",", "v", ")", "in", "embed_params", ".", "items", "(", ")", "if", "v", "]", "if", "filtered_embed_params", ":", "params", "[", "'embed'", "]", "=", "filtered_embed_params", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/apps'", ",", "params", "=", "params", ")", "apps", "=", "self", ".", "_parse_response", "(", "response", ",", "MarathonApp", ",", "is_list", "=", "True", ",", "resource_name", "=", "'apps'", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "apps", "=", "[", "o", "for", "o", "in", "apps", "if", "getattr", "(", "o", ",", "k", ")", "==", "v", "]", "return", "apps" ]
List all apps. :param str cmd: if passed, only show apps with a matching `cmd` :param bool embed_tasks: embed tasks in result :param bool embed_counts: embed all task counts :param bool embed_deployments: embed all deployment identifier :param bool embed_readiness: embed all readiness check results :param bool embed_last_task_failure: embeds the last task failure :param bool embed_failures: shorthand for embed_last_task_failure :param bool embed_task_stats: embed task stats in result :param str app_id: if passed, only show apps with an 'id' that matches or contains this value :param str label: if passed, only show apps with the selected labels :param kwargs: arbitrary search filters :returns: list of applications :rtype: list[:class:`marathon.models.app.MarathonApp`]
[ "List", "all", "apps", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L178-L225
train
thefactory/marathon-python
marathon/client.py
MarathonClient.get_app
def get_app(self, app_id, embed_tasks=False, embed_counts=False, embed_deployments=False, embed_readiness=False, embed_last_task_failure=False, embed_failures=False, embed_task_stats=False): """Get a single app. :param str app_id: application ID :param bool embed_tasks: embed tasks in result :param bool embed_counts: embed all task counts :param bool embed_deployments: embed all deployment identifier :param bool embed_readiness: embed all readiness check results :param bool embed_last_task_failure: embeds the last task failure :param bool embed_failures: shorthand for embed_last_task_failure :param bool embed_task_stats: embed task stats in result :returns: application :rtype: :class:`marathon.models.app.MarathonApp` """ params = {} embed_params = { 'app.tasks': embed_tasks, 'app.counts': embed_counts, 'app.deployments': embed_deployments, 'app.readiness': embed_readiness, 'app.lastTaskFailure': embed_last_task_failure, 'app.failures': embed_failures, 'app.taskStats': embed_task_stats } filtered_embed_params = [k for (k, v) in embed_params.items() if v] if filtered_embed_params: params['embed'] = filtered_embed_params response = self._do_request( 'GET', '/v2/apps/{app_id}'.format(app_id=app_id), params=params) return self._parse_response(response, MarathonApp, resource_name='app')
python
def get_app(self, app_id, embed_tasks=False, embed_counts=False, embed_deployments=False, embed_readiness=False, embed_last_task_failure=False, embed_failures=False, embed_task_stats=False): """Get a single app. :param str app_id: application ID :param bool embed_tasks: embed tasks in result :param bool embed_counts: embed all task counts :param bool embed_deployments: embed all deployment identifier :param bool embed_readiness: embed all readiness check results :param bool embed_last_task_failure: embeds the last task failure :param bool embed_failures: shorthand for embed_last_task_failure :param bool embed_task_stats: embed task stats in result :returns: application :rtype: :class:`marathon.models.app.MarathonApp` """ params = {} embed_params = { 'app.tasks': embed_tasks, 'app.counts': embed_counts, 'app.deployments': embed_deployments, 'app.readiness': embed_readiness, 'app.lastTaskFailure': embed_last_task_failure, 'app.failures': embed_failures, 'app.taskStats': embed_task_stats } filtered_embed_params = [k for (k, v) in embed_params.items() if v] if filtered_embed_params: params['embed'] = filtered_embed_params response = self._do_request( 'GET', '/v2/apps/{app_id}'.format(app_id=app_id), params=params) return self._parse_response(response, MarathonApp, resource_name='app')
[ "def", "get_app", "(", "self", ",", "app_id", ",", "embed_tasks", "=", "False", ",", "embed_counts", "=", "False", ",", "embed_deployments", "=", "False", ",", "embed_readiness", "=", "False", ",", "embed_last_task_failure", "=", "False", ",", "embed_failures", "=", "False", ",", "embed_task_stats", "=", "False", ")", ":", "params", "=", "{", "}", "embed_params", "=", "{", "'app.tasks'", ":", "embed_tasks", ",", "'app.counts'", ":", "embed_counts", ",", "'app.deployments'", ":", "embed_deployments", ",", "'app.readiness'", ":", "embed_readiness", ",", "'app.lastTaskFailure'", ":", "embed_last_task_failure", ",", "'app.failures'", ":", "embed_failures", ",", "'app.taskStats'", ":", "embed_task_stats", "}", "filtered_embed_params", "=", "[", "k", "for", "(", "k", ",", "v", ")", "in", "embed_params", ".", "items", "(", ")", "if", "v", "]", "if", "filtered_embed_params", ":", "params", "[", "'embed'", "]", "=", "filtered_embed_params", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/apps/{app_id}'", ".", "format", "(", "app_id", "=", "app_id", ")", ",", "params", "=", "params", ")", "return", "self", ".", "_parse_response", "(", "response", ",", "MarathonApp", ",", "resource_name", "=", "'app'", ")" ]
Get a single app. :param str app_id: application ID :param bool embed_tasks: embed tasks in result :param bool embed_counts: embed all task counts :param bool embed_deployments: embed all deployment identifier :param bool embed_readiness: embed all readiness check results :param bool embed_last_task_failure: embeds the last task failure :param bool embed_failures: shorthand for embed_last_task_failure :param bool embed_task_stats: embed task stats in result :returns: application :rtype: :class:`marathon.models.app.MarathonApp`
[ "Get", "a", "single", "app", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L227-L261
train
thefactory/marathon-python
marathon/client.py
MarathonClient.update_app
def update_app(self, app_id, app, force=False, minimal=True): """Update an app. Applies writable settings in `app` to `app_id` Note: this method can not be used to rename apps. :param str app_id: target application ID :param app: application settings :type app: :class:`marathon.models.app.MarathonApp` :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict """ # Changes won't take if version is set - blank it for convenience app.version = None params = {'force': force} data = app.to_json(minimal=minimal) response = self._do_request( 'PUT', '/v2/apps/{app_id}'.format(app_id=app_id), params=params, data=data) return response.json()
python
def update_app(self, app_id, app, force=False, minimal=True): """Update an app. Applies writable settings in `app` to `app_id` Note: this method can not be used to rename apps. :param str app_id: target application ID :param app: application settings :type app: :class:`marathon.models.app.MarathonApp` :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict """ # Changes won't take if version is set - blank it for convenience app.version = None params = {'force': force} data = app.to_json(minimal=minimal) response = self._do_request( 'PUT', '/v2/apps/{app_id}'.format(app_id=app_id), params=params, data=data) return response.json()
[ "def", "update_app", "(", "self", ",", "app_id", ",", "app", ",", "force", "=", "False", ",", "minimal", "=", "True", ")", ":", "# Changes won't take if version is set - blank it for convenience", "app", ".", "version", "=", "None", "params", "=", "{", "'force'", ":", "force", "}", "data", "=", "app", ".", "to_json", "(", "minimal", "=", "minimal", ")", "response", "=", "self", ".", "_do_request", "(", "'PUT'", ",", "'/v2/apps/{app_id}'", ".", "format", "(", "app_id", "=", "app_id", ")", ",", "params", "=", "params", ",", "data", "=", "data", ")", "return", "response", ".", "json", "(", ")" ]
Update an app. Applies writable settings in `app` to `app_id` Note: this method can not be used to rename apps. :param str app_id: target application ID :param app: application settings :type app: :class:`marathon.models.app.MarathonApp` :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict
[ "Update", "an", "app", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L276-L299
train
thefactory/marathon-python
marathon/client.py
MarathonClient.update_apps
def update_apps(self, apps, force=False, minimal=True): """Update multiple apps. Applies writable settings in elements of apps either by upgrading existing ones or creating new ones :param apps: sequence of application settings :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict """ json_repr_apps = [] for app in apps: # Changes won't take if version is set - blank it for convenience app.version = None json_repr_apps.append(app.json_repr(minimal=minimal)) params = {'force': force} encoder = MarathonMinimalJsonEncoder if minimal else MarathonJsonEncoder data = json.dumps(json_repr_apps, cls=encoder, sort_keys=True) response = self._do_request( 'PUT', '/v2/apps', params=params, data=data) return response.json()
python
def update_apps(self, apps, force=False, minimal=True): """Update multiple apps. Applies writable settings in elements of apps either by upgrading existing ones or creating new ones :param apps: sequence of application settings :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict """ json_repr_apps = [] for app in apps: # Changes won't take if version is set - blank it for convenience app.version = None json_repr_apps.append(app.json_repr(minimal=minimal)) params = {'force': force} encoder = MarathonMinimalJsonEncoder if minimal else MarathonJsonEncoder data = json.dumps(json_repr_apps, cls=encoder, sort_keys=True) response = self._do_request( 'PUT', '/v2/apps', params=params, data=data) return response.json()
[ "def", "update_apps", "(", "self", ",", "apps", ",", "force", "=", "False", ",", "minimal", "=", "True", ")", ":", "json_repr_apps", "=", "[", "]", "for", "app", "in", "apps", ":", "# Changes won't take if version is set - blank it for convenience", "app", ".", "version", "=", "None", "json_repr_apps", ".", "append", "(", "app", ".", "json_repr", "(", "minimal", "=", "minimal", ")", ")", "params", "=", "{", "'force'", ":", "force", "}", "encoder", "=", "MarathonMinimalJsonEncoder", "if", "minimal", "else", "MarathonJsonEncoder", "data", "=", "json", ".", "dumps", "(", "json_repr_apps", ",", "cls", "=", "encoder", ",", "sort_keys", "=", "True", ")", "response", "=", "self", ".", "_do_request", "(", "'PUT'", ",", "'/v2/apps'", ",", "params", "=", "params", ",", "data", "=", "data", ")", "return", "response", ".", "json", "(", ")" ]
Update multiple apps. Applies writable settings in elements of apps either by upgrading existing ones or creating new ones :param apps: sequence of application settings :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict
[ "Update", "multiple", "apps", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L301-L325
train
thefactory/marathon-python
marathon/client.py
MarathonClient.rollback_app
def rollback_app(self, app_id, version, force=False): """Roll an app back to a previous version. :param str app_id: application ID :param str version: application version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict """ params = {'force': force} data = json.dumps({'version': version}) response = self._do_request( 'PUT', '/v2/apps/{app_id}'.format(app_id=app_id), params=params, data=data) return response.json()
python
def rollback_app(self, app_id, version, force=False): """Roll an app back to a previous version. :param str app_id: application ID :param str version: application version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict """ params = {'force': force} data = json.dumps({'version': version}) response = self._do_request( 'PUT', '/v2/apps/{app_id}'.format(app_id=app_id), params=params, data=data) return response.json()
[ "def", "rollback_app", "(", "self", ",", "app_id", ",", "version", ",", "force", "=", "False", ")", ":", "params", "=", "{", "'force'", ":", "force", "}", "data", "=", "json", ".", "dumps", "(", "{", "'version'", ":", "version", "}", ")", "response", "=", "self", ".", "_do_request", "(", "'PUT'", ",", "'/v2/apps/{app_id}'", ".", "format", "(", "app_id", "=", "app_id", ")", ",", "params", "=", "params", ",", "data", "=", "data", ")", "return", "response", ".", "json", "(", ")" ]
Roll an app back to a previous version. :param str app_id: application ID :param str version: application version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict
[ "Roll", "an", "app", "back", "to", "a", "previous", "version", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L327-L341
train
thefactory/marathon-python
marathon/client.py
MarathonClient.delete_app
def delete_app(self, app_id, force=False): """Stop and destroy an app. :param str app_id: application ID :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict """ params = {'force': force} response = self._do_request( 'DELETE', '/v2/apps/{app_id}'.format(app_id=app_id), params=params) return response.json()
python
def delete_app(self, app_id, force=False): """Stop and destroy an app. :param str app_id: application ID :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict """ params = {'force': force} response = self._do_request( 'DELETE', '/v2/apps/{app_id}'.format(app_id=app_id), params=params) return response.json()
[ "def", "delete_app", "(", "self", ",", "app_id", ",", "force", "=", "False", ")", ":", "params", "=", "{", "'force'", ":", "force", "}", "response", "=", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/apps/{app_id}'", ".", "format", "(", "app_id", "=", "app_id", ")", ",", "params", "=", "params", ")", "return", "response", ".", "json", "(", ")" ]
Stop and destroy an app. :param str app_id: application ID :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict
[ "Stop", "and", "destroy", "an", "app", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L343-L355
train
thefactory/marathon-python
marathon/client.py
MarathonClient.scale_app
def scale_app(self, app_id, instances=None, delta=None, force=False): """Scale an app. Scale an app to a target number of instances (with `instances`), or scale the number of instances up or down by some delta (`delta`). If the resulting number of instances would be negative, desired instances will be set to zero. If both `instances` and `delta` are passed, use `instances`. :param str app_id: application ID :param int instances: [optional] the number of instances to scale to :param int delta: [optional] the number of instances to scale up or down by :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict """ if instances is None and delta is None: marathon.log.error('instances or delta must be passed') return try: app = self.get_app(app_id) except NotFoundError: marathon.log.error('App "{app}" not found'.format(app=app_id)) return desired = instances if instances is not None else ( app.instances + delta) return self.update_app(app.id, MarathonApp(instances=desired), force=force)
python
def scale_app(self, app_id, instances=None, delta=None, force=False): """Scale an app. Scale an app to a target number of instances (with `instances`), or scale the number of instances up or down by some delta (`delta`). If the resulting number of instances would be negative, desired instances will be set to zero. If both `instances` and `delta` are passed, use `instances`. :param str app_id: application ID :param int instances: [optional] the number of instances to scale to :param int delta: [optional] the number of instances to scale up or down by :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict """ if instances is None and delta is None: marathon.log.error('instances or delta must be passed') return try: app = self.get_app(app_id) except NotFoundError: marathon.log.error('App "{app}" not found'.format(app=app_id)) return desired = instances if instances is not None else ( app.instances + delta) return self.update_app(app.id, MarathonApp(instances=desired), force=force)
[ "def", "scale_app", "(", "self", ",", "app_id", ",", "instances", "=", "None", ",", "delta", "=", "None", ",", "force", "=", "False", ")", ":", "if", "instances", "is", "None", "and", "delta", "is", "None", ":", "marathon", ".", "log", ".", "error", "(", "'instances or delta must be passed'", ")", "return", "try", ":", "app", "=", "self", ".", "get_app", "(", "app_id", ")", "except", "NotFoundError", ":", "marathon", ".", "log", ".", "error", "(", "'App \"{app}\" not found'", ".", "format", "(", "app", "=", "app_id", ")", ")", "return", "desired", "=", "instances", "if", "instances", "is", "not", "None", "else", "(", "app", ".", "instances", "+", "delta", ")", "return", "self", ".", "update_app", "(", "app", ".", "id", ",", "MarathonApp", "(", "instances", "=", "desired", ")", ",", "force", "=", "force", ")" ]
Scale an app. Scale an app to a target number of instances (with `instances`), or scale the number of instances up or down by some delta (`delta`). If the resulting number of instances would be negative, desired instances will be set to zero. If both `instances` and `delta` are passed, use `instances`. :param str app_id: application ID :param int instances: [optional] the number of instances to scale to :param int delta: [optional] the number of instances to scale up or down by :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict
[ "Scale", "an", "app", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L357-L386
train
thefactory/marathon-python
marathon/client.py
MarathonClient.create_group
def create_group(self, group): """Create and start a group. :param :class:`marathon.models.group.MarathonGroup` group: the group to create :returns: success :rtype: dict containing the version ID """ data = group.to_json() response = self._do_request('POST', '/v2/groups', data=data) return response.json()
python
def create_group(self, group): """Create and start a group. :param :class:`marathon.models.group.MarathonGroup` group: the group to create :returns: success :rtype: dict containing the version ID """ data = group.to_json() response = self._do_request('POST', '/v2/groups', data=data) return response.json()
[ "def", "create_group", "(", "self", ",", "group", ")", ":", "data", "=", "group", ".", "to_json", "(", ")", "response", "=", "self", ".", "_do_request", "(", "'POST'", ",", "'/v2/groups'", ",", "data", "=", "data", ")", "return", "response", ".", "json", "(", ")" ]
Create and start a group. :param :class:`marathon.models.group.MarathonGroup` group: the group to create :returns: success :rtype: dict containing the version ID
[ "Create", "and", "start", "a", "group", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L388-L398
train
thefactory/marathon-python
marathon/client.py
MarathonClient.list_groups
def list_groups(self, **kwargs): """List all groups. :param kwargs: arbitrary search filters :returns: list of groups :rtype: list[:class:`marathon.models.group.MarathonGroup`] """ response = self._do_request('GET', '/v2/groups') groups = self._parse_response( response, MarathonGroup, is_list=True, resource_name='groups') for k, v in kwargs.items(): groups = [o for o in groups if getattr(o, k) == v] return groups
python
def list_groups(self, **kwargs): """List all groups. :param kwargs: arbitrary search filters :returns: list of groups :rtype: list[:class:`marathon.models.group.MarathonGroup`] """ response = self._do_request('GET', '/v2/groups') groups = self._parse_response( response, MarathonGroup, is_list=True, resource_name='groups') for k, v in kwargs.items(): groups = [o for o in groups if getattr(o, k) == v] return groups
[ "def", "list_groups", "(", "self", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/groups'", ")", "groups", "=", "self", ".", "_parse_response", "(", "response", ",", "MarathonGroup", ",", "is_list", "=", "True", ",", "resource_name", "=", "'groups'", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "groups", "=", "[", "o", "for", "o", "in", "groups", "if", "getattr", "(", "o", ",", "k", ")", "==", "v", "]", "return", "groups" ]
List all groups. :param kwargs: arbitrary search filters :returns: list of groups :rtype: list[:class:`marathon.models.group.MarathonGroup`]
[ "List", "all", "groups", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L400-L413
train
thefactory/marathon-python
marathon/client.py
MarathonClient.get_group
def get_group(self, group_id): """Get a single group. :param str group_id: group ID :returns: group :rtype: :class:`marathon.models.group.MarathonGroup` """ response = self._do_request( 'GET', '/v2/groups/{group_id}'.format(group_id=group_id)) return self._parse_response(response, MarathonGroup)
python
def get_group(self, group_id): """Get a single group. :param str group_id: group ID :returns: group :rtype: :class:`marathon.models.group.MarathonGroup` """ response = self._do_request( 'GET', '/v2/groups/{group_id}'.format(group_id=group_id)) return self._parse_response(response, MarathonGroup)
[ "def", "get_group", "(", "self", ",", "group_id", ")", ":", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/groups/{group_id}'", ".", "format", "(", "group_id", "=", "group_id", ")", ")", "return", "self", ".", "_parse_response", "(", "response", ",", "MarathonGroup", ")" ]
Get a single group. :param str group_id: group ID :returns: group :rtype: :class:`marathon.models.group.MarathonGroup`
[ "Get", "a", "single", "group", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L415-L425
train
thefactory/marathon-python
marathon/client.py
MarathonClient.update_group
def update_group(self, group_id, group, force=False, minimal=True): """Update a group. Applies writable settings in `group` to `group_id` Note: this method can not be used to rename groups. :param str group_id: target group ID :param group: group settings :type group: :class:`marathon.models.group.MarathonGroup` :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict """ # Changes won't take if version is set - blank it for convenience group.version = None params = {'force': force} data = group.to_json(minimal=minimal) response = self._do_request( 'PUT', '/v2/groups/{group_id}'.format(group_id=group_id), data=data, params=params) return response.json()
python
def update_group(self, group_id, group, force=False, minimal=True): """Update a group. Applies writable settings in `group` to `group_id` Note: this method can not be used to rename groups. :param str group_id: target group ID :param group: group settings :type group: :class:`marathon.models.group.MarathonGroup` :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict """ # Changes won't take if version is set - blank it for convenience group.version = None params = {'force': force} data = group.to_json(minimal=minimal) response = self._do_request( 'PUT', '/v2/groups/{group_id}'.format(group_id=group_id), data=data, params=params) return response.json()
[ "def", "update_group", "(", "self", ",", "group_id", ",", "group", ",", "force", "=", "False", ",", "minimal", "=", "True", ")", ":", "# Changes won't take if version is set - blank it for convenience", "group", ".", "version", "=", "None", "params", "=", "{", "'force'", ":", "force", "}", "data", "=", "group", ".", "to_json", "(", "minimal", "=", "minimal", ")", "response", "=", "self", ".", "_do_request", "(", "'PUT'", ",", "'/v2/groups/{group_id}'", ".", "format", "(", "group_id", "=", "group_id", ")", ",", "data", "=", "data", ",", "params", "=", "params", ")", "return", "response", ".", "json", "(", ")" ]
Update a group. Applies writable settings in `group` to `group_id` Note: this method can not be used to rename groups. :param str group_id: target group ID :param group: group settings :type group: :class:`marathon.models.group.MarathonGroup` :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict
[ "Update", "a", "group", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L427-L450
train
thefactory/marathon-python
marathon/client.py
MarathonClient.rollback_group
def rollback_group(self, group_id, version, force=False): """Roll a group back to a previous version. :param str group_id: group ID :param str version: group version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict """ params = {'force': force} response = self._do_request( 'PUT', '/v2/groups/{group_id}/versions/{version}'.format( group_id=group_id, version=version), params=params) return response.json()
python
def rollback_group(self, group_id, version, force=False): """Roll a group back to a previous version. :param str group_id: group ID :param str version: group version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict """ params = {'force': force} response = self._do_request( 'PUT', '/v2/groups/{group_id}/versions/{version}'.format( group_id=group_id, version=version), params=params) return response.json()
[ "def", "rollback_group", "(", "self", ",", "group_id", ",", "version", ",", "force", "=", "False", ")", ":", "params", "=", "{", "'force'", ":", "force", "}", "response", "=", "self", ".", "_do_request", "(", "'PUT'", ",", "'/v2/groups/{group_id}/versions/{version}'", ".", "format", "(", "group_id", "=", "group_id", ",", "version", "=", "version", ")", ",", "params", "=", "params", ")", "return", "response", ".", "json", "(", ")" ]
Roll a group back to a previous version. :param str group_id: group ID :param str version: group version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict
[ "Roll", "a", "group", "back", "to", "a", "previous", "version", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L452-L468
train
thefactory/marathon-python
marathon/client.py
MarathonClient.delete_group
def delete_group(self, group_id, force=False): """Stop and destroy a group. :param str group_id: group ID :param bool force: apply even if a deployment is in progress :returns: a dict containing the deleted version :rtype: dict """ params = {'force': force} response = self._do_request( 'DELETE', '/v2/groups/{group_id}'.format(group_id=group_id), params=params) return response.json()
python
def delete_group(self, group_id, force=False): """Stop and destroy a group. :param str group_id: group ID :param bool force: apply even if a deployment is in progress :returns: a dict containing the deleted version :rtype: dict """ params = {'force': force} response = self._do_request( 'DELETE', '/v2/groups/{group_id}'.format(group_id=group_id), params=params) return response.json()
[ "def", "delete_group", "(", "self", ",", "group_id", ",", "force", "=", "False", ")", ":", "params", "=", "{", "'force'", ":", "force", "}", "response", "=", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/groups/{group_id}'", ".", "format", "(", "group_id", "=", "group_id", ")", ",", "params", "=", "params", ")", "return", "response", ".", "json", "(", ")" ]
Stop and destroy a group. :param str group_id: group ID :param bool force: apply even if a deployment is in progress :returns: a dict containing the deleted version :rtype: dict
[ "Stop", "and", "destroy", "a", "group", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L470-L482
train
thefactory/marathon-python
marathon/client.py
MarathonClient.scale_group
def scale_group(self, group_id, scale_by): """Scale a group by a factor. :param str group_id: group ID :param int scale_by: factor to scale by :returns: a dict containing the deployment id and version :rtype: dict """ data = {'scaleBy': scale_by} response = self._do_request( 'PUT', '/v2/groups/{group_id}'.format(group_id=group_id), data=json.dumps(data)) return response.json()
python
def scale_group(self, group_id, scale_by): """Scale a group by a factor. :param str group_id: group ID :param int scale_by: factor to scale by :returns: a dict containing the deployment id and version :rtype: dict """ data = {'scaleBy': scale_by} response = self._do_request( 'PUT', '/v2/groups/{group_id}'.format(group_id=group_id), data=json.dumps(data)) return response.json()
[ "def", "scale_group", "(", "self", ",", "group_id", ",", "scale_by", ")", ":", "data", "=", "{", "'scaleBy'", ":", "scale_by", "}", "response", "=", "self", ".", "_do_request", "(", "'PUT'", ",", "'/v2/groups/{group_id}'", ".", "format", "(", "group_id", "=", "group_id", ")", ",", "data", "=", "json", ".", "dumps", "(", "data", ")", ")", "return", "response", ".", "json", "(", ")" ]
Scale a group by a factor. :param str group_id: group ID :param int scale_by: factor to scale by :returns: a dict containing the deployment id and version :rtype: dict
[ "Scale", "a", "group", "by", "a", "factor", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L484-L496
train
thefactory/marathon-python
marathon/client.py
MarathonClient.list_tasks
def list_tasks(self, app_id=None, **kwargs): """List running tasks, optionally filtered by app_id. :param str app_id: if passed, only show tasks for this application :param kwargs: arbitrary search filters :returns: list of tasks :rtype: list[:class:`marathon.models.task.MarathonTask`] """ response = self._do_request( 'GET', '/v2/apps/%s/tasks' % app_id if app_id else '/v2/tasks') tasks = self._parse_response( response, MarathonTask, is_list=True, resource_name='tasks') [setattr(t, 'app_id', app_id) for t in tasks if app_id and t.app_id is None] for k, v in kwargs.items(): tasks = [o for o in tasks if getattr(o, k) == v] return tasks
python
def list_tasks(self, app_id=None, **kwargs): """List running tasks, optionally filtered by app_id. :param str app_id: if passed, only show tasks for this application :param kwargs: arbitrary search filters :returns: list of tasks :rtype: list[:class:`marathon.models.task.MarathonTask`] """ response = self._do_request( 'GET', '/v2/apps/%s/tasks' % app_id if app_id else '/v2/tasks') tasks = self._parse_response( response, MarathonTask, is_list=True, resource_name='tasks') [setattr(t, 'app_id', app_id) for t in tasks if app_id and t.app_id is None] for k, v in kwargs.items(): tasks = [o for o in tasks if getattr(o, k) == v] return tasks
[ "def", "list_tasks", "(", "self", ",", "app_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/apps/%s/tasks'", "%", "app_id", "if", "app_id", "else", "'/v2/tasks'", ")", "tasks", "=", "self", ".", "_parse_response", "(", "response", ",", "MarathonTask", ",", "is_list", "=", "True", ",", "resource_name", "=", "'tasks'", ")", "[", "setattr", "(", "t", ",", "'app_id'", ",", "app_id", ")", "for", "t", "in", "tasks", "if", "app_id", "and", "t", ".", "app_id", "is", "None", "]", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "tasks", "=", "[", "o", "for", "o", "in", "tasks", "if", "getattr", "(", "o", ",", "k", ")", "==", "v", "]", "return", "tasks" ]
List running tasks, optionally filtered by app_id. :param str app_id: if passed, only show tasks for this application :param kwargs: arbitrary search filters :returns: list of tasks :rtype: list[:class:`marathon.models.task.MarathonTask`]
[ "List", "running", "tasks", "optionally", "filtered", "by", "app_id", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L498-L516
train
thefactory/marathon-python
marathon/client.py
MarathonClient.kill_given_tasks
def kill_given_tasks(self, task_ids, scale=False, force=None): """Kill a list of given tasks. :param list[str] task_ids: tasks to kill :param bool scale: if true, scale down the app by the number of tasks killed :param bool force: if true, ignore any current running deployments :return: True on success :rtype: bool """ params = {'scale': scale} if force is not None: params['force'] = force data = json.dumps({"ids": task_ids}) response = self._do_request( 'POST', '/v2/tasks/delete', params=params, data=data) return response == 200
python
def kill_given_tasks(self, task_ids, scale=False, force=None): """Kill a list of given tasks. :param list[str] task_ids: tasks to kill :param bool scale: if true, scale down the app by the number of tasks killed :param bool force: if true, ignore any current running deployments :return: True on success :rtype: bool """ params = {'scale': scale} if force is not None: params['force'] = force data = json.dumps({"ids": task_ids}) response = self._do_request( 'POST', '/v2/tasks/delete', params=params, data=data) return response == 200
[ "def", "kill_given_tasks", "(", "self", ",", "task_ids", ",", "scale", "=", "False", ",", "force", "=", "None", ")", ":", "params", "=", "{", "'scale'", ":", "scale", "}", "if", "force", "is", "not", "None", ":", "params", "[", "'force'", "]", "=", "force", "data", "=", "json", ".", "dumps", "(", "{", "\"ids\"", ":", "task_ids", "}", ")", "response", "=", "self", ".", "_do_request", "(", "'POST'", ",", "'/v2/tasks/delete'", ",", "params", "=", "params", ",", "data", "=", "data", ")", "return", "response", "==", "200" ]
Kill a list of given tasks. :param list[str] task_ids: tasks to kill :param bool scale: if true, scale down the app by the number of tasks killed :param bool force: if true, ignore any current running deployments :return: True on success :rtype: bool
[ "Kill", "a", "list", "of", "given", "tasks", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L518-L534
train
thefactory/marathon-python
marathon/client.py
MarathonClient.kill_tasks
def kill_tasks(self, app_id, scale=False, wipe=False, host=None, batch_size=0, batch_delay=0): """Kill all tasks belonging to app. :param str app_id: application ID :param bool scale: if true, scale down the app by the number of tasks killed :param str host: if provided, only terminate tasks on this Mesos slave :param int batch_size: if non-zero, terminate tasks in groups of this size :param int batch_delay: time (in seconds) to wait in between batched kills. If zero, automatically determine :returns: list of killed tasks :rtype: list[:class:`marathon.models.task.MarathonTask`] """ def batch(iterable, size): sourceiter = iter(iterable) while True: batchiter = itertools.islice(sourceiter, size) yield itertools.chain([next(batchiter)], batchiter) if batch_size == 0: # Terminate all at once params = {'scale': scale, 'wipe': wipe} if host: params['host'] = host response = self._do_request( 'DELETE', '/v2/apps/{app_id}/tasks'.format(app_id=app_id), params) # Marathon is inconsistent about what type of object it returns on the multi # task deletion endpoint, depending on the version of Marathon. See: # https://github.com/mesosphere/marathon/blob/06a6f763a75fb6d652b4f1660685ae234bd15387/src/main/scala/mesosphere/marathon/api/v2/AppTasksResource.scala#L88-L95 if "tasks" in response.json(): return self._parse_response(response, MarathonTask, is_list=True, resource_name='tasks') else: return response.json() else: # Terminate in batches tasks = self.list_tasks( app_id, host=host) if host else self.list_tasks(app_id) for tbatch in batch(tasks, batch_size): killed_tasks = [self.kill_task(app_id, t.id, scale=scale, wipe=wipe) for t in tbatch] # Pause until the tasks have been killed to avoid race # conditions killed_task_ids = set(t.id for t in killed_tasks) running_task_ids = killed_task_ids while killed_task_ids.intersection(running_task_ids): time.sleep(1) running_task_ids = set( t.id for t in self.get_app(app_id).tasks) if batch_delay == 0: # Pause until the replacement tasks are healthy desired_instances = self.get_app(app_id).instances running_instances = 0 while running_instances < desired_instances: time.sleep(1) running_instances = sum( t.started_at is None for t in self.get_app(app_id).tasks) else: time.sleep(batch_delay) return tasks
python
def kill_tasks(self, app_id, scale=False, wipe=False, host=None, batch_size=0, batch_delay=0): """Kill all tasks belonging to app. :param str app_id: application ID :param bool scale: if true, scale down the app by the number of tasks killed :param str host: if provided, only terminate tasks on this Mesos slave :param int batch_size: if non-zero, terminate tasks in groups of this size :param int batch_delay: time (in seconds) to wait in between batched kills. If zero, automatically determine :returns: list of killed tasks :rtype: list[:class:`marathon.models.task.MarathonTask`] """ def batch(iterable, size): sourceiter = iter(iterable) while True: batchiter = itertools.islice(sourceiter, size) yield itertools.chain([next(batchiter)], batchiter) if batch_size == 0: # Terminate all at once params = {'scale': scale, 'wipe': wipe} if host: params['host'] = host response = self._do_request( 'DELETE', '/v2/apps/{app_id}/tasks'.format(app_id=app_id), params) # Marathon is inconsistent about what type of object it returns on the multi # task deletion endpoint, depending on the version of Marathon. See: # https://github.com/mesosphere/marathon/blob/06a6f763a75fb6d652b4f1660685ae234bd15387/src/main/scala/mesosphere/marathon/api/v2/AppTasksResource.scala#L88-L95 if "tasks" in response.json(): return self._parse_response(response, MarathonTask, is_list=True, resource_name='tasks') else: return response.json() else: # Terminate in batches tasks = self.list_tasks( app_id, host=host) if host else self.list_tasks(app_id) for tbatch in batch(tasks, batch_size): killed_tasks = [self.kill_task(app_id, t.id, scale=scale, wipe=wipe) for t in tbatch] # Pause until the tasks have been killed to avoid race # conditions killed_task_ids = set(t.id for t in killed_tasks) running_task_ids = killed_task_ids while killed_task_ids.intersection(running_task_ids): time.sleep(1) running_task_ids = set( t.id for t in self.get_app(app_id).tasks) if batch_delay == 0: # Pause until the replacement tasks are healthy desired_instances = self.get_app(app_id).instances running_instances = 0 while running_instances < desired_instances: time.sleep(1) running_instances = sum( t.started_at is None for t in self.get_app(app_id).tasks) else: time.sleep(batch_delay) return tasks
[ "def", "kill_tasks", "(", "self", ",", "app_id", ",", "scale", "=", "False", ",", "wipe", "=", "False", ",", "host", "=", "None", ",", "batch_size", "=", "0", ",", "batch_delay", "=", "0", ")", ":", "def", "batch", "(", "iterable", ",", "size", ")", ":", "sourceiter", "=", "iter", "(", "iterable", ")", "while", "True", ":", "batchiter", "=", "itertools", ".", "islice", "(", "sourceiter", ",", "size", ")", "yield", "itertools", ".", "chain", "(", "[", "next", "(", "batchiter", ")", "]", ",", "batchiter", ")", "if", "batch_size", "==", "0", ":", "# Terminate all at once", "params", "=", "{", "'scale'", ":", "scale", ",", "'wipe'", ":", "wipe", "}", "if", "host", ":", "params", "[", "'host'", "]", "=", "host", "response", "=", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/apps/{app_id}/tasks'", ".", "format", "(", "app_id", "=", "app_id", ")", ",", "params", ")", "# Marathon is inconsistent about what type of object it returns on the multi", "# task deletion endpoint, depending on the version of Marathon. See:", "# https://github.com/mesosphere/marathon/blob/06a6f763a75fb6d652b4f1660685ae234bd15387/src/main/scala/mesosphere/marathon/api/v2/AppTasksResource.scala#L88-L95", "if", "\"tasks\"", "in", "response", ".", "json", "(", ")", ":", "return", "self", ".", "_parse_response", "(", "response", ",", "MarathonTask", ",", "is_list", "=", "True", ",", "resource_name", "=", "'tasks'", ")", "else", ":", "return", "response", ".", "json", "(", ")", "else", ":", "# Terminate in batches", "tasks", "=", "self", ".", "list_tasks", "(", "app_id", ",", "host", "=", "host", ")", "if", "host", "else", "self", ".", "list_tasks", "(", "app_id", ")", "for", "tbatch", "in", "batch", "(", "tasks", ",", "batch_size", ")", ":", "killed_tasks", "=", "[", "self", ".", "kill_task", "(", "app_id", ",", "t", ".", "id", ",", "scale", "=", "scale", ",", "wipe", "=", "wipe", ")", "for", "t", "in", "tbatch", "]", "# Pause until the tasks have been killed to avoid race", "# conditions", "killed_task_ids", "=", "set", "(", "t", ".", "id", "for", "t", "in", "killed_tasks", ")", "running_task_ids", "=", "killed_task_ids", "while", "killed_task_ids", ".", "intersection", "(", "running_task_ids", ")", ":", "time", ".", "sleep", "(", "1", ")", "running_task_ids", "=", "set", "(", "t", ".", "id", "for", "t", "in", "self", ".", "get_app", "(", "app_id", ")", ".", "tasks", ")", "if", "batch_delay", "==", "0", ":", "# Pause until the replacement tasks are healthy", "desired_instances", "=", "self", ".", "get_app", "(", "app_id", ")", ".", "instances", "running_instances", "=", "0", "while", "running_instances", "<", "desired_instances", ":", "time", ".", "sleep", "(", "1", ")", "running_instances", "=", "sum", "(", "t", ".", "started_at", "is", "None", "for", "t", "in", "self", ".", "get_app", "(", "app_id", ")", ".", "tasks", ")", "else", ":", "time", ".", "sleep", "(", "batch_delay", ")", "return", "tasks" ]
Kill all tasks belonging to app. :param str app_id: application ID :param bool scale: if true, scale down the app by the number of tasks killed :param str host: if provided, only terminate tasks on this Mesos slave :param int batch_size: if non-zero, terminate tasks in groups of this size :param int batch_delay: time (in seconds) to wait in between batched kills. If zero, automatically determine :returns: list of killed tasks :rtype: list[:class:`marathon.models.task.MarathonTask`]
[ "Kill", "all", "tasks", "belonging", "to", "app", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L536-L597
train
thefactory/marathon-python
marathon/client.py
MarathonClient.kill_task
def kill_task(self, app_id, task_id, scale=False, wipe=False): """Kill a task. :param str app_id: application ID :param str task_id: the task to kill :param bool scale: if true, scale down the app by one if the task exists :returns: the killed task :rtype: :class:`marathon.models.task.MarathonTask` """ params = {'scale': scale, 'wipe': wipe} response = self._do_request('DELETE', '/v2/apps/{app_id}/tasks/{task_id}' .format(app_id=app_id, task_id=task_id), params) # Marathon is inconsistent about what type of object it returns on the multi # task deletion endpoint, depending on the version of Marathon. See: # https://github.com/mesosphere/marathon/blob/06a6f763a75fb6d652b4f1660685ae234bd15387/src/main/scala/mesosphere/marathon/api/v2/AppTasksResource.scala#L88-L95 if "task" in response.json(): return self._parse_response(response, MarathonTask, is_list=False, resource_name='task') else: return response.json()
python
def kill_task(self, app_id, task_id, scale=False, wipe=False): """Kill a task. :param str app_id: application ID :param str task_id: the task to kill :param bool scale: if true, scale down the app by one if the task exists :returns: the killed task :rtype: :class:`marathon.models.task.MarathonTask` """ params = {'scale': scale, 'wipe': wipe} response = self._do_request('DELETE', '/v2/apps/{app_id}/tasks/{task_id}' .format(app_id=app_id, task_id=task_id), params) # Marathon is inconsistent about what type of object it returns on the multi # task deletion endpoint, depending on the version of Marathon. See: # https://github.com/mesosphere/marathon/blob/06a6f763a75fb6d652b4f1660685ae234bd15387/src/main/scala/mesosphere/marathon/api/v2/AppTasksResource.scala#L88-L95 if "task" in response.json(): return self._parse_response(response, MarathonTask, is_list=False, resource_name='task') else: return response.json()
[ "def", "kill_task", "(", "self", ",", "app_id", ",", "task_id", ",", "scale", "=", "False", ",", "wipe", "=", "False", ")", ":", "params", "=", "{", "'scale'", ":", "scale", ",", "'wipe'", ":", "wipe", "}", "response", "=", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/apps/{app_id}/tasks/{task_id}'", ".", "format", "(", "app_id", "=", "app_id", ",", "task_id", "=", "task_id", ")", ",", "params", ")", "# Marathon is inconsistent about what type of object it returns on the multi", "# task deletion endpoint, depending on the version of Marathon. See:", "# https://github.com/mesosphere/marathon/blob/06a6f763a75fb6d652b4f1660685ae234bd15387/src/main/scala/mesosphere/marathon/api/v2/AppTasksResource.scala#L88-L95", "if", "\"task\"", "in", "response", ".", "json", "(", ")", ":", "return", "self", ".", "_parse_response", "(", "response", ",", "MarathonTask", ",", "is_list", "=", "False", ",", "resource_name", "=", "'task'", ")", "else", ":", "return", "response", ".", "json", "(", ")" ]
Kill a task. :param str app_id: application ID :param str task_id: the task to kill :param bool scale: if true, scale down the app by one if the task exists :returns: the killed task :rtype: :class:`marathon.models.task.MarathonTask`
[ "Kill", "a", "task", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L599-L618
train
thefactory/marathon-python
marathon/client.py
MarathonClient.list_versions
def list_versions(self, app_id): """List the versions of an app. :param str app_id: application ID :returns: list of versions :rtype: list[str] """ response = self._do_request( 'GET', '/v2/apps/{app_id}/versions'.format(app_id=app_id)) return [version for version in response.json()['versions']]
python
def list_versions(self, app_id): """List the versions of an app. :param str app_id: application ID :returns: list of versions :rtype: list[str] """ response = self._do_request( 'GET', '/v2/apps/{app_id}/versions'.format(app_id=app_id)) return [version for version in response.json()['versions']]
[ "def", "list_versions", "(", "self", ",", "app_id", ")", ":", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/apps/{app_id}/versions'", ".", "format", "(", "app_id", "=", "app_id", ")", ")", "return", "[", "version", "for", "version", "in", "response", ".", "json", "(", ")", "[", "'versions'", "]", "]" ]
List the versions of an app. :param str app_id: application ID :returns: list of versions :rtype: list[str]
[ "List", "the", "versions", "of", "an", "app", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L620-L630
train
thefactory/marathon-python
marathon/client.py
MarathonClient.get_version
def get_version(self, app_id, version): """Get the configuration of an app at a specific version. :param str app_id: application ID :param str version: application version :return: application configuration :rtype: :class:`marathon.models.app.MarathonApp` """ response = self._do_request('GET', '/v2/apps/{app_id}/versions/{version}' .format(app_id=app_id, version=version)) return MarathonApp.from_json(response.json())
python
def get_version(self, app_id, version): """Get the configuration of an app at a specific version. :param str app_id: application ID :param str version: application version :return: application configuration :rtype: :class:`marathon.models.app.MarathonApp` """ response = self._do_request('GET', '/v2/apps/{app_id}/versions/{version}' .format(app_id=app_id, version=version)) return MarathonApp.from_json(response.json())
[ "def", "get_version", "(", "self", ",", "app_id", ",", "version", ")", ":", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/apps/{app_id}/versions/{version}'", ".", "format", "(", "app_id", "=", "app_id", ",", "version", "=", "version", ")", ")", "return", "MarathonApp", ".", "from_json", "(", "response", ".", "json", "(", ")", ")" ]
Get the configuration of an app at a specific version. :param str app_id: application ID :param str version: application version :return: application configuration :rtype: :class:`marathon.models.app.MarathonApp`
[ "Get", "the", "configuration", "of", "an", "app", "at", "a", "specific", "version", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L632-L643
train
thefactory/marathon-python
marathon/client.py
MarathonClient.create_event_subscription
def create_event_subscription(self, url): """Register a callback URL as an event subscriber. :param str url: callback URL :returns: the created event subscription :rtype: dict """ params = {'callbackUrl': url} response = self._do_request('POST', '/v2/eventSubscriptions', params) return response.json()
python
def create_event_subscription(self, url): """Register a callback URL as an event subscriber. :param str url: callback URL :returns: the created event subscription :rtype: dict """ params = {'callbackUrl': url} response = self._do_request('POST', '/v2/eventSubscriptions', params) return response.json()
[ "def", "create_event_subscription", "(", "self", ",", "url", ")", ":", "params", "=", "{", "'callbackUrl'", ":", "url", "}", "response", "=", "self", ".", "_do_request", "(", "'POST'", ",", "'/v2/eventSubscriptions'", ",", "params", ")", "return", "response", ".", "json", "(", ")" ]
Register a callback URL as an event subscriber. :param str url: callback URL :returns: the created event subscription :rtype: dict
[ "Register", "a", "callback", "URL", "as", "an", "event", "subscriber", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L654-L664
train
thefactory/marathon-python
marathon/client.py
MarathonClient.delete_event_subscription
def delete_event_subscription(self, url): """Deregister a callback URL as an event subscriber. :param str url: callback URL :returns: the deleted event subscription :rtype: dict """ params = {'callbackUrl': url} response = self._do_request('DELETE', '/v2/eventSubscriptions', params) return response.json()
python
def delete_event_subscription(self, url): """Deregister a callback URL as an event subscriber. :param str url: callback URL :returns: the deleted event subscription :rtype: dict """ params = {'callbackUrl': url} response = self._do_request('DELETE', '/v2/eventSubscriptions', params) return response.json()
[ "def", "delete_event_subscription", "(", "self", ",", "url", ")", ":", "params", "=", "{", "'callbackUrl'", ":", "url", "}", "response", "=", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/eventSubscriptions'", ",", "params", ")", "return", "response", ".", "json", "(", ")" ]
Deregister a callback URL as an event subscriber. :param str url: callback URL :returns: the deleted event subscription :rtype: dict
[ "Deregister", "a", "callback", "URL", "as", "an", "event", "subscriber", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L666-L676
train
thefactory/marathon-python
marathon/client.py
MarathonClient.list_deployments
def list_deployments(self): """List all running deployments. :returns: list of deployments :rtype: list[:class:`marathon.models.deployment.MarathonDeployment`] """ response = self._do_request('GET', '/v2/deployments') return self._parse_response(response, MarathonDeployment, is_list=True)
python
def list_deployments(self): """List all running deployments. :returns: list of deployments :rtype: list[:class:`marathon.models.deployment.MarathonDeployment`] """ response = self._do_request('GET', '/v2/deployments') return self._parse_response(response, MarathonDeployment, is_list=True)
[ "def", "list_deployments", "(", "self", ")", ":", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/deployments'", ")", "return", "self", ".", "_parse_response", "(", "response", ",", "MarathonDeployment", ",", "is_list", "=", "True", ")" ]
List all running deployments. :returns: list of deployments :rtype: list[:class:`marathon.models.deployment.MarathonDeployment`]
[ "List", "all", "running", "deployments", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L678-L685
train
thefactory/marathon-python
marathon/client.py
MarathonClient.list_queue
def list_queue(self, embed_last_unused_offers=False): """List all the tasks queued up or waiting to be scheduled. :returns: list of queue items :rtype: list[:class:`marathon.models.queue.MarathonQueueItem`] """ if embed_last_unused_offers: params = {'embed': 'lastUnusedOffers'} else: params = {} response = self._do_request('GET', '/v2/queue', params=params) return self._parse_response(response, MarathonQueueItem, is_list=True, resource_name='queue')
python
def list_queue(self, embed_last_unused_offers=False): """List all the tasks queued up or waiting to be scheduled. :returns: list of queue items :rtype: list[:class:`marathon.models.queue.MarathonQueueItem`] """ if embed_last_unused_offers: params = {'embed': 'lastUnusedOffers'} else: params = {} response = self._do_request('GET', '/v2/queue', params=params) return self._parse_response(response, MarathonQueueItem, is_list=True, resource_name='queue')
[ "def", "list_queue", "(", "self", ",", "embed_last_unused_offers", "=", "False", ")", ":", "if", "embed_last_unused_offers", ":", "params", "=", "{", "'embed'", ":", "'lastUnusedOffers'", "}", "else", ":", "params", "=", "{", "}", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/queue'", ",", "params", "=", "params", ")", "return", "self", ".", "_parse_response", "(", "response", ",", "MarathonQueueItem", ",", "is_list", "=", "True", ",", "resource_name", "=", "'queue'", ")" ]
List all the tasks queued up or waiting to be scheduled. :returns: list of queue items :rtype: list[:class:`marathon.models.queue.MarathonQueueItem`]
[ "List", "all", "the", "tasks", "queued", "up", "or", "waiting", "to", "be", "scheduled", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L687-L698
train
thefactory/marathon-python
marathon/client.py
MarathonClient.delete_deployment
def delete_deployment(self, deployment_id, force=False): """Cancel a deployment. :param str deployment_id: deployment id :param bool force: if true, don't create a rollback deployment to restore the previous configuration :returns: a dict containing the deployment id and version (empty dict if force=True) :rtype: dict """ if force: params = {'force': True} self._do_request('DELETE', '/v2/deployments/{deployment}'.format( deployment=deployment_id), params=params) # Successful DELETE with ?force=true returns empty text (and status # code 202). Client code should poll until deployment is removed. return {} else: response = self._do_request( 'DELETE', '/v2/deployments/{deployment}'.format(deployment=deployment_id)) return response.json()
python
def delete_deployment(self, deployment_id, force=False): """Cancel a deployment. :param str deployment_id: deployment id :param bool force: if true, don't create a rollback deployment to restore the previous configuration :returns: a dict containing the deployment id and version (empty dict if force=True) :rtype: dict """ if force: params = {'force': True} self._do_request('DELETE', '/v2/deployments/{deployment}'.format( deployment=deployment_id), params=params) # Successful DELETE with ?force=true returns empty text (and status # code 202). Client code should poll until deployment is removed. return {} else: response = self._do_request( 'DELETE', '/v2/deployments/{deployment}'.format(deployment=deployment_id)) return response.json()
[ "def", "delete_deployment", "(", "self", ",", "deployment_id", ",", "force", "=", "False", ")", ":", "if", "force", ":", "params", "=", "{", "'force'", ":", "True", "}", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/deployments/{deployment}'", ".", "format", "(", "deployment", "=", "deployment_id", ")", ",", "params", "=", "params", ")", "# Successful DELETE with ?force=true returns empty text (and status", "# code 202). Client code should poll until deployment is removed.", "return", "{", "}", "else", ":", "response", "=", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/deployments/{deployment}'", ".", "format", "(", "deployment", "=", "deployment_id", ")", ")", "return", "response", ".", "json", "(", ")" ]
Cancel a deployment. :param str deployment_id: deployment id :param bool force: if true, don't create a rollback deployment to restore the previous configuration :returns: a dict containing the deployment id and version (empty dict if force=True) :rtype: dict
[ "Cancel", "a", "deployment", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L700-L719
train
thefactory/marathon-python
marathon/client.py
MarathonClient.event_stream
def event_stream(self, raw=False, event_types=None): """Polls event bus using /v2/events :param bool raw: if true, yield raw event text, else yield MarathonEvent object :param event_types: a list of event types to consume :type event_types: list[type] or list[str] :returns: iterator with events :rtype: iterator """ ef = EventFactory() params = { 'event_type': [ EventFactory.class_to_event[et] if isinstance( et, type) and issubclass(et, MarathonEvent) else et for et in event_types or [] ] } for raw_message in self._do_sse_request('/v2/events', params=params): try: _data = raw_message.decode('utf8').split(':', 1) if _data[0] == 'data': if raw: yield _data[1] else: event_data = json.loads(_data[1].strip()) if 'eventType' not in event_data: raise MarathonError('Invalid event data received.') yield ef.process(event_data) except ValueError: raise MarathonError('Invalid event data received.')
python
def event_stream(self, raw=False, event_types=None): """Polls event bus using /v2/events :param bool raw: if true, yield raw event text, else yield MarathonEvent object :param event_types: a list of event types to consume :type event_types: list[type] or list[str] :returns: iterator with events :rtype: iterator """ ef = EventFactory() params = { 'event_type': [ EventFactory.class_to_event[et] if isinstance( et, type) and issubclass(et, MarathonEvent) else et for et in event_types or [] ] } for raw_message in self._do_sse_request('/v2/events', params=params): try: _data = raw_message.decode('utf8').split(':', 1) if _data[0] == 'data': if raw: yield _data[1] else: event_data = json.loads(_data[1].strip()) if 'eventType' not in event_data: raise MarathonError('Invalid event data received.') yield ef.process(event_data) except ValueError: raise MarathonError('Invalid event data received.')
[ "def", "event_stream", "(", "self", ",", "raw", "=", "False", ",", "event_types", "=", "None", ")", ":", "ef", "=", "EventFactory", "(", ")", "params", "=", "{", "'event_type'", ":", "[", "EventFactory", ".", "class_to_event", "[", "et", "]", "if", "isinstance", "(", "et", ",", "type", ")", "and", "issubclass", "(", "et", ",", "MarathonEvent", ")", "else", "et", "for", "et", "in", "event_types", "or", "[", "]", "]", "}", "for", "raw_message", "in", "self", ".", "_do_sse_request", "(", "'/v2/events'", ",", "params", "=", "params", ")", ":", "try", ":", "_data", "=", "raw_message", ".", "decode", "(", "'utf8'", ")", ".", "split", "(", "':'", ",", "1", ")", "if", "_data", "[", "0", "]", "==", "'data'", ":", "if", "raw", ":", "yield", "_data", "[", "1", "]", "else", ":", "event_data", "=", "json", ".", "loads", "(", "_data", "[", "1", "]", ".", "strip", "(", ")", ")", "if", "'eventType'", "not", "in", "event_data", ":", "raise", "MarathonError", "(", "'Invalid event data received.'", ")", "yield", "ef", ".", "process", "(", "event_data", ")", "except", "ValueError", ":", "raise", "MarathonError", "(", "'Invalid event data received.'", ")" ]
Polls event bus using /v2/events :param bool raw: if true, yield raw event text, else yield MarathonEvent object :param event_types: a list of event types to consume :type event_types: list[type] or list[str] :returns: iterator with events :rtype: iterator
[ "Polls", "event", "bus", "using", "/", "v2", "/", "events" ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L771-L804
train
thefactory/marathon-python
marathon/models/base.py
assert_valid_path
def assert_valid_path(path): """Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid. :param str path: The app id. :rtype: str """ if path is None: return # As seen in: # https://github.com/mesosphere/marathon/blob/0c11661ca2f259f8a903d114ef79023649a6f04b/src/main/scala/mesosphere/marathon/state/PathId.scala#L71 for id in filter(None, path.strip('/').split('/')): if not ID_PATTERN.match(id): raise ValueError( 'invalid path (allowed: lowercase letters, digits, hyphen, "/", ".", ".."): %r' % path) return path
python
def assert_valid_path(path): """Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid. :param str path: The app id. :rtype: str """ if path is None: return # As seen in: # https://github.com/mesosphere/marathon/blob/0c11661ca2f259f8a903d114ef79023649a6f04b/src/main/scala/mesosphere/marathon/state/PathId.scala#L71 for id in filter(None, path.strip('/').split('/')): if not ID_PATTERN.match(id): raise ValueError( 'invalid path (allowed: lowercase letters, digits, hyphen, "/", ".", ".."): %r' % path) return path
[ "def", "assert_valid_path", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "# As seen in:", "# https://github.com/mesosphere/marathon/blob/0c11661ca2f259f8a903d114ef79023649a6f04b/src/main/scala/mesosphere/marathon/state/PathId.scala#L71", "for", "id", "in", "filter", "(", "None", ",", "path", ".", "strip", "(", "'/'", ")", ".", "split", "(", "'/'", ")", ")", ":", "if", "not", "ID_PATTERN", ".", "match", "(", "id", ")", ":", "raise", "ValueError", "(", "'invalid path (allowed: lowercase letters, digits, hyphen, \"/\", \".\", \"..\"): %r'", "%", "path", ")", "return", "path" ]
Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid. :param str path: The app id. :rtype: str
[ "Checks", "if", "a", "path", "is", "a", "correct", "format", "that", "Marathon", "expects", ".", "Raises", "ValueError", "if", "not", "valid", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L90-L105
train
thefactory/marathon-python
marathon/models/base.py
assert_valid_id
def assert_valid_id(id): """Checks if an id is the correct format that Marathon expects. Raises ValueError if not valid. :param str id: App or group id. :rtype: str """ if id is None: return if not ID_PATTERN.match(id.strip('/')): raise ValueError( 'invalid id (allowed: lowercase letters, digits, hyphen, ".", ".."): %r' % id) return id
python
def assert_valid_id(id): """Checks if an id is the correct format that Marathon expects. Raises ValueError if not valid. :param str id: App or group id. :rtype: str """ if id is None: return if not ID_PATTERN.match(id.strip('/')): raise ValueError( 'invalid id (allowed: lowercase letters, digits, hyphen, ".", ".."): %r' % id) return id
[ "def", "assert_valid_id", "(", "id", ")", ":", "if", "id", "is", "None", ":", "return", "if", "not", "ID_PATTERN", ".", "match", "(", "id", ".", "strip", "(", "'/'", ")", ")", ":", "raise", "ValueError", "(", "'invalid id (allowed: lowercase letters, digits, hyphen, \".\", \"..\"): %r'", "%", "id", ")", "return", "id" ]
Checks if an id is the correct format that Marathon expects. Raises ValueError if not valid. :param str id: App or group id. :rtype: str
[ "Checks", "if", "an", "id", "is", "the", "correct", "format", "that", "Marathon", "expects", ".", "Raises", "ValueError", "if", "not", "valid", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L108-L120
train
thefactory/marathon-python
marathon/models/base.py
MarathonObject.json_repr
def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict """ if minimal: return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} else: return {to_camel_case(k): v for k, v in vars(self).items()}
python
def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict """ if minimal: return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} else: return {to_camel_case(k): v for k, v in vars(self).items()}
[ "def", "json_repr", "(", "self", ",", "minimal", "=", "False", ")", ":", "if", "minimal", ":", "return", "{", "to_camel_case", "(", "k", ")", ":", "v", "for", "k", ",", "v", "in", "vars", "(", "self", ")", ".", "items", "(", ")", "if", "(", "v", "or", "v", "is", "False", "or", "v", "==", "0", ")", "}", "else", ":", "return", "{", "to_camel_case", "(", "k", ")", ":", "v", "for", "k", ",", "v", "in", "vars", "(", "self", ")", ".", "items", "(", ")", "}" ]
Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict
[ "Construct", "a", "JSON", "-", "friendly", "representation", "of", "the", "object", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L25-L35
train
thefactory/marathon-python
marathon/models/base.py
MarathonObject.from_json
def from_json(cls, attributes): """Construct an object from a parsed response. :param dict attributes: object attributes from parsed response """ return cls(**{to_snake_case(k): v for k, v in attributes.items()})
python
def from_json(cls, attributes): """Construct an object from a parsed response. :param dict attributes: object attributes from parsed response """ return cls(**{to_snake_case(k): v for k, v in attributes.items()})
[ "def", "from_json", "(", "cls", ",", "attributes", ")", ":", "return", "cls", "(", "*", "*", "{", "to_snake_case", "(", "k", ")", ":", "v", "for", "k", ",", "v", "in", "attributes", ".", "items", "(", ")", "}", ")" ]
Construct an object from a parsed response. :param dict attributes: object attributes from parsed response
[ "Construct", "an", "object", "from", "a", "parsed", "response", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L38-L43
train
thefactory/marathon-python
marathon/models/base.py
MarathonObject.to_json
def to_json(self, minimal=True): """Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: str """ if minimal: return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) else: return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True)
python
def to_json(self, minimal=True): """Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: str """ if minimal: return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) else: return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True)
[ "def", "to_json", "(", "self", ",", "minimal", "=", "True", ")", ":", "if", "minimal", ":", "return", "json", ".", "dumps", "(", "self", ".", "json_repr", "(", "minimal", "=", "True", ")", ",", "cls", "=", "MarathonMinimalJsonEncoder", ",", "sort_keys", "=", "True", ")", "else", ":", "return", "json", ".", "dumps", "(", "self", ".", "json_repr", "(", ")", ",", "cls", "=", "MarathonJsonEncoder", ",", "sort_keys", "=", "True", ")" ]
Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: str
[ "Encode", "an", "object", "as", "a", "JSON", "string", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L45-L55
train
thefactory/marathon-python
marathon/models/constraint.py
MarathonConstraint.json_repr
def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: [ignored] :rtype: list """ if self.value: return [self.field, self.operator, self.value] else: return [self.field, self.operator]
python
def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: [ignored] :rtype: list """ if self.value: return [self.field, self.operator, self.value] else: return [self.field, self.operator]
[ "def", "json_repr", "(", "self", ",", "minimal", "=", "False", ")", ":", "if", "self", ".", "value", ":", "return", "[", "self", ".", "field", ",", "self", ".", "operator", ",", "self", ".", "value", "]", "else", ":", "return", "[", "self", ".", "field", ",", "self", ".", "operator", "]" ]
Construct a JSON-friendly representation of the object. :param bool minimal: [ignored] :rtype: list
[ "Construct", "a", "JSON", "-", "friendly", "representation", "of", "the", "object", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/constraint.py#L32-L42
train
thefactory/marathon-python
marathon/models/constraint.py
MarathonConstraint.from_json
def from_json(cls, obj): """Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from parsed response :rtype: :class:`MarathonConstraint` """ if len(obj) == 2: (field, operator) = obj return cls(field, operator) if len(obj) > 2: (field, operator, value) = obj return cls(field, operator, value)
python
def from_json(cls, obj): """Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from parsed response :rtype: :class:`MarathonConstraint` """ if len(obj) == 2: (field, operator) = obj return cls(field, operator) if len(obj) > 2: (field, operator, value) = obj return cls(field, operator, value)
[ "def", "from_json", "(", "cls", ",", "obj", ")", ":", "if", "len", "(", "obj", ")", "==", "2", ":", "(", "field", ",", "operator", ")", "=", "obj", "return", "cls", "(", "field", ",", "operator", ")", "if", "len", "(", "obj", ")", ">", "2", ":", "(", "field", ",", "operator", ",", "value", ")", "=", "obj", "return", "cls", "(", "field", ",", "operator", ",", "value", ")" ]
Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from parsed response :rtype: :class:`MarathonConstraint`
[ "Construct", "a", "MarathonConstraint", "from", "a", "parsed", "response", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/constraint.py#L45-L57
train
thefactory/marathon-python
marathon/models/constraint.py
MarathonConstraint.from_string
def from_string(cls, constraint): """ :param str constraint: The string representation of a constraint :rtype: :class:`MarathonConstraint` """ obj = constraint.split(':') marathon_constraint = cls.from_json(obj) if marathon_constraint: return marathon_constraint raise ValueError("Invalid string format. " "Expected `field:operator:value`")
python
def from_string(cls, constraint): """ :param str constraint: The string representation of a constraint :rtype: :class:`MarathonConstraint` """ obj = constraint.split(':') marathon_constraint = cls.from_json(obj) if marathon_constraint: return marathon_constraint raise ValueError("Invalid string format. " "Expected `field:operator:value`")
[ "def", "from_string", "(", "cls", ",", "constraint", ")", ":", "obj", "=", "constraint", ".", "split", "(", "':'", ")", "marathon_constraint", "=", "cls", ".", "from_json", "(", "obj", ")", "if", "marathon_constraint", ":", "return", "marathon_constraint", "raise", "ValueError", "(", "\"Invalid string format. \"", "\"Expected `field:operator:value`\"", ")" ]
:param str constraint: The string representation of a constraint :rtype: :class:`MarathonConstraint`
[ ":", "param", "str", "constraint", ":", "The", "string", "representation", "of", "a", "constraint" ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/constraint.py#L60-L73
train
thefactory/marathon-python
marathon/models/endpoint.py
MarathonEndpoint.from_tasks
def from_tasks(cls, tasks): """Construct a list of MarathonEndpoints from a list of tasks. :param list[:class:`marathon.models.MarathonTask`] tasks: list of tasks to parse :rtype: list[:class:`MarathonEndpoint`] """ endpoints = [ [ MarathonEndpoint(task.app_id, task.service_ports[ port_index], task.host, task.id, port) for port_index, port in enumerate(task.ports) ] for task in tasks ] # Flatten result return [item for sublist in endpoints for item in sublist]
python
def from_tasks(cls, tasks): """Construct a list of MarathonEndpoints from a list of tasks. :param list[:class:`marathon.models.MarathonTask`] tasks: list of tasks to parse :rtype: list[:class:`MarathonEndpoint`] """ endpoints = [ [ MarathonEndpoint(task.app_id, task.service_ports[ port_index], task.host, task.id, port) for port_index, port in enumerate(task.ports) ] for task in tasks ] # Flatten result return [item for sublist in endpoints for item in sublist]
[ "def", "from_tasks", "(", "cls", ",", "tasks", ")", ":", "endpoints", "=", "[", "[", "MarathonEndpoint", "(", "task", ".", "app_id", ",", "task", ".", "service_ports", "[", "port_index", "]", ",", "task", ".", "host", ",", "task", ".", "id", ",", "port", ")", "for", "port_index", ",", "port", "in", "enumerate", "(", "task", ".", "ports", ")", "]", "for", "task", "in", "tasks", "]", "# Flatten result", "return", "[", "item", "for", "sublist", "in", "endpoints", "for", "item", "in", "sublist", "]" ]
Construct a list of MarathonEndpoints from a list of tasks. :param list[:class:`marathon.models.MarathonTask`] tasks: list of tasks to parse :rtype: list[:class:`MarathonEndpoint`]
[ "Construct", "a", "list", "of", "MarathonEndpoints", "from", "a", "list", "of", "tasks", "." ]
592b253aa8edf2475c97ca438ad7b6936652caf2
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/endpoint.py#L33-L50
train
jml/tree-format
tree_format/_text.py
_format_newlines
def _format_newlines(prefix, formatted_node, options): """ Convert newlines into U+23EC characters, followed by an actual newline and then a tree prefix so as to position the remaining text under the previous line. """ replacement = u''.join([ options.NEWLINE, u'\n', prefix]) return formatted_node.replace(u'\n', replacement)
python
def _format_newlines(prefix, formatted_node, options): """ Convert newlines into U+23EC characters, followed by an actual newline and then a tree prefix so as to position the remaining text under the previous line. """ replacement = u''.join([ options.NEWLINE, u'\n', prefix]) return formatted_node.replace(u'\n', replacement)
[ "def", "_format_newlines", "(", "prefix", ",", "formatted_node", ",", "options", ")", ":", "replacement", "=", "u''", ".", "join", "(", "[", "options", ".", "NEWLINE", ",", "u'\\n'", ",", "prefix", "]", ")", "return", "formatted_node", ".", "replace", "(", "u'\\n'", ",", "replacement", ")" ]
Convert newlines into U+23EC characters, followed by an actual newline and then a tree prefix so as to position the remaining text under the previous line.
[ "Convert", "newlines", "into", "U", "+", "23EC", "characters", "followed", "by", "an", "actual", "newline", "and", "then", "a", "tree", "prefix", "so", "as", "to", "position", "the", "remaining", "text", "under", "the", "previous", "line", "." ]
cb17aba273ff043505ab9fd2afc08ce18a44cf44
https://github.com/jml/tree-format/blob/cb17aba273ff043505ab9fd2afc08ce18a44cf44/tree_format/_text.py#L45-L55
train
umbresp/brawlstars
brawlstars/client.py
Client.get_band
def get_band(self, tag): """Gets a band. Gets a band with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If the data was unable to be received, a brawlstars.HTTPError will be raised along with the HTTP status code. On success, will return a Band. """ tag = tag.strip("#") tag = tag.upper() try: resp = requests.get(self._base_url + 'bands/' + tag, headers=self.headers, timeout=self.timeout) if resp.status_code == 200: data = resp.json() elif 500 > resp.status_code > 400: raise HTTPError(resp.status_code) else: raise Error() except ValueError: raise MissingData('data') except Exception: raise Timeout() data = Box(data) band = Band(data) return band
python
def get_band(self, tag): """Gets a band. Gets a band with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If the data was unable to be received, a brawlstars.HTTPError will be raised along with the HTTP status code. On success, will return a Band. """ tag = tag.strip("#") tag = tag.upper() try: resp = requests.get(self._base_url + 'bands/' + tag, headers=self.headers, timeout=self.timeout) if resp.status_code == 200: data = resp.json() elif 500 > resp.status_code > 400: raise HTTPError(resp.status_code) else: raise Error() except ValueError: raise MissingData('data') except Exception: raise Timeout() data = Box(data) band = Band(data) return band
[ "def", "get_band", "(", "self", ",", "tag", ")", ":", "tag", "=", "tag", ".", "strip", "(", "\"#\"", ")", "tag", "=", "tag", ".", "upper", "(", ")", "try", ":", "resp", "=", "requests", ".", "get", "(", "self", ".", "_base_url", "+", "'bands/'", "+", "tag", ",", "headers", "=", "self", ".", "headers", ",", "timeout", "=", "self", ".", "timeout", ")", "if", "resp", ".", "status_code", "==", "200", ":", "data", "=", "resp", ".", "json", "(", ")", "elif", "500", ">", "resp", ".", "status_code", ">", "400", ":", "raise", "HTTPError", "(", "resp", ".", "status_code", ")", "else", ":", "raise", "Error", "(", ")", "except", "ValueError", ":", "raise", "MissingData", "(", "'data'", ")", "except", "Exception", ":", "raise", "Timeout", "(", ")", "data", "=", "Box", "(", "data", ")", "band", "=", "Band", "(", "data", ")", "return", "band" ]
Gets a band. Gets a band with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If the data was unable to be received, a brawlstars.HTTPError will be raised along with the HTTP status code. On success, will return a Band.
[ "Gets", "a", "band", "." ]
dc8c91b68dc01983c6af3ab68df266a657ec3f7c
https://github.com/umbresp/brawlstars/blob/dc8c91b68dc01983c6af3ab68df266a657ec3f7c/brawlstars/client.py#L78-L108
train
umbresp/brawlstars
brawlstars/asyncclient.py
AsyncClient.get_player
async def get_player(self, tag): """Gets a player. Gets a player with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If the data was unable to be received, a brawlstars.HTTPError will be raised along with the HTTP status code. On success, will return a Player. """ tag = tag.strip("#") tag = tag.upper() try: async with self.session.get(self._base_url + 'players/' + tag, timeout=self.timeout, headers=self.headers) as resp: if resp.status == 200: data = await resp.json() elif 500 > resp.status > 400: raise HTTPError(resp.status) else: raise Error() except asyncio.TimeoutError: raise Timeout() except ValueError: raise MissingData('data') except Exception: raise InvalidArg('tag') data = Box(data) player = Player(data) return player
python
async def get_player(self, tag): """Gets a player. Gets a player with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If the data was unable to be received, a brawlstars.HTTPError will be raised along with the HTTP status code. On success, will return a Player. """ tag = tag.strip("#") tag = tag.upper() try: async with self.session.get(self._base_url + 'players/' + tag, timeout=self.timeout, headers=self.headers) as resp: if resp.status == 200: data = await resp.json() elif 500 > resp.status > 400: raise HTTPError(resp.status) else: raise Error() except asyncio.TimeoutError: raise Timeout() except ValueError: raise MissingData('data') except Exception: raise InvalidArg('tag') data = Box(data) player = Player(data) return player
[ "async", "def", "get_player", "(", "self", ",", "tag", ")", ":", "tag", "=", "tag", ".", "strip", "(", "\"#\"", ")", "tag", "=", "tag", ".", "upper", "(", ")", "try", ":", "async", "with", "self", ".", "session", ".", "get", "(", "self", ".", "_base_url", "+", "'players/'", "+", "tag", ",", "timeout", "=", "self", ".", "timeout", ",", "headers", "=", "self", ".", "headers", ")", "as", "resp", ":", "if", "resp", ".", "status", "==", "200", ":", "data", "=", "await", "resp", ".", "json", "(", ")", "elif", "500", ">", "resp", ".", "status", ">", "400", ":", "raise", "HTTPError", "(", "resp", ".", "status", ")", "else", ":", "raise", "Error", "(", ")", "except", "asyncio", ".", "TimeoutError", ":", "raise", "Timeout", "(", ")", "except", "ValueError", ":", "raise", "MissingData", "(", "'data'", ")", "except", "Exception", ":", "raise", "InvalidArg", "(", "'tag'", ")", "data", "=", "Box", "(", "data", ")", "player", "=", "Player", "(", "data", ")", "return", "player" ]
Gets a player. Gets a player with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If the data was unable to be received, a brawlstars.HTTPError will be raised along with the HTTP status code. On success, will return a Player.
[ "Gets", "a", "player", "." ]
dc8c91b68dc01983c6af3ab68df266a657ec3f7c
https://github.com/umbresp/brawlstars/blob/dc8c91b68dc01983c6af3ab68df266a657ec3f7c/brawlstars/asyncclient.py#L48-L81
train
umbresp/brawlstars
brawlstars/asyncclient.py
AsyncClient.get_band
async def get_band(self, tag): """Gets a band. Gets a band with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If the data was unable to be received, a brawlstars.HTTPError will be raised along with the HTTP status code. On success, will return a Band. """ tag = tag.strip("#") tag = tag.upper() try: async with self.session.get(self._base_url + 'bands/' + tag, timeout=self.timeout, headers=self.headers) as resp: if resp.status == 200: data = await resp.json() elif 500 > resp.status > 400: raise HTTPError(resp.status) else: raise Error() except asyncio.TimeoutError: raise Timeout() except ValueError: raise MissingData('data') except Exception: raise InvalidArg('tag') data = Box(data) band = Band(data) return band
python
async def get_band(self, tag): """Gets a band. Gets a band with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If the data was unable to be received, a brawlstars.HTTPError will be raised along with the HTTP status code. On success, will return a Band. """ tag = tag.strip("#") tag = tag.upper() try: async with self.session.get(self._base_url + 'bands/' + tag, timeout=self.timeout, headers=self.headers) as resp: if resp.status == 200: data = await resp.json() elif 500 > resp.status > 400: raise HTTPError(resp.status) else: raise Error() except asyncio.TimeoutError: raise Timeout() except ValueError: raise MissingData('data') except Exception: raise InvalidArg('tag') data = Box(data) band = Band(data) return band
[ "async", "def", "get_band", "(", "self", ",", "tag", ")", ":", "tag", "=", "tag", ".", "strip", "(", "\"#\"", ")", "tag", "=", "tag", ".", "upper", "(", ")", "try", ":", "async", "with", "self", ".", "session", ".", "get", "(", "self", ".", "_base_url", "+", "'bands/'", "+", "tag", ",", "timeout", "=", "self", ".", "timeout", ",", "headers", "=", "self", ".", "headers", ")", "as", "resp", ":", "if", "resp", ".", "status", "==", "200", ":", "data", "=", "await", "resp", ".", "json", "(", ")", "elif", "500", ">", "resp", ".", "status", ">", "400", ":", "raise", "HTTPError", "(", "resp", ".", "status", ")", "else", ":", "raise", "Error", "(", ")", "except", "asyncio", ".", "TimeoutError", ":", "raise", "Timeout", "(", ")", "except", "ValueError", ":", "raise", "MissingData", "(", "'data'", ")", "except", "Exception", ":", "raise", "InvalidArg", "(", "'tag'", ")", "data", "=", "Box", "(", "data", ")", "band", "=", "Band", "(", "data", ")", "return", "band" ]
Gets a band. Gets a band with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If the data was unable to be received, a brawlstars.HTTPError will be raised along with the HTTP status code. On success, will return a Band.
[ "Gets", "a", "band", "." ]
dc8c91b68dc01983c6af3ab68df266a657ec3f7c
https://github.com/umbresp/brawlstars/blob/dc8c91b68dc01983c6af3ab68df266a657ec3f7c/brawlstars/asyncclient.py#L83-L116
train
mnmelo/lazy_import
lazy_import/__init__.py
lazy_module
def lazy_module(modname, error_strings=None, lazy_mod_class=LazyModule, level='leaf'): """Function allowing lazy importing of a module into the namespace. A lazy module object is created, registered in `sys.modules`, and returned. This is a hollow module; actual loading, and `ImportErrors` if not found, are delayed until an attempt is made to access attributes of the lazy module. A handy application is to use :func:`lazy_module` early in your own code (say, in `__init__.py`) to register all modulenames you want to be lazy. Because of registration in `sys.modules` later invocations of `import modulename` will also return the lazy object. This means that after initial registration the rest of your code can use regular pyhon import statements and retain the lazyness of the modules. Parameters ---------- modname : str The module to import. error_strings : dict, optional A dictionary of strings to use when module-loading fails. Key 'msg' sets the message to use (defaults to :attr:`lazy_import._MSG`). The message is formatted using the remaining dictionary keys. The default message informs the user of which module is missing (key 'module'), what code loaded the module as lazy (key 'caller'), and which package should be installed to solve the dependency (key 'install_name'). None of the keys is mandatory and all are given smart names by default. lazy_mod_class: type, optional Which class to use when instantiating the lazy module, to allow deep customization. The default is :class:`LazyModule` and custom alternatives **must** be a subclass thereof. level : str, optional Which submodule reference to return. Either a reference to the 'leaf' module (the default) or to the 'base' module. This is useful if you'll be using the module functionality in the same place you're calling :func:`lazy_module` from, since then you don't need to run `import` again. Setting *level* does not affect which names/modules get registered in `sys.modules`. For *level* set to 'base' and *modulename* 'aaa.bbb.ccc':: aaa = lazy_import.lazy_module("aaa.bbb.ccc", level='base') # 'aaa' becomes defined in the current namespace, with # (sub)attributes 'aaa.bbb' and 'aaa.bbb.ccc'. # It's the lazy equivalent to: import aaa.bbb.ccc For *level* set to 'leaf':: ccc = lazy_import.lazy_module("aaa.bbb.ccc", level='leaf') # Only 'ccc' becomes set in the current namespace. # Lazy equivalent to: from aaa.bbb import ccc Returns ------- module The module specified by *modname*, or its base, depending on *level*. The module isn't immediately imported. Instead, an instance of *lazy_mod_class* is returned. Upon access to any of its attributes, the module is finally loaded. Examples -------- >>> import lazy_import, sys >>> np = lazy_import.lazy_module("numpy") >>> np Lazily-loaded module numpy >>> np is sys.modules['numpy'] True >>> np.pi # This causes the full loading of the module ... 3.141592653589793 >>> np # ... and the module is changed in place. <module 'numpy' from '/usr/local/lib/python/site-packages/numpy/__init__.py'> >>> import lazy_import, sys >>> # The following succeeds even when asking for a module that's not available >>> missing = lazy_import.lazy_module("missing_module") >>> missing Lazily-loaded module missing_module >>> missing is sys.modules['missing_module'] True >>> missing.some_attr # This causes the full loading of the module, which now fails. ImportError: __main__ attempted to use a functionality that requires module missing_module, but it couldn't be loaded. Please install missing_module and retry. See Also -------- :func:`lazy_callable` :class:`LazyModule` """ if error_strings is None: error_strings = {} _set_default_errornames(modname, error_strings) mod = _lazy_module(modname, error_strings, lazy_mod_class) if level == 'base': return sys.modules[module_basename(modname)] elif level == 'leaf': return mod else: raise ValueError("Parameter 'level' must be one of ('base', 'leaf')")
python
def lazy_module(modname, error_strings=None, lazy_mod_class=LazyModule, level='leaf'): """Function allowing lazy importing of a module into the namespace. A lazy module object is created, registered in `sys.modules`, and returned. This is a hollow module; actual loading, and `ImportErrors` if not found, are delayed until an attempt is made to access attributes of the lazy module. A handy application is to use :func:`lazy_module` early in your own code (say, in `__init__.py`) to register all modulenames you want to be lazy. Because of registration in `sys.modules` later invocations of `import modulename` will also return the lazy object. This means that after initial registration the rest of your code can use regular pyhon import statements and retain the lazyness of the modules. Parameters ---------- modname : str The module to import. error_strings : dict, optional A dictionary of strings to use when module-loading fails. Key 'msg' sets the message to use (defaults to :attr:`lazy_import._MSG`). The message is formatted using the remaining dictionary keys. The default message informs the user of which module is missing (key 'module'), what code loaded the module as lazy (key 'caller'), and which package should be installed to solve the dependency (key 'install_name'). None of the keys is mandatory and all are given smart names by default. lazy_mod_class: type, optional Which class to use when instantiating the lazy module, to allow deep customization. The default is :class:`LazyModule` and custom alternatives **must** be a subclass thereof. level : str, optional Which submodule reference to return. Either a reference to the 'leaf' module (the default) or to the 'base' module. This is useful if you'll be using the module functionality in the same place you're calling :func:`lazy_module` from, since then you don't need to run `import` again. Setting *level* does not affect which names/modules get registered in `sys.modules`. For *level* set to 'base' and *modulename* 'aaa.bbb.ccc':: aaa = lazy_import.lazy_module("aaa.bbb.ccc", level='base') # 'aaa' becomes defined in the current namespace, with # (sub)attributes 'aaa.bbb' and 'aaa.bbb.ccc'. # It's the lazy equivalent to: import aaa.bbb.ccc For *level* set to 'leaf':: ccc = lazy_import.lazy_module("aaa.bbb.ccc", level='leaf') # Only 'ccc' becomes set in the current namespace. # Lazy equivalent to: from aaa.bbb import ccc Returns ------- module The module specified by *modname*, or its base, depending on *level*. The module isn't immediately imported. Instead, an instance of *lazy_mod_class* is returned. Upon access to any of its attributes, the module is finally loaded. Examples -------- >>> import lazy_import, sys >>> np = lazy_import.lazy_module("numpy") >>> np Lazily-loaded module numpy >>> np is sys.modules['numpy'] True >>> np.pi # This causes the full loading of the module ... 3.141592653589793 >>> np # ... and the module is changed in place. <module 'numpy' from '/usr/local/lib/python/site-packages/numpy/__init__.py'> >>> import lazy_import, sys >>> # The following succeeds even when asking for a module that's not available >>> missing = lazy_import.lazy_module("missing_module") >>> missing Lazily-loaded module missing_module >>> missing is sys.modules['missing_module'] True >>> missing.some_attr # This causes the full loading of the module, which now fails. ImportError: __main__ attempted to use a functionality that requires module missing_module, but it couldn't be loaded. Please install missing_module and retry. See Also -------- :func:`lazy_callable` :class:`LazyModule` """ if error_strings is None: error_strings = {} _set_default_errornames(modname, error_strings) mod = _lazy_module(modname, error_strings, lazy_mod_class) if level == 'base': return sys.modules[module_basename(modname)] elif level == 'leaf': return mod else: raise ValueError("Parameter 'level' must be one of ('base', 'leaf')")
[ "def", "lazy_module", "(", "modname", ",", "error_strings", "=", "None", ",", "lazy_mod_class", "=", "LazyModule", ",", "level", "=", "'leaf'", ")", ":", "if", "error_strings", "is", "None", ":", "error_strings", "=", "{", "}", "_set_default_errornames", "(", "modname", ",", "error_strings", ")", "mod", "=", "_lazy_module", "(", "modname", ",", "error_strings", ",", "lazy_mod_class", ")", "if", "level", "==", "'base'", ":", "return", "sys", ".", "modules", "[", "module_basename", "(", "modname", ")", "]", "elif", "level", "==", "'leaf'", ":", "return", "mod", "else", ":", "raise", "ValueError", "(", "\"Parameter 'level' must be one of ('base', 'leaf')\"", ")" ]
Function allowing lazy importing of a module into the namespace. A lazy module object is created, registered in `sys.modules`, and returned. This is a hollow module; actual loading, and `ImportErrors` if not found, are delayed until an attempt is made to access attributes of the lazy module. A handy application is to use :func:`lazy_module` early in your own code (say, in `__init__.py`) to register all modulenames you want to be lazy. Because of registration in `sys.modules` later invocations of `import modulename` will also return the lazy object. This means that after initial registration the rest of your code can use regular pyhon import statements and retain the lazyness of the modules. Parameters ---------- modname : str The module to import. error_strings : dict, optional A dictionary of strings to use when module-loading fails. Key 'msg' sets the message to use (defaults to :attr:`lazy_import._MSG`). The message is formatted using the remaining dictionary keys. The default message informs the user of which module is missing (key 'module'), what code loaded the module as lazy (key 'caller'), and which package should be installed to solve the dependency (key 'install_name'). None of the keys is mandatory and all are given smart names by default. lazy_mod_class: type, optional Which class to use when instantiating the lazy module, to allow deep customization. The default is :class:`LazyModule` and custom alternatives **must** be a subclass thereof. level : str, optional Which submodule reference to return. Either a reference to the 'leaf' module (the default) or to the 'base' module. This is useful if you'll be using the module functionality in the same place you're calling :func:`lazy_module` from, since then you don't need to run `import` again. Setting *level* does not affect which names/modules get registered in `sys.modules`. For *level* set to 'base' and *modulename* 'aaa.bbb.ccc':: aaa = lazy_import.lazy_module("aaa.bbb.ccc", level='base') # 'aaa' becomes defined in the current namespace, with # (sub)attributes 'aaa.bbb' and 'aaa.bbb.ccc'. # It's the lazy equivalent to: import aaa.bbb.ccc For *level* set to 'leaf':: ccc = lazy_import.lazy_module("aaa.bbb.ccc", level='leaf') # Only 'ccc' becomes set in the current namespace. # Lazy equivalent to: from aaa.bbb import ccc Returns ------- module The module specified by *modname*, or its base, depending on *level*. The module isn't immediately imported. Instead, an instance of *lazy_mod_class* is returned. Upon access to any of its attributes, the module is finally loaded. Examples -------- >>> import lazy_import, sys >>> np = lazy_import.lazy_module("numpy") >>> np Lazily-loaded module numpy >>> np is sys.modules['numpy'] True >>> np.pi # This causes the full loading of the module ... 3.141592653589793 >>> np # ... and the module is changed in place. <module 'numpy' from '/usr/local/lib/python/site-packages/numpy/__init__.py'> >>> import lazy_import, sys >>> # The following succeeds even when asking for a module that's not available >>> missing = lazy_import.lazy_module("missing_module") >>> missing Lazily-loaded module missing_module >>> missing is sys.modules['missing_module'] True >>> missing.some_attr # This causes the full loading of the module, which now fails. ImportError: __main__ attempted to use a functionality that requires module missing_module, but it couldn't be loaded. Please install missing_module and retry. See Also -------- :func:`lazy_callable` :class:`LazyModule`
[ "Function", "allowing", "lazy", "importing", "of", "a", "module", "into", "the", "namespace", "." ]
29c74c83e90adff62d363220fee8cf7d6f0dd3c9
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L233-L334
train
mnmelo/lazy_import
lazy_import/__init__.py
lazy_callable
def lazy_callable(modname, *names, **kwargs): """Performs lazy importing of one or more callables. :func:`lazy_callable` creates functions that are thin wrappers that pass any and all arguments straight to the target module's callables. These can be functions or classes. The full loading of that module is only actually triggered when the returned lazy function itself is called. This lazy import of the target module uses the same mechanism as :func:`lazy_module`. If, however, the target module has already been fully imported prior to invocation of :func:`lazy_callable`, then the target callables themselves are returned and no lazy imports are made. :func:`lazy_function` and :func:`lazy_function` are aliases of :func:`lazy_callable`. Parameters ---------- modname : str The base module from where to import the callable(s) in *names*, or a full 'module_name.callable_name' string. names : str (optional) The callable name(s) to import from the module specified by *modname*. If left empty, *modname* is assumed to also include the callable name to import. error_strings : dict, optional A dictionary of strings to use when reporting loading errors (either a missing module, or a missing callable name in the loaded module). *error_string* follows the same usage as described under :func:`lazy_module`, with the exceptions that 1) a further key, 'msg_callable', can be supplied to be used as the error when a module is successfully loaded but the target callable can't be found therein (defaulting to :attr:`lazy_import._MSG_CALLABLE`); 2) a key 'callable' is always added with the callable name being loaded. lazy_mod_class : type, optional See definition under :func:`lazy_module`. lazy_call_class : type, optional Analogously to *lazy_mod_class*, allows setting a custom class to handle lazy callables, other than the default :class:`LazyCallable`. Returns ------- wrapper function or tuple of wrapper functions If *names* is passed, returns a tuple of wrapper functions, one for each element in *names*. If only *modname* is passed it is assumed to be a full 'module_name.callable_name' string, in which case the wrapper for the imported callable is returned directly, and not in a tuple. Notes ----- Unlike :func:`lazy_module`, which returns a lazy module that eventually mutates into the fully-functional version, :func:`lazy_callable` only returns thin wrappers that never change. This means that the returned wrapper object never truly becomes the one under the module's namespace, even after successful loading of the module in *modname*. This is fine for most practical use cases, but may break code that relies on the usage of the returned objects oter than calling them. One such example is the lazy import of a class: it's fine to use the returned wrapper to instantiate an object, but it can't be used, for instance, to subclass from. Examples -------- >>> import lazy_import, sys >>> fn = lazy_import.lazy_callable("numpy.arange") >>> sys.modules['numpy'] Lazily-loaded module numpy >>> fn(10) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> sys.modules['numpy'] <module 'numpy' from '/usr/local/lib/python3.5/site-packages/numpy/__init__.py'> >>> import lazy_import, sys >>> cl = lazy_import.lazy_callable("numpy.ndarray") # a class >>> obj = cl([1, 2]) # This works OK (and also triggers the loading of numpy) >>> class MySubclass(cl): # This fails because cls is just a wrapper, >>> pass # not an actual class. See Also -------- :func:`lazy_module` :class:`LazyCallable` :class:`LazyModule` """ if not names: modname, _, name = modname.rpartition(".") lazy_mod_class = _setdef(kwargs, 'lazy_mod_class', LazyModule) lazy_call_class = _setdef(kwargs, 'lazy_call_class', LazyCallable) error_strings = _setdef(kwargs, 'error_strings', {}) _set_default_errornames(modname, error_strings, call=True) if not names: # We allow passing a single string as 'modname.callable_name', # in which case the wrapper is returned directly and not as a list. return _lazy_callable(modname, name, error_strings.copy(), lazy_mod_class, lazy_call_class) return tuple(_lazy_callable(modname, cname, error_strings.copy(), lazy_mod_class, lazy_call_class) for cname in names)
python
def lazy_callable(modname, *names, **kwargs): """Performs lazy importing of one or more callables. :func:`lazy_callable` creates functions that are thin wrappers that pass any and all arguments straight to the target module's callables. These can be functions or classes. The full loading of that module is only actually triggered when the returned lazy function itself is called. This lazy import of the target module uses the same mechanism as :func:`lazy_module`. If, however, the target module has already been fully imported prior to invocation of :func:`lazy_callable`, then the target callables themselves are returned and no lazy imports are made. :func:`lazy_function` and :func:`lazy_function` are aliases of :func:`lazy_callable`. Parameters ---------- modname : str The base module from where to import the callable(s) in *names*, or a full 'module_name.callable_name' string. names : str (optional) The callable name(s) to import from the module specified by *modname*. If left empty, *modname* is assumed to also include the callable name to import. error_strings : dict, optional A dictionary of strings to use when reporting loading errors (either a missing module, or a missing callable name in the loaded module). *error_string* follows the same usage as described under :func:`lazy_module`, with the exceptions that 1) a further key, 'msg_callable', can be supplied to be used as the error when a module is successfully loaded but the target callable can't be found therein (defaulting to :attr:`lazy_import._MSG_CALLABLE`); 2) a key 'callable' is always added with the callable name being loaded. lazy_mod_class : type, optional See definition under :func:`lazy_module`. lazy_call_class : type, optional Analogously to *lazy_mod_class*, allows setting a custom class to handle lazy callables, other than the default :class:`LazyCallable`. Returns ------- wrapper function or tuple of wrapper functions If *names* is passed, returns a tuple of wrapper functions, one for each element in *names*. If only *modname* is passed it is assumed to be a full 'module_name.callable_name' string, in which case the wrapper for the imported callable is returned directly, and not in a tuple. Notes ----- Unlike :func:`lazy_module`, which returns a lazy module that eventually mutates into the fully-functional version, :func:`lazy_callable` only returns thin wrappers that never change. This means that the returned wrapper object never truly becomes the one under the module's namespace, even after successful loading of the module in *modname*. This is fine for most practical use cases, but may break code that relies on the usage of the returned objects oter than calling them. One such example is the lazy import of a class: it's fine to use the returned wrapper to instantiate an object, but it can't be used, for instance, to subclass from. Examples -------- >>> import lazy_import, sys >>> fn = lazy_import.lazy_callable("numpy.arange") >>> sys.modules['numpy'] Lazily-loaded module numpy >>> fn(10) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> sys.modules['numpy'] <module 'numpy' from '/usr/local/lib/python3.5/site-packages/numpy/__init__.py'> >>> import lazy_import, sys >>> cl = lazy_import.lazy_callable("numpy.ndarray") # a class >>> obj = cl([1, 2]) # This works OK (and also triggers the loading of numpy) >>> class MySubclass(cl): # This fails because cls is just a wrapper, >>> pass # not an actual class. See Also -------- :func:`lazy_module` :class:`LazyCallable` :class:`LazyModule` """ if not names: modname, _, name = modname.rpartition(".") lazy_mod_class = _setdef(kwargs, 'lazy_mod_class', LazyModule) lazy_call_class = _setdef(kwargs, 'lazy_call_class', LazyCallable) error_strings = _setdef(kwargs, 'error_strings', {}) _set_default_errornames(modname, error_strings, call=True) if not names: # We allow passing a single string as 'modname.callable_name', # in which case the wrapper is returned directly and not as a list. return _lazy_callable(modname, name, error_strings.copy(), lazy_mod_class, lazy_call_class) return tuple(_lazy_callable(modname, cname, error_strings.copy(), lazy_mod_class, lazy_call_class) for cname in names)
[ "def", "lazy_callable", "(", "modname", ",", "*", "names", ",", "*", "*", "kwargs", ")", ":", "if", "not", "names", ":", "modname", ",", "_", ",", "name", "=", "modname", ".", "rpartition", "(", "\".\"", ")", "lazy_mod_class", "=", "_setdef", "(", "kwargs", ",", "'lazy_mod_class'", ",", "LazyModule", ")", "lazy_call_class", "=", "_setdef", "(", "kwargs", ",", "'lazy_call_class'", ",", "LazyCallable", ")", "error_strings", "=", "_setdef", "(", "kwargs", ",", "'error_strings'", ",", "{", "}", ")", "_set_default_errornames", "(", "modname", ",", "error_strings", ",", "call", "=", "True", ")", "if", "not", "names", ":", "# We allow passing a single string as 'modname.callable_name',", "# in which case the wrapper is returned directly and not as a list.", "return", "_lazy_callable", "(", "modname", ",", "name", ",", "error_strings", ".", "copy", "(", ")", ",", "lazy_mod_class", ",", "lazy_call_class", ")", "return", "tuple", "(", "_lazy_callable", "(", "modname", ",", "cname", ",", "error_strings", ".", "copy", "(", ")", ",", "lazy_mod_class", ",", "lazy_call_class", ")", "for", "cname", "in", "names", ")" ]
Performs lazy importing of one or more callables. :func:`lazy_callable` creates functions that are thin wrappers that pass any and all arguments straight to the target module's callables. These can be functions or classes. The full loading of that module is only actually triggered when the returned lazy function itself is called. This lazy import of the target module uses the same mechanism as :func:`lazy_module`. If, however, the target module has already been fully imported prior to invocation of :func:`lazy_callable`, then the target callables themselves are returned and no lazy imports are made. :func:`lazy_function` and :func:`lazy_function` are aliases of :func:`lazy_callable`. Parameters ---------- modname : str The base module from where to import the callable(s) in *names*, or a full 'module_name.callable_name' string. names : str (optional) The callable name(s) to import from the module specified by *modname*. If left empty, *modname* is assumed to also include the callable name to import. error_strings : dict, optional A dictionary of strings to use when reporting loading errors (either a missing module, or a missing callable name in the loaded module). *error_string* follows the same usage as described under :func:`lazy_module`, with the exceptions that 1) a further key, 'msg_callable', can be supplied to be used as the error when a module is successfully loaded but the target callable can't be found therein (defaulting to :attr:`lazy_import._MSG_CALLABLE`); 2) a key 'callable' is always added with the callable name being loaded. lazy_mod_class : type, optional See definition under :func:`lazy_module`. lazy_call_class : type, optional Analogously to *lazy_mod_class*, allows setting a custom class to handle lazy callables, other than the default :class:`LazyCallable`. Returns ------- wrapper function or tuple of wrapper functions If *names* is passed, returns a tuple of wrapper functions, one for each element in *names*. If only *modname* is passed it is assumed to be a full 'module_name.callable_name' string, in which case the wrapper for the imported callable is returned directly, and not in a tuple. Notes ----- Unlike :func:`lazy_module`, which returns a lazy module that eventually mutates into the fully-functional version, :func:`lazy_callable` only returns thin wrappers that never change. This means that the returned wrapper object never truly becomes the one under the module's namespace, even after successful loading of the module in *modname*. This is fine for most practical use cases, but may break code that relies on the usage of the returned objects oter than calling them. One such example is the lazy import of a class: it's fine to use the returned wrapper to instantiate an object, but it can't be used, for instance, to subclass from. Examples -------- >>> import lazy_import, sys >>> fn = lazy_import.lazy_callable("numpy.arange") >>> sys.modules['numpy'] Lazily-loaded module numpy >>> fn(10) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> sys.modules['numpy'] <module 'numpy' from '/usr/local/lib/python3.5/site-packages/numpy/__init__.py'> >>> import lazy_import, sys >>> cl = lazy_import.lazy_callable("numpy.ndarray") # a class >>> obj = cl([1, 2]) # This works OK (and also triggers the loading of numpy) >>> class MySubclass(cl): # This fails because cls is just a wrapper, >>> pass # not an actual class. See Also -------- :func:`lazy_module` :class:`LazyCallable` :class:`LazyModule`
[ "Performs", "lazy", "importing", "of", "one", "or", "more", "callables", "." ]
29c74c83e90adff62d363220fee8cf7d6f0dd3c9
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L384-L483
train
mnmelo/lazy_import
lazy_import/__init__.py
_load_module
def _load_module(module): """Ensures that a module, and its parents, are properly loaded """ modclass = type(module) # We only take care of our own LazyModule instances if not issubclass(modclass, LazyModule): raise TypeError("Passed module is not a LazyModule instance.") with _ImportLockContext(): parent, _, modname = module.__name__.rpartition('.') logger.debug("loading module {}".format(modname)) # We first identify whether this is a loadable LazyModule, then we # strip as much of lazy_import behavior as possible (keeping it cached, # in case loading fails and we need to reset the lazy state). if not hasattr(modclass, '_lazy_import_error_msgs'): # Alreay loaded (no _lazy_import_error_msgs attr). Not reloading. return # First, ensure the parent is loaded (using recursion; *very* unlikely # we'll ever hit a stack limit in this case). modclass._LOADING = True try: if parent: logger.debug("first loading parent module {}".format(parent)) setattr(sys.modules[parent], modname, module) if not hasattr(modclass, '_LOADING'): logger.debug("Module {} already loaded by the parent" .format(modname)) # We've been loaded by the parent. Let's bail. return cached_data = _clean_lazymodule(module) try: # Get Python to do the real import! reload_module(module) except: # Loading failed. We reset our lazy state. logger.debug("Failed to load module {}. Resetting..." .format(modname)) _reset_lazymodule(module, cached_data) raise else: # Successful load logger.debug("Successfully loaded module {}".format(modname)) delattr(modclass, '_LOADING') _reset_lazy_submod_refs(module) except (AttributeError, ImportError) as err: logger.debug("Failed to load {}.\n{}: {}" .format(modname, err.__class__.__name__, err)) logger.lazy_trace() # Under Python 3 reloading our dummy LazyModule instances causes an # AttributeError if the module can't be found. Would be preferrable # if we could always rely on an ImportError. As it is we vet the # AttributeError as thoroughly as possible. if ((six.PY3 and isinstance(err, AttributeError)) and not err.args[0] == "'NoneType' object has no attribute 'name'"): # Not the AttributeError we were looking for. raise msg = modclass._lazy_import_error_msgs['msg'] raise_from(ImportError( msg.format(**modclass._lazy_import_error_strings)), None)
python
def _load_module(module): """Ensures that a module, and its parents, are properly loaded """ modclass = type(module) # We only take care of our own LazyModule instances if not issubclass(modclass, LazyModule): raise TypeError("Passed module is not a LazyModule instance.") with _ImportLockContext(): parent, _, modname = module.__name__.rpartition('.') logger.debug("loading module {}".format(modname)) # We first identify whether this is a loadable LazyModule, then we # strip as much of lazy_import behavior as possible (keeping it cached, # in case loading fails and we need to reset the lazy state). if not hasattr(modclass, '_lazy_import_error_msgs'): # Alreay loaded (no _lazy_import_error_msgs attr). Not reloading. return # First, ensure the parent is loaded (using recursion; *very* unlikely # we'll ever hit a stack limit in this case). modclass._LOADING = True try: if parent: logger.debug("first loading parent module {}".format(parent)) setattr(sys.modules[parent], modname, module) if not hasattr(modclass, '_LOADING'): logger.debug("Module {} already loaded by the parent" .format(modname)) # We've been loaded by the parent. Let's bail. return cached_data = _clean_lazymodule(module) try: # Get Python to do the real import! reload_module(module) except: # Loading failed. We reset our lazy state. logger.debug("Failed to load module {}. Resetting..." .format(modname)) _reset_lazymodule(module, cached_data) raise else: # Successful load logger.debug("Successfully loaded module {}".format(modname)) delattr(modclass, '_LOADING') _reset_lazy_submod_refs(module) except (AttributeError, ImportError) as err: logger.debug("Failed to load {}.\n{}: {}" .format(modname, err.__class__.__name__, err)) logger.lazy_trace() # Under Python 3 reloading our dummy LazyModule instances causes an # AttributeError if the module can't be found. Would be preferrable # if we could always rely on an ImportError. As it is we vet the # AttributeError as thoroughly as possible. if ((six.PY3 and isinstance(err, AttributeError)) and not err.args[0] == "'NoneType' object has no attribute 'name'"): # Not the AttributeError we were looking for. raise msg = modclass._lazy_import_error_msgs['msg'] raise_from(ImportError( msg.format(**modclass._lazy_import_error_strings)), None)
[ "def", "_load_module", "(", "module", ")", ":", "modclass", "=", "type", "(", "module", ")", "# We only take care of our own LazyModule instances", "if", "not", "issubclass", "(", "modclass", ",", "LazyModule", ")", ":", "raise", "TypeError", "(", "\"Passed module is not a LazyModule instance.\"", ")", "with", "_ImportLockContext", "(", ")", ":", "parent", ",", "_", ",", "modname", "=", "module", ".", "__name__", ".", "rpartition", "(", "'.'", ")", "logger", ".", "debug", "(", "\"loading module {}\"", ".", "format", "(", "modname", ")", ")", "# We first identify whether this is a loadable LazyModule, then we", "# strip as much of lazy_import behavior as possible (keeping it cached,", "# in case loading fails and we need to reset the lazy state).", "if", "not", "hasattr", "(", "modclass", ",", "'_lazy_import_error_msgs'", ")", ":", "# Alreay loaded (no _lazy_import_error_msgs attr). Not reloading.", "return", "# First, ensure the parent is loaded (using recursion; *very* unlikely", "# we'll ever hit a stack limit in this case).", "modclass", ".", "_LOADING", "=", "True", "try", ":", "if", "parent", ":", "logger", ".", "debug", "(", "\"first loading parent module {}\"", ".", "format", "(", "parent", ")", ")", "setattr", "(", "sys", ".", "modules", "[", "parent", "]", ",", "modname", ",", "module", ")", "if", "not", "hasattr", "(", "modclass", ",", "'_LOADING'", ")", ":", "logger", ".", "debug", "(", "\"Module {} already loaded by the parent\"", ".", "format", "(", "modname", ")", ")", "# We've been loaded by the parent. Let's bail.", "return", "cached_data", "=", "_clean_lazymodule", "(", "module", ")", "try", ":", "# Get Python to do the real import!", "reload_module", "(", "module", ")", "except", ":", "# Loading failed. We reset our lazy state.", "logger", ".", "debug", "(", "\"Failed to load module {}. Resetting...\"", ".", "format", "(", "modname", ")", ")", "_reset_lazymodule", "(", "module", ",", "cached_data", ")", "raise", "else", ":", "# Successful load", "logger", ".", "debug", "(", "\"Successfully loaded module {}\"", ".", "format", "(", "modname", ")", ")", "delattr", "(", "modclass", ",", "'_LOADING'", ")", "_reset_lazy_submod_refs", "(", "module", ")", "except", "(", "AttributeError", ",", "ImportError", ")", "as", "err", ":", "logger", ".", "debug", "(", "\"Failed to load {}.\\n{}: {}\"", ".", "format", "(", "modname", ",", "err", ".", "__class__", ".", "__name__", ",", "err", ")", ")", "logger", ".", "lazy_trace", "(", ")", "# Under Python 3 reloading our dummy LazyModule instances causes an", "# AttributeError if the module can't be found. Would be preferrable", "# if we could always rely on an ImportError. As it is we vet the", "# AttributeError as thoroughly as possible.", "if", "(", "(", "six", ".", "PY3", "and", "isinstance", "(", "err", ",", "AttributeError", ")", ")", "and", "not", "err", ".", "args", "[", "0", "]", "==", "\"'NoneType' object has no attribute 'name'\"", ")", ":", "# Not the AttributeError we were looking for.", "raise", "msg", "=", "modclass", ".", "_lazy_import_error_msgs", "[", "'msg'", "]", "raise_from", "(", "ImportError", "(", "msg", ".", "format", "(", "*", "*", "modclass", ".", "_lazy_import_error_strings", ")", ")", ",", "None", ")" ]
Ensures that a module, and its parents, are properly loaded
[ "Ensures", "that", "a", "module", "and", "its", "parents", "are", "properly", "loaded" ]
29c74c83e90adff62d363220fee8cf7d6f0dd3c9
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L504-L563
train
mnmelo/lazy_import
lazy_import/__init__.py
_setdef
def _setdef(argdict, name, defaultvalue): """Like dict.setdefault but sets the default value also if None is present. """ if not name in argdict or argdict[name] is None: argdict[name] = defaultvalue return argdict[name]
python
def _setdef(argdict, name, defaultvalue): """Like dict.setdefault but sets the default value also if None is present. """ if not name in argdict or argdict[name] is None: argdict[name] = defaultvalue return argdict[name]
[ "def", "_setdef", "(", "argdict", ",", "name", ",", "defaultvalue", ")", ":", "if", "not", "name", "in", "argdict", "or", "argdict", "[", "name", "]", "is", "None", ":", "argdict", "[", "name", "]", "=", "defaultvalue", "return", "argdict", "[", "name", "]" ]
Like dict.setdefault but sets the default value also if None is present.
[ "Like", "dict", ".", "setdefault", "but", "sets", "the", "default", "value", "also", "if", "None", "is", "present", "." ]
29c74c83e90adff62d363220fee8cf7d6f0dd3c9
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L584-L590
train
mnmelo/lazy_import
lazy_import/__init__.py
_clean_lazymodule
def _clean_lazymodule(module): """Removes all lazy behavior from a module's class, for loading. Also removes all module attributes listed under the module's class deletion dictionaries. Deletion dictionaries are class attributes with names specified in `_DELETION_DICT`. Parameters ---------- module: LazyModule Returns ------- dict A dictionary of deleted class attributes, that can be used to reset the lazy state using :func:`_reset_lazymodule`. """ modclass = type(module) _clean_lazy_submod_refs(module) modclass.__getattribute__ = ModuleType.__getattribute__ modclass.__setattr__ = ModuleType.__setattr__ cls_attrs = {} for cls_attr in _CLS_ATTRS: try: cls_attrs[cls_attr] = getattr(modclass, cls_attr) delattr(modclass, cls_attr) except AttributeError: pass return cls_attrs
python
def _clean_lazymodule(module): """Removes all lazy behavior from a module's class, for loading. Also removes all module attributes listed under the module's class deletion dictionaries. Deletion dictionaries are class attributes with names specified in `_DELETION_DICT`. Parameters ---------- module: LazyModule Returns ------- dict A dictionary of deleted class attributes, that can be used to reset the lazy state using :func:`_reset_lazymodule`. """ modclass = type(module) _clean_lazy_submod_refs(module) modclass.__getattribute__ = ModuleType.__getattribute__ modclass.__setattr__ = ModuleType.__setattr__ cls_attrs = {} for cls_attr in _CLS_ATTRS: try: cls_attrs[cls_attr] = getattr(modclass, cls_attr) delattr(modclass, cls_attr) except AttributeError: pass return cls_attrs
[ "def", "_clean_lazymodule", "(", "module", ")", ":", "modclass", "=", "type", "(", "module", ")", "_clean_lazy_submod_refs", "(", "module", ")", "modclass", ".", "__getattribute__", "=", "ModuleType", ".", "__getattribute__", "modclass", ".", "__setattr__", "=", "ModuleType", ".", "__setattr__", "cls_attrs", "=", "{", "}", "for", "cls_attr", "in", "_CLS_ATTRS", ":", "try", ":", "cls_attrs", "[", "cls_attr", "]", "=", "getattr", "(", "modclass", ",", "cls_attr", ")", "delattr", "(", "modclass", ",", "cls_attr", ")", "except", "AttributeError", ":", "pass", "return", "cls_attrs" ]
Removes all lazy behavior from a module's class, for loading. Also removes all module attributes listed under the module's class deletion dictionaries. Deletion dictionaries are class attributes with names specified in `_DELETION_DICT`. Parameters ---------- module: LazyModule Returns ------- dict A dictionary of deleted class attributes, that can be used to reset the lazy state using :func:`_reset_lazymodule`.
[ "Removes", "all", "lazy", "behavior", "from", "a", "module", "s", "class", "for", "loading", "." ]
29c74c83e90adff62d363220fee8cf7d6f0dd3c9
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L619-L648
train
mnmelo/lazy_import
lazy_import/__init__.py
_reset_lazymodule
def _reset_lazymodule(module, cls_attrs): """Resets a module's lazy state from cached data. """ modclass = type(module) del modclass.__getattribute__ del modclass.__setattr__ try: del modclass._LOADING except AttributeError: pass for cls_attr in _CLS_ATTRS: try: setattr(modclass, cls_attr, cls_attrs[cls_attr]) except KeyError: pass _reset_lazy_submod_refs(module)
python
def _reset_lazymodule(module, cls_attrs): """Resets a module's lazy state from cached data. """ modclass = type(module) del modclass.__getattribute__ del modclass.__setattr__ try: del modclass._LOADING except AttributeError: pass for cls_attr in _CLS_ATTRS: try: setattr(modclass, cls_attr, cls_attrs[cls_attr]) except KeyError: pass _reset_lazy_submod_refs(module)
[ "def", "_reset_lazymodule", "(", "module", ",", "cls_attrs", ")", ":", "modclass", "=", "type", "(", "module", ")", "del", "modclass", ".", "__getattribute__", "del", "modclass", ".", "__setattr__", "try", ":", "del", "modclass", ".", "_LOADING", "except", "AttributeError", ":", "pass", "for", "cls_attr", "in", "_CLS_ATTRS", ":", "try", ":", "setattr", "(", "modclass", ",", "cls_attr", ",", "cls_attrs", "[", "cls_attr", "]", ")", "except", "KeyError", ":", "pass", "_reset_lazy_submod_refs", "(", "module", ")" ]
Resets a module's lazy state from cached data.
[ "Resets", "a", "module", "s", "lazy", "state", "from", "cached", "data", "." ]
29c74c83e90adff62d363220fee8cf7d6f0dd3c9
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L666-L682
train
Mangopay/mangopay2-python-sdk
mangopay/compat.py
python_2_unicode_compatible
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if six.PY2: klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass
python
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if six.PY2: klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass
[ "def", "python_2_unicode_compatible", "(", "klass", ")", ":", "if", "six", ".", "PY2", ":", "klass", ".", "__unicode__", "=", "klass", ".", "__str__", "klass", ".", "__str__", "=", "lambda", "self", ":", "self", ".", "__unicode__", "(", ")", ".", "encode", "(", "'utf-8'", ")", "return", "klass" ]
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.
[ "A", "decorator", "that", "defines", "__unicode__", "and", "__str__", "methods", "under", "Python", "2", ".", "Under", "Python", "3", "it", "does", "nothing", "." ]
9bbbc0f797581c9fdf7da5a70879bee6643024b7
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/compat.py#L5-L16
train
Mangopay/mangopay2-python-sdk
mangopay/utils.py
timestamp_from_datetime
def timestamp_from_datetime(dt): """ Compute timestamp from a datetime object that could be timezone aware or unaware. """ try: utc_dt = dt.astimezone(pytz.utc) except ValueError: utc_dt = dt.replace(tzinfo=pytz.utc) return timegm(utc_dt.timetuple())
python
def timestamp_from_datetime(dt): """ Compute timestamp from a datetime object that could be timezone aware or unaware. """ try: utc_dt = dt.astimezone(pytz.utc) except ValueError: utc_dt = dt.replace(tzinfo=pytz.utc) return timegm(utc_dt.timetuple())
[ "def", "timestamp_from_datetime", "(", "dt", ")", ":", "try", ":", "utc_dt", "=", "dt", ".", "astimezone", "(", "pytz", ".", "utc", ")", "except", "ValueError", ":", "utc_dt", "=", "dt", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", "return", "timegm", "(", "utc_dt", ".", "timetuple", "(", ")", ")" ]
Compute timestamp from a datetime object that could be timezone aware or unaware.
[ "Compute", "timestamp", "from", "a", "datetime", "object", "that", "could", "be", "timezone", "aware", "or", "unaware", "." ]
9bbbc0f797581c9fdf7da5a70879bee6643024b7
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/utils.py#L549-L558
train
Mangopay/mangopay2-python-sdk
mangopay/utils.py
force_bytes
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, memoryview): s = bytes(s) if isinstance(s, bytes): if encoding == 'utf-8': return s else: return s.decode('utf-8', errors).encode(encoding, errors) if strings_only and (s is None or isinstance(s, int)): return s if not isinstance(s, six.string_types): try: if six.PY3: return six.text_type(s).encode(encoding) else: return bytes(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return b' '.join([force_bytes(arg, encoding, strings_only, errors) for arg in s]) return six.text_type(s).encode(encoding, errors) else: return s.encode(encoding, errors)
python
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, memoryview): s = bytes(s) if isinstance(s, bytes): if encoding == 'utf-8': return s else: return s.decode('utf-8', errors).encode(encoding, errors) if strings_only and (s is None or isinstance(s, int)): return s if not isinstance(s, six.string_types): try: if six.PY3: return six.text_type(s).encode(encoding) else: return bytes(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return b' '.join([force_bytes(arg, encoding, strings_only, errors) for arg in s]) return six.text_type(s).encode(encoding, errors) else: return s.encode(encoding, errors)
[ "def", "force_bytes", "(", "s", ",", "encoding", "=", "'utf-8'", ",", "strings_only", "=", "False", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "s", ",", "memoryview", ")", ":", "s", "=", "bytes", "(", "s", ")", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "if", "encoding", "==", "'utf-8'", ":", "return", "s", "else", ":", "return", "s", ".", "decode", "(", "'utf-8'", ",", "errors", ")", ".", "encode", "(", "encoding", ",", "errors", ")", "if", "strings_only", "and", "(", "s", "is", "None", "or", "isinstance", "(", "s", ",", "int", ")", ")", ":", "return", "s", "if", "not", "isinstance", "(", "s", ",", "six", ".", "string_types", ")", ":", "try", ":", "if", "six", ".", "PY3", ":", "return", "six", ".", "text_type", "(", "s", ")", ".", "encode", "(", "encoding", ")", "else", ":", "return", "bytes", "(", "s", ")", "except", "UnicodeEncodeError", ":", "if", "isinstance", "(", "s", ",", "Exception", ")", ":", "# An Exception subclass containing non-ASCII data that doesn't", "# know how to print itself properly. We shouldn't raise a", "# further exception.", "return", "b' '", ".", "join", "(", "[", "force_bytes", "(", "arg", ",", "encoding", ",", "strings_only", ",", "errors", ")", "for", "arg", "in", "s", "]", ")", "return", "six", ".", "text_type", "(", "s", ")", ".", "encode", "(", "encoding", ",", "errors", ")", "else", ":", "return", "s", ".", "encode", "(", "encoding", ",", "errors", ")" ]
Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects.
[ "Similar", "to", "smart_bytes", "except", "that", "lazy", "instances", "are", "resolved", "to", "strings", "rather", "than", "kept", "as", "lazy", "objects", "." ]
9bbbc0f797581c9fdf7da5a70879bee6643024b7
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/utils.py#L624-L655
train
Mangopay/mangopay2-python-sdk
mangopay/utils.py
memoize
def memoize(func, cache, num_args): """ Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key. """ @wraps(func) def wrapper(*args): mem_args = args[:num_args] if mem_args in cache: return cache[mem_args] result = func(*args) cache[mem_args] = result return result return wrapper
python
def memoize(func, cache, num_args): """ Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key. """ @wraps(func) def wrapper(*args): mem_args = args[:num_args] if mem_args in cache: return cache[mem_args] result = func(*args) cache[mem_args] = result return result return wrapper
[ "def", "memoize", "(", "func", ",", "cache", ",", "num_args", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ")", ":", "mem_args", "=", "args", "[", ":", "num_args", "]", "if", "mem_args", "in", "cache", ":", "return", "cache", "[", "mem_args", "]", "result", "=", "func", "(", "*", "args", ")", "cache", "[", "mem_args", "]", "=", "result", "return", "result", "return", "wrapper" ]
Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key.
[ "Wrap", "a", "function", "so", "that", "results", "for", "any", "argument", "tuple", "are", "stored", "in", "cache", ".", "Note", "that", "the", "args", "to", "the", "function", "must", "be", "usable", "as", "dictionary", "keys", ".", "Only", "the", "first", "num_args", "are", "considered", "when", "creating", "the", "key", "." ]
9bbbc0f797581c9fdf7da5a70879bee6643024b7
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/utils.py#L664-L681
train
Mangopay/mangopay2-python-sdk
mangopay/utils.py
reraise_as
def reraise_as(new_exception_or_type): """ Obtained from https://github.com/dcramer/reraise/blob/master/src/reraise.py >>> try: >>> do_something_crazy() >>> except Exception: >>> reraise_as(UnhandledException) """ __traceback_hide__ = True # NOQA e_type, e_value, e_traceback = sys.exc_info() if inspect.isclass(new_exception_or_type): new_type = new_exception_or_type new_exception = new_exception_or_type() else: new_type = type(new_exception_or_type) new_exception = new_exception_or_type new_exception.__cause__ = e_value try: six.reraise(new_type, new_exception, e_traceback) finally: del e_traceback
python
def reraise_as(new_exception_or_type): """ Obtained from https://github.com/dcramer/reraise/blob/master/src/reraise.py >>> try: >>> do_something_crazy() >>> except Exception: >>> reraise_as(UnhandledException) """ __traceback_hide__ = True # NOQA e_type, e_value, e_traceback = sys.exc_info() if inspect.isclass(new_exception_or_type): new_type = new_exception_or_type new_exception = new_exception_or_type() else: new_type = type(new_exception_or_type) new_exception = new_exception_or_type new_exception.__cause__ = e_value try: six.reraise(new_type, new_exception, e_traceback) finally: del e_traceback
[ "def", "reraise_as", "(", "new_exception_or_type", ")", ":", "__traceback_hide__", "=", "True", "# NOQA", "e_type", ",", "e_value", ",", "e_traceback", "=", "sys", ".", "exc_info", "(", ")", "if", "inspect", ".", "isclass", "(", "new_exception_or_type", ")", ":", "new_type", "=", "new_exception_or_type", "new_exception", "=", "new_exception_or_type", "(", ")", "else", ":", "new_type", "=", "type", "(", "new_exception_or_type", ")", "new_exception", "=", "new_exception_or_type", "new_exception", ".", "__cause__", "=", "e_value", "try", ":", "six", ".", "reraise", "(", "new_type", ",", "new_exception", ",", "e_traceback", ")", "finally", ":", "del", "e_traceback" ]
Obtained from https://github.com/dcramer/reraise/blob/master/src/reraise.py >>> try: >>> do_something_crazy() >>> except Exception: >>> reraise_as(UnhandledException)
[ "Obtained", "from", "https", ":", "//", "github", ".", "com", "/", "dcramer", "/", "reraise", "/", "blob", "/", "master", "/", "src", "/", "reraise", ".", "py", ">>>", "try", ":", ">>>", "do_something_crazy", "()", ">>>", "except", "Exception", ":", ">>>", "reraise_as", "(", "UnhandledException", ")" ]
9bbbc0f797581c9fdf7da5a70879bee6643024b7
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/utils.py#L684-L708
train
erigones/zabbix-api
zabbix_api.py
hide_auth
def hide_auth(msg): """Remove sensitive information from msg.""" for pattern, repl in RE_HIDE_AUTH: msg = pattern.sub(repl, msg) return msg
python
def hide_auth(msg): """Remove sensitive information from msg.""" for pattern, repl in RE_HIDE_AUTH: msg = pattern.sub(repl, msg) return msg
[ "def", "hide_auth", "(", "msg", ")", ":", "for", "pattern", ",", "repl", "in", "RE_HIDE_AUTH", ":", "msg", "=", "pattern", ".", "sub", "(", "repl", ",", "msg", ")", "return", "msg" ]
Remove sensitive information from msg.
[ "Remove", "sensitive", "information", "from", "msg", "." ]
2474ab1d1ddb46c26eea70671b3a599b836d42da
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L71-L76
train
erigones/zabbix-api
zabbix_api.py
ZabbixAPI.init
def init(self): """Prepare the HTTP handler, URL, and HTTP headers for all subsequent requests""" self.debug('Initializing %r', self) proto = self.server.split('://')[0] if proto == 'https': if hasattr(ssl, 'create_default_context'): context = ssl.create_default_context() if self.ssl_verify: context.check_hostname = True context.verify_mode = ssl.CERT_REQUIRED else: context.check_hostname = False context.verify_mode = ssl.CERT_NONE self._http_handler = urllib2.HTTPSHandler(debuglevel=0, context=context) else: self._http_handler = urllib2.HTTPSHandler(debuglevel=0) elif proto == 'http': self._http_handler = urllib2.HTTPHandler(debuglevel=0) else: raise ValueError('Invalid protocol %s' % proto) self._api_url = self.server + '/api_jsonrpc.php' self._http_headers = { 'Content-Type': 'application/json-rpc', 'User-Agent': 'python/zabbix_api', } if self.httpuser: self.debug('HTTP authentication enabled') auth = self.httpuser + ':' + self.httppasswd self._http_headers['Authorization'] = 'Basic ' + b64encode(auth.encode('utf-8')).decode('ascii')
python
def init(self): """Prepare the HTTP handler, URL, and HTTP headers for all subsequent requests""" self.debug('Initializing %r', self) proto = self.server.split('://')[0] if proto == 'https': if hasattr(ssl, 'create_default_context'): context = ssl.create_default_context() if self.ssl_verify: context.check_hostname = True context.verify_mode = ssl.CERT_REQUIRED else: context.check_hostname = False context.verify_mode = ssl.CERT_NONE self._http_handler = urllib2.HTTPSHandler(debuglevel=0, context=context) else: self._http_handler = urllib2.HTTPSHandler(debuglevel=0) elif proto == 'http': self._http_handler = urllib2.HTTPHandler(debuglevel=0) else: raise ValueError('Invalid protocol %s' % proto) self._api_url = self.server + '/api_jsonrpc.php' self._http_headers = { 'Content-Type': 'application/json-rpc', 'User-Agent': 'python/zabbix_api', } if self.httpuser: self.debug('HTTP authentication enabled') auth = self.httpuser + ':' + self.httppasswd self._http_headers['Authorization'] = 'Basic ' + b64encode(auth.encode('utf-8')).decode('ascii')
[ "def", "init", "(", "self", ")", ":", "self", ".", "debug", "(", "'Initializing %r'", ",", "self", ")", "proto", "=", "self", ".", "server", ".", "split", "(", "'://'", ")", "[", "0", "]", "if", "proto", "==", "'https'", ":", "if", "hasattr", "(", "ssl", ",", "'create_default_context'", ")", ":", "context", "=", "ssl", ".", "create_default_context", "(", ")", "if", "self", ".", "ssl_verify", ":", "context", ".", "check_hostname", "=", "True", "context", ".", "verify_mode", "=", "ssl", ".", "CERT_REQUIRED", "else", ":", "context", ".", "check_hostname", "=", "False", "context", ".", "verify_mode", "=", "ssl", ".", "CERT_NONE", "self", ".", "_http_handler", "=", "urllib2", ".", "HTTPSHandler", "(", "debuglevel", "=", "0", ",", "context", "=", "context", ")", "else", ":", "self", ".", "_http_handler", "=", "urllib2", ".", "HTTPSHandler", "(", "debuglevel", "=", "0", ")", "elif", "proto", "==", "'http'", ":", "self", ".", "_http_handler", "=", "urllib2", ".", "HTTPHandler", "(", "debuglevel", "=", "0", ")", "else", ":", "raise", "ValueError", "(", "'Invalid protocol %s'", "%", "proto", ")", "self", ".", "_api_url", "=", "self", ".", "server", "+", "'/api_jsonrpc.php'", "self", ".", "_http_headers", "=", "{", "'Content-Type'", ":", "'application/json-rpc'", ",", "'User-Agent'", ":", "'python/zabbix_api'", ",", "}", "if", "self", ".", "httpuser", ":", "self", ".", "debug", "(", "'HTTP authentication enabled'", ")", "auth", "=", "self", ".", "httpuser", "+", "':'", "+", "self", ".", "httppasswd", "self", ".", "_http_headers", "[", "'Authorization'", "]", "=", "'Basic '", "+", "b64encode", "(", "auth", ".", "encode", "(", "'utf-8'", ")", ")", ".", "decode", "(", "'ascii'", ")" ]
Prepare the HTTP handler, URL, and HTTP headers for all subsequent requests
[ "Prepare", "the", "HTTP", "handler", "URL", "and", "HTTP", "headers", "for", "all", "subsequent", "requests" ]
2474ab1d1ddb46c26eea70671b3a599b836d42da
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L168-L201
train
erigones/zabbix-api
zabbix_api.py
ZabbixAPI.timestamp_to_datetime
def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT): """Convert unix timestamp to human readable date/time string""" return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format)
python
def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT): """Convert unix timestamp to human readable date/time string""" return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format)
[ "def", "timestamp_to_datetime", "(", "cls", ",", "dt", ",", "dt_format", "=", "DATETIME_FORMAT", ")", ":", "return", "cls", ".", "convert_datetime", "(", "cls", ".", "get_datetime", "(", "dt", ")", ",", "dt_format", "=", "dt_format", ")" ]
Convert unix timestamp to human readable date/time string
[ "Convert", "unix", "timestamp", "to", "human", "readable", "date", "/", "time", "string" ]
2474ab1d1ddb46c26eea70671b3a599b836d42da
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L222-L224
train
erigones/zabbix-api
zabbix_api.py
ZabbixAPI.get_age
def get_age(dt): """Calculate delta between current time and datetime and return a human readable form of the delta object""" delta = datetime.now() - dt days = delta.days hours, rem = divmod(delta.seconds, 3600) minutes, seconds = divmod(rem, 60) if days: return '%dd %dh %dm' % (days, hours, minutes) else: return '%dh %dm %ds' % (hours, minutes, seconds)
python
def get_age(dt): """Calculate delta between current time and datetime and return a human readable form of the delta object""" delta = datetime.now() - dt days = delta.days hours, rem = divmod(delta.seconds, 3600) minutes, seconds = divmod(rem, 60) if days: return '%dd %dh %dm' % (days, hours, minutes) else: return '%dh %dm %ds' % (hours, minutes, seconds)
[ "def", "get_age", "(", "dt", ")", ":", "delta", "=", "datetime", ".", "now", "(", ")", "-", "dt", "days", "=", "delta", ".", "days", "hours", ",", "rem", "=", "divmod", "(", "delta", ".", "seconds", ",", "3600", ")", "minutes", ",", "seconds", "=", "divmod", "(", "rem", ",", "60", ")", "if", "days", ":", "return", "'%dd %dh %dm'", "%", "(", "days", ",", "hours", ",", "minutes", ")", "else", ":", "return", "'%dh %dm %ds'", "%", "(", "hours", ",", "minutes", ",", "seconds", ")" ]
Calculate delta between current time and datetime and return a human readable form of the delta object
[ "Calculate", "delta", "between", "current", "time", "and", "datetime", "and", "return", "a", "human", "readable", "form", "of", "the", "delta", "object" ]
2474ab1d1ddb46c26eea70671b3a599b836d42da
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L227-L237
train
erigones/zabbix-api
zabbix_api.py
ZabbixAPI.json_obj
def json_obj(self, method, params=None, auth=True): """Return JSON object expected by the Zabbix API""" if params is None: params = {} obj = { 'jsonrpc': '2.0', 'method': method, 'params': params, 'auth': self.__auth if auth else None, 'id': self.id, } return json.dumps(obj)
python
def json_obj(self, method, params=None, auth=True): """Return JSON object expected by the Zabbix API""" if params is None: params = {} obj = { 'jsonrpc': '2.0', 'method': method, 'params': params, 'auth': self.__auth if auth else None, 'id': self.id, } return json.dumps(obj)
[ "def", "json_obj", "(", "self", ",", "method", ",", "params", "=", "None", ",", "auth", "=", "True", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "obj", "=", "{", "'jsonrpc'", ":", "'2.0'", ",", "'method'", ":", "method", ",", "'params'", ":", "params", ",", "'auth'", ":", "self", ".", "__auth", "if", "auth", "else", "None", ",", "'id'", ":", "self", ".", "id", ",", "}", "return", "json", ".", "dumps", "(", "obj", ")" ]
Return JSON object expected by the Zabbix API
[ "Return", "JSON", "object", "expected", "by", "the", "Zabbix", "API" ]
2474ab1d1ddb46c26eea70671b3a599b836d42da
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L253-L266
train
erigones/zabbix-api
zabbix_api.py
ZabbixAPI.do_request
def do_request(self, json_obj): """Perform one HTTP request to Zabbix API""" self.debug('Request: url="%s" headers=%s', self._api_url, self._http_headers) self.debug('Request: body=%s', json_obj) self.r_query.append(json_obj) request = urllib2.Request(url=self._api_url, data=json_obj.encode('utf-8'), headers=self._http_headers) opener = urllib2.build_opener(self._http_handler) urllib2.install_opener(opener) try: response = opener.open(request, timeout=self.timeout) except Exception as e: raise ZabbixAPIException('HTTP connection problem: %s' % e) self.debug('Response: code=%s', response.code) # NOTE: Getting a 412 response code means the headers are not in the list of allowed headers. if response.code != 200: raise ZabbixAPIException('HTTP error %s: %s' % (response.status, response.reason)) reads = response.read() if len(reads) == 0: raise ZabbixAPIException('Received zero answer') try: jobj = json.loads(reads.decode('utf-8')) except ValueError as e: self.log(ERROR, 'Unable to decode. returned string: %s', reads) raise ZabbixAPIException('Unable to decode response: %s' % e) self.debug('Response: body=%s', jobj) self.id += 1 if 'error' in jobj: # zabbix API error error = jobj['error'] if isinstance(error, dict): raise ZabbixAPIError(**error) try: return jobj['result'] except KeyError: raise ZabbixAPIException('Missing result in API response')
python
def do_request(self, json_obj): """Perform one HTTP request to Zabbix API""" self.debug('Request: url="%s" headers=%s', self._api_url, self._http_headers) self.debug('Request: body=%s', json_obj) self.r_query.append(json_obj) request = urllib2.Request(url=self._api_url, data=json_obj.encode('utf-8'), headers=self._http_headers) opener = urllib2.build_opener(self._http_handler) urllib2.install_opener(opener) try: response = opener.open(request, timeout=self.timeout) except Exception as e: raise ZabbixAPIException('HTTP connection problem: %s' % e) self.debug('Response: code=%s', response.code) # NOTE: Getting a 412 response code means the headers are not in the list of allowed headers. if response.code != 200: raise ZabbixAPIException('HTTP error %s: %s' % (response.status, response.reason)) reads = response.read() if len(reads) == 0: raise ZabbixAPIException('Received zero answer') try: jobj = json.loads(reads.decode('utf-8')) except ValueError as e: self.log(ERROR, 'Unable to decode. returned string: %s', reads) raise ZabbixAPIException('Unable to decode response: %s' % e) self.debug('Response: body=%s', jobj) self.id += 1 if 'error' in jobj: # zabbix API error error = jobj['error'] if isinstance(error, dict): raise ZabbixAPIError(**error) try: return jobj['result'] except KeyError: raise ZabbixAPIException('Missing result in API response')
[ "def", "do_request", "(", "self", ",", "json_obj", ")", ":", "self", ".", "debug", "(", "'Request: url=\"%s\" headers=%s'", ",", "self", ".", "_api_url", ",", "self", ".", "_http_headers", ")", "self", ".", "debug", "(", "'Request: body=%s'", ",", "json_obj", ")", "self", ".", "r_query", ".", "append", "(", "json_obj", ")", "request", "=", "urllib2", ".", "Request", "(", "url", "=", "self", ".", "_api_url", ",", "data", "=", "json_obj", ".", "encode", "(", "'utf-8'", ")", ",", "headers", "=", "self", ".", "_http_headers", ")", "opener", "=", "urllib2", ".", "build_opener", "(", "self", ".", "_http_handler", ")", "urllib2", ".", "install_opener", "(", "opener", ")", "try", ":", "response", "=", "opener", ".", "open", "(", "request", ",", "timeout", "=", "self", ".", "timeout", ")", "except", "Exception", "as", "e", ":", "raise", "ZabbixAPIException", "(", "'HTTP connection problem: %s'", "%", "e", ")", "self", ".", "debug", "(", "'Response: code=%s'", ",", "response", ".", "code", ")", "# NOTE: Getting a 412 response code means the headers are not in the list of allowed headers.", "if", "response", ".", "code", "!=", "200", ":", "raise", "ZabbixAPIException", "(", "'HTTP error %s: %s'", "%", "(", "response", ".", "status", ",", "response", ".", "reason", ")", ")", "reads", "=", "response", ".", "read", "(", ")", "if", "len", "(", "reads", ")", "==", "0", ":", "raise", "ZabbixAPIException", "(", "'Received zero answer'", ")", "try", ":", "jobj", "=", "json", ".", "loads", "(", "reads", ".", "decode", "(", "'utf-8'", ")", ")", "except", "ValueError", "as", "e", ":", "self", ".", "log", "(", "ERROR", ",", "'Unable to decode. returned string: %s'", ",", "reads", ")", "raise", "ZabbixAPIException", "(", "'Unable to decode response: %s'", "%", "e", ")", "self", ".", "debug", "(", "'Response: body=%s'", ",", "jobj", ")", "self", ".", "id", "+=", "1", "if", "'error'", "in", "jobj", ":", "# zabbix API error", "error", "=", "jobj", "[", "'error'", "]", "if", "isinstance", "(", "error", ",", "dict", ")", ":", "raise", "ZabbixAPIError", "(", "*", "*", "error", ")", "try", ":", "return", "jobj", "[", "'result'", "]", "except", "KeyError", ":", "raise", "ZabbixAPIException", "(", "'Missing result in API response'", ")" ]
Perform one HTTP request to Zabbix API
[ "Perform", "one", "HTTP", "request", "to", "Zabbix", "API" ]
2474ab1d1ddb46c26eea70671b3a599b836d42da
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L268-L312
train
erigones/zabbix-api
zabbix_api.py
ZabbixAPI.login
def login(self, user=None, password=None, save=True): """Perform a user.login API request""" if user and password: if save: self.__username = user self.__password = password elif self.__username and self.__password: user = self.__username password = self.__password else: raise ZabbixAPIException('No authentication information available.') self.last_login = time() # Don't print the raw password hashed_pw_string = 'md5(%s)' % md5(password.encode('utf-8')).hexdigest() self.debug('Trying to login with %r:%r', user, hashed_pw_string) obj = self.json_obj('user.login', params={'user': user, 'password': password}, auth=False) self.__auth = self.do_request(obj)
python
def login(self, user=None, password=None, save=True): """Perform a user.login API request""" if user and password: if save: self.__username = user self.__password = password elif self.__username and self.__password: user = self.__username password = self.__password else: raise ZabbixAPIException('No authentication information available.') self.last_login = time() # Don't print the raw password hashed_pw_string = 'md5(%s)' % md5(password.encode('utf-8')).hexdigest() self.debug('Trying to login with %r:%r', user, hashed_pw_string) obj = self.json_obj('user.login', params={'user': user, 'password': password}, auth=False) self.__auth = self.do_request(obj)
[ "def", "login", "(", "self", ",", "user", "=", "None", ",", "password", "=", "None", ",", "save", "=", "True", ")", ":", "if", "user", "and", "password", ":", "if", "save", ":", "self", ".", "__username", "=", "user", "self", ".", "__password", "=", "password", "elif", "self", ".", "__username", "and", "self", ".", "__password", ":", "user", "=", "self", ".", "__username", "password", "=", "self", ".", "__password", "else", ":", "raise", "ZabbixAPIException", "(", "'No authentication information available.'", ")", "self", ".", "last_login", "=", "time", "(", ")", "# Don't print the raw password", "hashed_pw_string", "=", "'md5(%s)'", "%", "md5", "(", "password", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "self", ".", "debug", "(", "'Trying to login with %r:%r'", ",", "user", ",", "hashed_pw_string", ")", "obj", "=", "self", ".", "json_obj", "(", "'user.login'", ",", "params", "=", "{", "'user'", ":", "user", ",", "'password'", ":", "password", "}", ",", "auth", "=", "False", ")", "self", ".", "__auth", "=", "self", ".", "do_request", "(", "obj", ")" ]
Perform a user.login API request
[ "Perform", "a", "user", ".", "login", "API", "request" ]
2474ab1d1ddb46c26eea70671b3a599b836d42da
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L314-L331
train
erigones/zabbix-api
zabbix_api.py
ZabbixAPI.relogin
def relogin(self): """Perform a re-login""" try: self.__auth = None # reset auth before relogin self.login() except ZabbixAPIException as e: self.log(ERROR, 'Zabbix API relogin error (%s)', e) self.__auth = None # logged_in() will always return False raise
python
def relogin(self): """Perform a re-login""" try: self.__auth = None # reset auth before relogin self.login() except ZabbixAPIException as e: self.log(ERROR, 'Zabbix API relogin error (%s)', e) self.__auth = None # logged_in() will always return False raise
[ "def", "relogin", "(", "self", ")", ":", "try", ":", "self", ".", "__auth", "=", "None", "# reset auth before relogin", "self", ".", "login", "(", ")", "except", "ZabbixAPIException", "as", "e", ":", "self", ".", "log", "(", "ERROR", ",", "'Zabbix API relogin error (%s)'", ",", "e", ")", "self", ".", "__auth", "=", "None", "# logged_in() will always return False", "raise" ]
Perform a re-login
[ "Perform", "a", "re", "-", "login" ]
2474ab1d1ddb46c26eea70671b3a599b836d42da
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L333-L341
train
erigones/zabbix-api
zabbix_api.py
ZabbixAPI.check_auth
def check_auth(self): """Perform a re-login if not signed in or raise an exception""" if not self.logged_in: if self.relogin_interval and self.last_login and (time() - self.last_login) > self.relogin_interval: self.log(WARNING, 'Zabbix API not logged in. Performing Zabbix API relogin after %d seconds', self.relogin_interval) self.relogin() # Will raise exception in case of login error else: raise ZabbixAPIException('Not logged in.')
python
def check_auth(self): """Perform a re-login if not signed in or raise an exception""" if not self.logged_in: if self.relogin_interval and self.last_login and (time() - self.last_login) > self.relogin_interval: self.log(WARNING, 'Zabbix API not logged in. Performing Zabbix API relogin after %d seconds', self.relogin_interval) self.relogin() # Will raise exception in case of login error else: raise ZabbixAPIException('Not logged in.')
[ "def", "check_auth", "(", "self", ")", ":", "if", "not", "self", ".", "logged_in", ":", "if", "self", ".", "relogin_interval", "and", "self", ".", "last_login", "and", "(", "time", "(", ")", "-", "self", ".", "last_login", ")", ">", "self", ".", "relogin_interval", ":", "self", ".", "log", "(", "WARNING", ",", "'Zabbix API not logged in. Performing Zabbix API relogin after %d seconds'", ",", "self", ".", "relogin_interval", ")", "self", ".", "relogin", "(", ")", "# Will raise exception in case of login error", "else", ":", "raise", "ZabbixAPIException", "(", "'Not logged in.'", ")" ]
Perform a re-login if not signed in or raise an exception
[ "Perform", "a", "re", "-", "login", "if", "not", "signed", "in", "or", "raise", "an", "exception" ]
2474ab1d1ddb46c26eea70671b3a599b836d42da
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L347-L355
train
erigones/zabbix-api
zabbix_api.py
ZabbixAPI.call
def call(self, method, params=None): """Check authentication and perform actual API request and relogin if needed""" start_time = time() self.check_auth() self.log(INFO, '[%s-%05d] Calling Zabbix API method "%s"', start_time, self.id, method) self.log(DEBUG, '\twith parameters: %s', params) try: return self.do_request(self.json_obj(method, params=params)) except ZabbixAPIError as ex: if self.relogin_interval and any(i in ex.error['data'] for i in self.LOGIN_ERRORS): self.log(WARNING, 'Zabbix API not logged in (%s). Performing Zabbix API relogin', ex) self.relogin() # Will raise exception in case of login error return self.do_request(self.json_obj(method, params=params)) raise # Re-raise the exception finally: self.log(INFO, '[%s-%05d] Zabbix API method "%s" finished in %g seconds', start_time, self.id, method, (time() - start_time))
python
def call(self, method, params=None): """Check authentication and perform actual API request and relogin if needed""" start_time = time() self.check_auth() self.log(INFO, '[%s-%05d] Calling Zabbix API method "%s"', start_time, self.id, method) self.log(DEBUG, '\twith parameters: %s', params) try: return self.do_request(self.json_obj(method, params=params)) except ZabbixAPIError as ex: if self.relogin_interval and any(i in ex.error['data'] for i in self.LOGIN_ERRORS): self.log(WARNING, 'Zabbix API not logged in (%s). Performing Zabbix API relogin', ex) self.relogin() # Will raise exception in case of login error return self.do_request(self.json_obj(method, params=params)) raise # Re-raise the exception finally: self.log(INFO, '[%s-%05d] Zabbix API method "%s" finished in %g seconds', start_time, self.id, method, (time() - start_time))
[ "def", "call", "(", "self", ",", "method", ",", "params", "=", "None", ")", ":", "start_time", "=", "time", "(", ")", "self", ".", "check_auth", "(", ")", "self", ".", "log", "(", "INFO", ",", "'[%s-%05d] Calling Zabbix API method \"%s\"'", ",", "start_time", ",", "self", ".", "id", ",", "method", ")", "self", ".", "log", "(", "DEBUG", ",", "'\\twith parameters: %s'", ",", "params", ")", "try", ":", "return", "self", ".", "do_request", "(", "self", ".", "json_obj", "(", "method", ",", "params", "=", "params", ")", ")", "except", "ZabbixAPIError", "as", "ex", ":", "if", "self", ".", "relogin_interval", "and", "any", "(", "i", "in", "ex", ".", "error", "[", "'data'", "]", "for", "i", "in", "self", ".", "LOGIN_ERRORS", ")", ":", "self", ".", "log", "(", "WARNING", ",", "'Zabbix API not logged in (%s). Performing Zabbix API relogin'", ",", "ex", ")", "self", ".", "relogin", "(", ")", "# Will raise exception in case of login error", "return", "self", ".", "do_request", "(", "self", ".", "json_obj", "(", "method", ",", "params", "=", "params", ")", ")", "raise", "# Re-raise the exception", "finally", ":", "self", ".", "log", "(", "INFO", ",", "'[%s-%05d] Zabbix API method \"%s\" finished in %g seconds'", ",", "start_time", ",", "self", ".", "id", ",", "method", ",", "(", "time", "(", ")", "-", "start_time", ")", ")" ]
Check authentication and perform actual API request and relogin if needed
[ "Check", "authentication", "and", "perform", "actual", "API", "request", "and", "relogin", "if", "needed" ]
2474ab1d1ddb46c26eea70671b3a599b836d42da
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L361-L378
train
nikhilkumarsingh/content-downloader
ctdl/gui_downloader.py
download_parallel
def download_parallel(url, directory, idx, min_file_size = 0, max_file_size = -1, no_redirects = False, pos = 0, mode = 's'): """ download function to download parallely """ global main_it global exit_flag global total_chunks global file_name global i_max file_name[idx]= url.split('/')[-1] file_address = directory + '/' + file_name[idx] is_redirects = not no_redirects resp = s.get(url, stream = True, allow_redirects = is_redirects) if not resp.status_code == 200: # ignore this file since server returns invalid response exit_flag += 1 return try: total_size = int(resp.headers['content-length']) except KeyError: total_size = len(resp.content) total_chunks[idx] = total_size / chunk_size if total_chunks[idx] < min_file_size: # ignore this file since file size is lesser than min_file_size exit_flag += 1 return elif max_file_size != -1 and total_chunks[idx] > max_file_size: # ignore this file since file size is greater than max_file_size exit_flag += 1 return file_iterable = resp.iter_content(chunk_size = chunk_size) with open(file_address, 'wb') as f: for sno, data in enumerate(file_iterable): i_max[idx] = sno + 1 f.write(data) exit_flag += 1
python
def download_parallel(url, directory, idx, min_file_size = 0, max_file_size = -1, no_redirects = False, pos = 0, mode = 's'): """ download function to download parallely """ global main_it global exit_flag global total_chunks global file_name global i_max file_name[idx]= url.split('/')[-1] file_address = directory + '/' + file_name[idx] is_redirects = not no_redirects resp = s.get(url, stream = True, allow_redirects = is_redirects) if not resp.status_code == 200: # ignore this file since server returns invalid response exit_flag += 1 return try: total_size = int(resp.headers['content-length']) except KeyError: total_size = len(resp.content) total_chunks[idx] = total_size / chunk_size if total_chunks[idx] < min_file_size: # ignore this file since file size is lesser than min_file_size exit_flag += 1 return elif max_file_size != -1 and total_chunks[idx] > max_file_size: # ignore this file since file size is greater than max_file_size exit_flag += 1 return file_iterable = resp.iter_content(chunk_size = chunk_size) with open(file_address, 'wb') as f: for sno, data in enumerate(file_iterable): i_max[idx] = sno + 1 f.write(data) exit_flag += 1
[ "def", "download_parallel", "(", "url", ",", "directory", ",", "idx", ",", "min_file_size", "=", "0", ",", "max_file_size", "=", "-", "1", ",", "no_redirects", "=", "False", ",", "pos", "=", "0", ",", "mode", "=", "'s'", ")", ":", "global", "main_it", "global", "exit_flag", "global", "total_chunks", "global", "file_name", "global", "i_max", "file_name", "[", "idx", "]", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "file_address", "=", "directory", "+", "'/'", "+", "file_name", "[", "idx", "]", "is_redirects", "=", "not", "no_redirects", "resp", "=", "s", ".", "get", "(", "url", ",", "stream", "=", "True", ",", "allow_redirects", "=", "is_redirects", ")", "if", "not", "resp", ".", "status_code", "==", "200", ":", "# ignore this file since server returns invalid response", "exit_flag", "+=", "1", "return", "try", ":", "total_size", "=", "int", "(", "resp", ".", "headers", "[", "'content-length'", "]", ")", "except", "KeyError", ":", "total_size", "=", "len", "(", "resp", ".", "content", ")", "total_chunks", "[", "idx", "]", "=", "total_size", "/", "chunk_size", "if", "total_chunks", "[", "idx", "]", "<", "min_file_size", ":", "# ignore this file since file size is lesser than min_file_size", "exit_flag", "+=", "1", "return", "elif", "max_file_size", "!=", "-", "1", "and", "total_chunks", "[", "idx", "]", ">", "max_file_size", ":", "# ignore this file since file size is greater than max_file_size", "exit_flag", "+=", "1", "return", "file_iterable", "=", "resp", ".", "iter_content", "(", "chunk_size", "=", "chunk_size", ")", "with", "open", "(", "file_address", ",", "'wb'", ")", "as", "f", ":", "for", "sno", ",", "data", "in", "enumerate", "(", "file_iterable", ")", ":", "i_max", "[", "idx", "]", "=", "sno", "+", "1", "f", ".", "write", "(", "data", ")", "exit_flag", "+=", "1" ]
download function to download parallely
[ "download", "function", "to", "download", "parallely" ]
8b14af3a6eadcc43581e0425dc1d218208de12df
https://github.com/nikhilkumarsingh/content-downloader/blob/8b14af3a6eadcc43581e0425dc1d218208de12df/ctdl/gui_downloader.py#L75-L116
train
nikhilkumarsingh/content-downloader
ctdl/gui_downloader.py
download_parallel_gui
def download_parallel_gui(root, urls, directory, min_file_size, max_file_size, no_redirects): """ called when paralled downloading is true """ global parallel # create directory to save files if not os.path.exists(directory): os.makedirs(directory) parallel = True app = progress_class(root, urls, directory, min_file_size, max_file_size, no_redirects)
python
def download_parallel_gui(root, urls, directory, min_file_size, max_file_size, no_redirects): """ called when paralled downloading is true """ global parallel # create directory to save files if not os.path.exists(directory): os.makedirs(directory) parallel = True app = progress_class(root, urls, directory, min_file_size, max_file_size, no_redirects)
[ "def", "download_parallel_gui", "(", "root", ",", "urls", ",", "directory", ",", "min_file_size", ",", "max_file_size", ",", "no_redirects", ")", ":", "global", "parallel", "# create directory to save files", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ")", "parallel", "=", "True", "app", "=", "progress_class", "(", "root", ",", "urls", ",", "directory", ",", "min_file_size", ",", "max_file_size", ",", "no_redirects", ")" ]
called when paralled downloading is true
[ "called", "when", "paralled", "downloading", "is", "true" ]
8b14af3a6eadcc43581e0425dc1d218208de12df
https://github.com/nikhilkumarsingh/content-downloader/blob/8b14af3a6eadcc43581e0425dc1d218208de12df/ctdl/gui_downloader.py#L239-L249
train
nikhilkumarsingh/content-downloader
ctdl/gui_downloader.py
download_series_gui
def download_series_gui(frame, urls, directory, min_file_size, max_file_size, no_redirects): """ called when user wants serial downloading """ # create directory to save files if not os.path.exists(directory): os.makedirs(directory) app = progress_class(frame, urls, directory, min_file_size, max_file_size, no_redirects)
python
def download_series_gui(frame, urls, directory, min_file_size, max_file_size, no_redirects): """ called when user wants serial downloading """ # create directory to save files if not os.path.exists(directory): os.makedirs(directory) app = progress_class(frame, urls, directory, min_file_size, max_file_size, no_redirects)
[ "def", "download_series_gui", "(", "frame", ",", "urls", ",", "directory", ",", "min_file_size", ",", "max_file_size", ",", "no_redirects", ")", ":", "# create directory to save files", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ")", "app", "=", "progress_class", "(", "frame", ",", "urls", ",", "directory", ",", "min_file_size", ",", "max_file_size", ",", "no_redirects", ")" ]
called when user wants serial downloading
[ "called", "when", "user", "wants", "serial", "downloading" ]
8b14af3a6eadcc43581e0425dc1d218208de12df
https://github.com/nikhilkumarsingh/content-downloader/blob/8b14af3a6eadcc43581e0425dc1d218208de12df/ctdl/gui_downloader.py#L254-L262
train
nikhilkumarsingh/content-downloader
ctdl/gui_downloader.py
myThread.run
def run(self): """ function called when thread is started """ global parallel if parallel: download_parallel(self.url, self.directory, self.idx, self.min_file_size, self.max_file_size, self.no_redirects) else: download(self.url, self.directory, self.idx, self.min_file_size, self.max_file_size, self.no_redirects)
python
def run(self): """ function called when thread is started """ global parallel if parallel: download_parallel(self.url, self.directory, self.idx, self.min_file_size, self.max_file_size, self.no_redirects) else: download(self.url, self.directory, self.idx, self.min_file_size, self.max_file_size, self.no_redirects)
[ "def", "run", "(", "self", ")", ":", "global", "parallel", "if", "parallel", ":", "download_parallel", "(", "self", ".", "url", ",", "self", ".", "directory", ",", "self", ".", "idx", ",", "self", ".", "min_file_size", ",", "self", ".", "max_file_size", ",", "self", ".", "no_redirects", ")", "else", ":", "download", "(", "self", ".", "url", ",", "self", ".", "directory", ",", "self", ".", "idx", ",", "self", ".", "min_file_size", ",", "self", ".", "max_file_size", ",", "self", ".", "no_redirects", ")" ]
function called when thread is started
[ "function", "called", "when", "thread", "is", "started" ]
8b14af3a6eadcc43581e0425dc1d218208de12df
https://github.com/nikhilkumarsingh/content-downloader/blob/8b14af3a6eadcc43581e0425dc1d218208de12df/ctdl/gui_downloader.py#L134-L145
train
nikhilkumarsingh/content-downloader
ctdl/gui_downloader.py
progress_class.start
def start(self): """ function to initialize thread for downloading """ global parallel for self.i in range(0, self.length): if parallel: self.thread.append(myThread(self.url[ self.i ], self.directory, self.i, self.min_file_size, self.max_file_size, self.no_redirects)) else: # if not parallel whole url list is passed self.thread.append(myThread(self.url, self.directory, self.i , self.min_file_size, self.max_file_size, self.no_redirects)) self.progress[self.i]["value"] = 0 self.bytes[self.i] = 0 self.thread[self.i].start() self.read_bytes()
python
def start(self): """ function to initialize thread for downloading """ global parallel for self.i in range(0, self.length): if parallel: self.thread.append(myThread(self.url[ self.i ], self.directory, self.i, self.min_file_size, self.max_file_size, self.no_redirects)) else: # if not parallel whole url list is passed self.thread.append(myThread(self.url, self.directory, self.i , self.min_file_size, self.max_file_size, self.no_redirects)) self.progress[self.i]["value"] = 0 self.bytes[self.i] = 0 self.thread[self.i].start() self.read_bytes()
[ "def", "start", "(", "self", ")", ":", "global", "parallel", "for", "self", ".", "i", "in", "range", "(", "0", ",", "self", ".", "length", ")", ":", "if", "parallel", ":", "self", ".", "thread", ".", "append", "(", "myThread", "(", "self", ".", "url", "[", "self", ".", "i", "]", ",", "self", ".", "directory", ",", "self", ".", "i", ",", "self", ".", "min_file_size", ",", "self", ".", "max_file_size", ",", "self", ".", "no_redirects", ")", ")", "else", ":", "# if not parallel whole url list is passed", "self", ".", "thread", ".", "append", "(", "myThread", "(", "self", ".", "url", ",", "self", ".", "directory", ",", "self", ".", "i", ",", "self", ".", "min_file_size", ",", "self", ".", "max_file_size", ",", "self", ".", "no_redirects", ")", ")", "self", ".", "progress", "[", "self", ".", "i", "]", "[", "\"value\"", "]", "=", "0", "self", ".", "bytes", "[", "self", ".", "i", "]", "=", "0", "self", ".", "thread", "[", "self", ".", "i", "]", ".", "start", "(", ")", "self", ".", "read_bytes", "(", ")" ]
function to initialize thread for downloading
[ "function", "to", "initialize", "thread", "for", "downloading" ]
8b14af3a6eadcc43581e0425dc1d218208de12df
https://github.com/nikhilkumarsingh/content-downloader/blob/8b14af3a6eadcc43581e0425dc1d218208de12df/ctdl/gui_downloader.py#L198-L215
train
nikhilkumarsingh/content-downloader
ctdl/gui_downloader.py
progress_class.read_bytes
def read_bytes(self): """ reading bytes; update progress bar after 1 ms """ global exit_flag for self.i in range(0, self.length) : self.bytes[self.i] = i_max[self.i] self.maxbytes[self.i] = total_chunks[self.i] self.progress[self.i]["maximum"] = total_chunks[self.i] self.progress[self.i]["value"] = self.bytes[self.i] self.str[self.i].set(file_name[self.i]+ " " + str(self.bytes[self.i]) + "KB / " + str(int(self.maxbytes[self.i] + 1)) + " KB") if exit_flag == self.length: exit_flag = 0 self.frame.destroy() else: self.frame.after(10, self.read_bytes)
python
def read_bytes(self): """ reading bytes; update progress bar after 1 ms """ global exit_flag for self.i in range(0, self.length) : self.bytes[self.i] = i_max[self.i] self.maxbytes[self.i] = total_chunks[self.i] self.progress[self.i]["maximum"] = total_chunks[self.i] self.progress[self.i]["value"] = self.bytes[self.i] self.str[self.i].set(file_name[self.i]+ " " + str(self.bytes[self.i]) + "KB / " + str(int(self.maxbytes[self.i] + 1)) + " KB") if exit_flag == self.length: exit_flag = 0 self.frame.destroy() else: self.frame.after(10, self.read_bytes)
[ "def", "read_bytes", "(", "self", ")", ":", "global", "exit_flag", "for", "self", ".", "i", "in", "range", "(", "0", ",", "self", ".", "length", ")", ":", "self", ".", "bytes", "[", "self", ".", "i", "]", "=", "i_max", "[", "self", ".", "i", "]", "self", ".", "maxbytes", "[", "self", ".", "i", "]", "=", "total_chunks", "[", "self", ".", "i", "]", "self", ".", "progress", "[", "self", ".", "i", "]", "[", "\"maximum\"", "]", "=", "total_chunks", "[", "self", ".", "i", "]", "self", ".", "progress", "[", "self", ".", "i", "]", "[", "\"value\"", "]", "=", "self", ".", "bytes", "[", "self", ".", "i", "]", "self", ".", "str", "[", "self", ".", "i", "]", ".", "set", "(", "file_name", "[", "self", ".", "i", "]", "+", "\" \"", "+", "str", "(", "self", ".", "bytes", "[", "self", ".", "i", "]", ")", "+", "\"KB / \"", "+", "str", "(", "int", "(", "self", ".", "maxbytes", "[", "self", ".", "i", "]", "+", "1", ")", ")", "+", "\" KB\"", ")", "if", "exit_flag", "==", "self", ".", "length", ":", "exit_flag", "=", "0", "self", ".", "frame", ".", "destroy", "(", ")", "else", ":", "self", ".", "frame", ".", "after", "(", "10", ",", "self", ".", "read_bytes", ")" ]
reading bytes; update progress bar after 1 ms
[ "reading", "bytes", ";", "update", "progress", "bar", "after", "1", "ms" ]
8b14af3a6eadcc43581e0425dc1d218208de12df
https://github.com/nikhilkumarsingh/content-downloader/blob/8b14af3a6eadcc43581e0425dc1d218208de12df/ctdl/gui_downloader.py#L218-L236
train
common-workflow-language/schema_salad
schema_salad/codegen_base.py
CodeGenBase.declare_type
def declare_type(self, declared_type): # type: (TypeDef) -> TypeDef """Add this type to our collection, if needed.""" if declared_type not in self.collected_types: self.collected_types[declared_type.name] = declared_type return declared_type
python
def declare_type(self, declared_type): # type: (TypeDef) -> TypeDef """Add this type to our collection, if needed.""" if declared_type not in self.collected_types: self.collected_types[declared_type.name] = declared_type return declared_type
[ "def", "declare_type", "(", "self", ",", "declared_type", ")", ":", "# type: (TypeDef) -> TypeDef", "if", "declared_type", "not", "in", "self", ".", "collected_types", ":", "self", ".", "collected_types", "[", "declared_type", ".", "name", "]", "=", "declared_type", "return", "declared_type" ]
Add this type to our collection, if needed.
[ "Add", "this", "type", "to", "our", "collection", "if", "needed", "." ]
608ba207b9058fe0a9c3db161058ab3782eef015
https://github.com/common-workflow-language/schema_salad/blob/608ba207b9058fe0a9c3db161058ab3782eef015/schema_salad/codegen_base.py#L33-L37
train
common-workflow-language/schema_salad
schema_salad/schema.py
get_metaschema
def get_metaschema(): # type: () -> Tuple[Names, List[Dict[Text, Any]], Loader] """Instantiate the metaschema.""" loader = ref_resolver.Loader({ "Any": "https://w3id.org/cwl/salad#Any", "ArraySchema": "https://w3id.org/cwl/salad#ArraySchema", "Array_symbol": "https://w3id.org/cwl/salad#ArraySchema/type/Array_symbol", "DocType": "https://w3id.org/cwl/salad#DocType", "Documentation": "https://w3id.org/cwl/salad#Documentation", "Documentation_symbol": "https://w3id.org/cwl/salad#Documentation/type/Documentation_symbol", "Documented": "https://w3id.org/cwl/salad#Documented", "EnumSchema": "https://w3id.org/cwl/salad#EnumSchema", "Enum_symbol": "https://w3id.org/cwl/salad#EnumSchema/type/Enum_symbol", "JsonldPredicate": "https://w3id.org/cwl/salad#JsonldPredicate", "NamedType": "https://w3id.org/cwl/salad#NamedType", "PrimitiveType": "https://w3id.org/cwl/salad#PrimitiveType", "RecordField": "https://w3id.org/cwl/salad#RecordField", "RecordSchema": "https://w3id.org/cwl/salad#RecordSchema", "Record_symbol": "https://w3id.org/cwl/salad#RecordSchema/type/Record_symbol", "SaladEnumSchema": "https://w3id.org/cwl/salad#SaladEnumSchema", "SaladRecordField": "https://w3id.org/cwl/salad#SaladRecordField", "SaladRecordSchema": "https://w3id.org/cwl/salad#SaladRecordSchema", "SchemaDefinedType": "https://w3id.org/cwl/salad#SchemaDefinedType", "SpecializeDef": "https://w3id.org/cwl/salad#SpecializeDef", "_container": "https://w3id.org/cwl/salad#JsonldPredicate/_container", "_id": { "@id": "https://w3id.org/cwl/salad#_id", "@type": "@id", "identity": True }, "_type": "https://w3id.org/cwl/salad#JsonldPredicate/_type", "abstract": "https://w3id.org/cwl/salad#SaladRecordSchema/abstract", "array": "https://w3id.org/cwl/salad#array", "boolean": "http://www.w3.org/2001/XMLSchema#boolean", "dct": "http://purl.org/dc/terms/", "default": { "@id": "https://w3id.org/cwl/salad#default", "noLinkCheck": True }, "doc": "rdfs:comment", "docAfter": { "@id": "https://w3id.org/cwl/salad#docAfter", "@type": "@id" }, "docChild": { "@id": "https://w3id.org/cwl/salad#docChild", "@type": "@id" }, "docParent": { "@id": "https://w3id.org/cwl/salad#docParent", "@type": "@id" }, "documentRoot": "https://w3id.org/cwl/salad#SchemaDefinedType/documentRoot", "documentation": "https://w3id.org/cwl/salad#documentation", "double": "http://www.w3.org/2001/XMLSchema#double", "enum": "https://w3id.org/cwl/salad#enum", "extends": { "@id": "https://w3id.org/cwl/salad#extends", "@type": "@id", "refScope": 1 }, "fields": { "@id": "https://w3id.org/cwl/salad#fields", "mapPredicate": "type", "mapSubject": "name" }, "float": "http://www.w3.org/2001/XMLSchema#float", "identity": "https://w3id.org/cwl/salad#JsonldPredicate/identity", "inVocab": "https://w3id.org/cwl/salad#NamedType/inVocab", "int": "http://www.w3.org/2001/XMLSchema#int", "items": { "@id": "https://w3id.org/cwl/salad#items", "@type": "@vocab", "refScope": 2 }, "jsonldPredicate": "sld:jsonldPredicate", "long": "http://www.w3.org/2001/XMLSchema#long", "mapPredicate": "https://w3id.org/cwl/salad#JsonldPredicate/mapPredicate", "mapSubject": "https://w3id.org/cwl/salad#JsonldPredicate/mapSubject", "name": "@id", "noLinkCheck": "https://w3id.org/cwl/salad#JsonldPredicate/noLinkCheck", "null": "https://w3id.org/cwl/salad#null", "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdfs": "http://www.w3.org/2000/01/rdf-schema#", "record": "https://w3id.org/cwl/salad#record", "refScope": "https://w3id.org/cwl/salad#JsonldPredicate/refScope", "sld": "https://w3id.org/cwl/salad#", "specialize": { "@id": "https://w3id.org/cwl/salad#specialize", "mapPredicate": "specializeTo", "mapSubject": "specializeFrom" }, "specializeFrom": { "@id": "https://w3id.org/cwl/salad#specializeFrom", "@type": "@id", "refScope": 1 }, "specializeTo": { "@id": "https://w3id.org/cwl/salad#specializeTo", "@type": "@id", "refScope": 1 }, "string": "http://www.w3.org/2001/XMLSchema#string", "subscope": "https://w3id.org/cwl/salad#JsonldPredicate/subscope", "symbols": { "@id": "https://w3id.org/cwl/salad#symbols", "@type": "@id", "identity": True }, "type": { "@id": "https://w3id.org/cwl/salad#type", "@type": "@vocab", "refScope": 2, "typeDSL": True }, "typeDSL": "https://w3id.org/cwl/salad#JsonldPredicate/typeDSL", "xsd": "http://www.w3.org/2001/XMLSchema#" }) for salad in SALAD_FILES: with resource_stream(__name__, 'metaschema/' + salad) as stream: loader.cache["https://w3id.org/cwl/" + salad] = stream.read() with resource_stream(__name__, 'metaschema/metaschema.yml') as stream: loader.cache["https://w3id.org/cwl/salad"] = stream.read() j = yaml.round_trip_load(loader.cache["https://w3id.org/cwl/salad"]) add_lc_filename(j, "metaschema.yml") j, _ = loader.resolve_all(j, "https://w3id.org/cwl/salad#") sch_obj = make_avro(j, loader) try: sch_names = make_avro_schema_from_avro(sch_obj) except SchemaParseException: _logger.error("Metaschema error, avro was:\n%s", json_dumps(sch_obj, indent=4)) raise validate_doc(sch_names, j, loader, strict=True) return (sch_names, j, loader)
python
def get_metaschema(): # type: () -> Tuple[Names, List[Dict[Text, Any]], Loader] """Instantiate the metaschema.""" loader = ref_resolver.Loader({ "Any": "https://w3id.org/cwl/salad#Any", "ArraySchema": "https://w3id.org/cwl/salad#ArraySchema", "Array_symbol": "https://w3id.org/cwl/salad#ArraySchema/type/Array_symbol", "DocType": "https://w3id.org/cwl/salad#DocType", "Documentation": "https://w3id.org/cwl/salad#Documentation", "Documentation_symbol": "https://w3id.org/cwl/salad#Documentation/type/Documentation_symbol", "Documented": "https://w3id.org/cwl/salad#Documented", "EnumSchema": "https://w3id.org/cwl/salad#EnumSchema", "Enum_symbol": "https://w3id.org/cwl/salad#EnumSchema/type/Enum_symbol", "JsonldPredicate": "https://w3id.org/cwl/salad#JsonldPredicate", "NamedType": "https://w3id.org/cwl/salad#NamedType", "PrimitiveType": "https://w3id.org/cwl/salad#PrimitiveType", "RecordField": "https://w3id.org/cwl/salad#RecordField", "RecordSchema": "https://w3id.org/cwl/salad#RecordSchema", "Record_symbol": "https://w3id.org/cwl/salad#RecordSchema/type/Record_symbol", "SaladEnumSchema": "https://w3id.org/cwl/salad#SaladEnumSchema", "SaladRecordField": "https://w3id.org/cwl/salad#SaladRecordField", "SaladRecordSchema": "https://w3id.org/cwl/salad#SaladRecordSchema", "SchemaDefinedType": "https://w3id.org/cwl/salad#SchemaDefinedType", "SpecializeDef": "https://w3id.org/cwl/salad#SpecializeDef", "_container": "https://w3id.org/cwl/salad#JsonldPredicate/_container", "_id": { "@id": "https://w3id.org/cwl/salad#_id", "@type": "@id", "identity": True }, "_type": "https://w3id.org/cwl/salad#JsonldPredicate/_type", "abstract": "https://w3id.org/cwl/salad#SaladRecordSchema/abstract", "array": "https://w3id.org/cwl/salad#array", "boolean": "http://www.w3.org/2001/XMLSchema#boolean", "dct": "http://purl.org/dc/terms/", "default": { "@id": "https://w3id.org/cwl/salad#default", "noLinkCheck": True }, "doc": "rdfs:comment", "docAfter": { "@id": "https://w3id.org/cwl/salad#docAfter", "@type": "@id" }, "docChild": { "@id": "https://w3id.org/cwl/salad#docChild", "@type": "@id" }, "docParent": { "@id": "https://w3id.org/cwl/salad#docParent", "@type": "@id" }, "documentRoot": "https://w3id.org/cwl/salad#SchemaDefinedType/documentRoot", "documentation": "https://w3id.org/cwl/salad#documentation", "double": "http://www.w3.org/2001/XMLSchema#double", "enum": "https://w3id.org/cwl/salad#enum", "extends": { "@id": "https://w3id.org/cwl/salad#extends", "@type": "@id", "refScope": 1 }, "fields": { "@id": "https://w3id.org/cwl/salad#fields", "mapPredicate": "type", "mapSubject": "name" }, "float": "http://www.w3.org/2001/XMLSchema#float", "identity": "https://w3id.org/cwl/salad#JsonldPredicate/identity", "inVocab": "https://w3id.org/cwl/salad#NamedType/inVocab", "int": "http://www.w3.org/2001/XMLSchema#int", "items": { "@id": "https://w3id.org/cwl/salad#items", "@type": "@vocab", "refScope": 2 }, "jsonldPredicate": "sld:jsonldPredicate", "long": "http://www.w3.org/2001/XMLSchema#long", "mapPredicate": "https://w3id.org/cwl/salad#JsonldPredicate/mapPredicate", "mapSubject": "https://w3id.org/cwl/salad#JsonldPredicate/mapSubject", "name": "@id", "noLinkCheck": "https://w3id.org/cwl/salad#JsonldPredicate/noLinkCheck", "null": "https://w3id.org/cwl/salad#null", "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdfs": "http://www.w3.org/2000/01/rdf-schema#", "record": "https://w3id.org/cwl/salad#record", "refScope": "https://w3id.org/cwl/salad#JsonldPredicate/refScope", "sld": "https://w3id.org/cwl/salad#", "specialize": { "@id": "https://w3id.org/cwl/salad#specialize", "mapPredicate": "specializeTo", "mapSubject": "specializeFrom" }, "specializeFrom": { "@id": "https://w3id.org/cwl/salad#specializeFrom", "@type": "@id", "refScope": 1 }, "specializeTo": { "@id": "https://w3id.org/cwl/salad#specializeTo", "@type": "@id", "refScope": 1 }, "string": "http://www.w3.org/2001/XMLSchema#string", "subscope": "https://w3id.org/cwl/salad#JsonldPredicate/subscope", "symbols": { "@id": "https://w3id.org/cwl/salad#symbols", "@type": "@id", "identity": True }, "type": { "@id": "https://w3id.org/cwl/salad#type", "@type": "@vocab", "refScope": 2, "typeDSL": True }, "typeDSL": "https://w3id.org/cwl/salad#JsonldPredicate/typeDSL", "xsd": "http://www.w3.org/2001/XMLSchema#" }) for salad in SALAD_FILES: with resource_stream(__name__, 'metaschema/' + salad) as stream: loader.cache["https://w3id.org/cwl/" + salad] = stream.read() with resource_stream(__name__, 'metaschema/metaschema.yml') as stream: loader.cache["https://w3id.org/cwl/salad"] = stream.read() j = yaml.round_trip_load(loader.cache["https://w3id.org/cwl/salad"]) add_lc_filename(j, "metaschema.yml") j, _ = loader.resolve_all(j, "https://w3id.org/cwl/salad#") sch_obj = make_avro(j, loader) try: sch_names = make_avro_schema_from_avro(sch_obj) except SchemaParseException: _logger.error("Metaschema error, avro was:\n%s", json_dumps(sch_obj, indent=4)) raise validate_doc(sch_names, j, loader, strict=True) return (sch_names, j, loader)
[ "def", "get_metaschema", "(", ")", ":", "# type: () -> Tuple[Names, List[Dict[Text, Any]], Loader]", "loader", "=", "ref_resolver", ".", "Loader", "(", "{", "\"Any\"", ":", "\"https://w3id.org/cwl/salad#Any\"", ",", "\"ArraySchema\"", ":", "\"https://w3id.org/cwl/salad#ArraySchema\"", ",", "\"Array_symbol\"", ":", "\"https://w3id.org/cwl/salad#ArraySchema/type/Array_symbol\"", ",", "\"DocType\"", ":", "\"https://w3id.org/cwl/salad#DocType\"", ",", "\"Documentation\"", ":", "\"https://w3id.org/cwl/salad#Documentation\"", ",", "\"Documentation_symbol\"", ":", "\"https://w3id.org/cwl/salad#Documentation/type/Documentation_symbol\"", ",", "\"Documented\"", ":", "\"https://w3id.org/cwl/salad#Documented\"", ",", "\"EnumSchema\"", ":", "\"https://w3id.org/cwl/salad#EnumSchema\"", ",", "\"Enum_symbol\"", ":", "\"https://w3id.org/cwl/salad#EnumSchema/type/Enum_symbol\"", ",", "\"JsonldPredicate\"", ":", "\"https://w3id.org/cwl/salad#JsonldPredicate\"", ",", "\"NamedType\"", ":", "\"https://w3id.org/cwl/salad#NamedType\"", ",", "\"PrimitiveType\"", ":", "\"https://w3id.org/cwl/salad#PrimitiveType\"", ",", "\"RecordField\"", ":", "\"https://w3id.org/cwl/salad#RecordField\"", ",", "\"RecordSchema\"", ":", "\"https://w3id.org/cwl/salad#RecordSchema\"", ",", "\"Record_symbol\"", ":", "\"https://w3id.org/cwl/salad#RecordSchema/type/Record_symbol\"", ",", "\"SaladEnumSchema\"", ":", "\"https://w3id.org/cwl/salad#SaladEnumSchema\"", ",", "\"SaladRecordField\"", ":", "\"https://w3id.org/cwl/salad#SaladRecordField\"", ",", "\"SaladRecordSchema\"", ":", "\"https://w3id.org/cwl/salad#SaladRecordSchema\"", ",", "\"SchemaDefinedType\"", ":", "\"https://w3id.org/cwl/salad#SchemaDefinedType\"", ",", "\"SpecializeDef\"", ":", "\"https://w3id.org/cwl/salad#SpecializeDef\"", ",", "\"_container\"", ":", "\"https://w3id.org/cwl/salad#JsonldPredicate/_container\"", ",", "\"_id\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#_id\"", ",", "\"@type\"", ":", "\"@id\"", ",", "\"identity\"", ":", "True", "}", ",", "\"_type\"", ":", "\"https://w3id.org/cwl/salad#JsonldPredicate/_type\"", ",", "\"abstract\"", ":", "\"https://w3id.org/cwl/salad#SaladRecordSchema/abstract\"", ",", "\"array\"", ":", "\"https://w3id.org/cwl/salad#array\"", ",", "\"boolean\"", ":", "\"http://www.w3.org/2001/XMLSchema#boolean\"", ",", "\"dct\"", ":", "\"http://purl.org/dc/terms/\"", ",", "\"default\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#default\"", ",", "\"noLinkCheck\"", ":", "True", "}", ",", "\"doc\"", ":", "\"rdfs:comment\"", ",", "\"docAfter\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#docAfter\"", ",", "\"@type\"", ":", "\"@id\"", "}", ",", "\"docChild\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#docChild\"", ",", "\"@type\"", ":", "\"@id\"", "}", ",", "\"docParent\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#docParent\"", ",", "\"@type\"", ":", "\"@id\"", "}", ",", "\"documentRoot\"", ":", "\"https://w3id.org/cwl/salad#SchemaDefinedType/documentRoot\"", ",", "\"documentation\"", ":", "\"https://w3id.org/cwl/salad#documentation\"", ",", "\"double\"", ":", "\"http://www.w3.org/2001/XMLSchema#double\"", ",", "\"enum\"", ":", "\"https://w3id.org/cwl/salad#enum\"", ",", "\"extends\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#extends\"", ",", "\"@type\"", ":", "\"@id\"", ",", "\"refScope\"", ":", "1", "}", ",", "\"fields\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#fields\"", ",", "\"mapPredicate\"", ":", "\"type\"", ",", "\"mapSubject\"", ":", "\"name\"", "}", ",", "\"float\"", ":", "\"http://www.w3.org/2001/XMLSchema#float\"", ",", "\"identity\"", ":", "\"https://w3id.org/cwl/salad#JsonldPredicate/identity\"", ",", "\"inVocab\"", ":", "\"https://w3id.org/cwl/salad#NamedType/inVocab\"", ",", "\"int\"", ":", "\"http://www.w3.org/2001/XMLSchema#int\"", ",", "\"items\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#items\"", ",", "\"@type\"", ":", "\"@vocab\"", ",", "\"refScope\"", ":", "2", "}", ",", "\"jsonldPredicate\"", ":", "\"sld:jsonldPredicate\"", ",", "\"long\"", ":", "\"http://www.w3.org/2001/XMLSchema#long\"", ",", "\"mapPredicate\"", ":", "\"https://w3id.org/cwl/salad#JsonldPredicate/mapPredicate\"", ",", "\"mapSubject\"", ":", "\"https://w3id.org/cwl/salad#JsonldPredicate/mapSubject\"", ",", "\"name\"", ":", "\"@id\"", ",", "\"noLinkCheck\"", ":", "\"https://w3id.org/cwl/salad#JsonldPredicate/noLinkCheck\"", ",", "\"null\"", ":", "\"https://w3id.org/cwl/salad#null\"", ",", "\"rdf\"", ":", "\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"", ",", "\"rdfs\"", ":", "\"http://www.w3.org/2000/01/rdf-schema#\"", ",", "\"record\"", ":", "\"https://w3id.org/cwl/salad#record\"", ",", "\"refScope\"", ":", "\"https://w3id.org/cwl/salad#JsonldPredicate/refScope\"", ",", "\"sld\"", ":", "\"https://w3id.org/cwl/salad#\"", ",", "\"specialize\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#specialize\"", ",", "\"mapPredicate\"", ":", "\"specializeTo\"", ",", "\"mapSubject\"", ":", "\"specializeFrom\"", "}", ",", "\"specializeFrom\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#specializeFrom\"", ",", "\"@type\"", ":", "\"@id\"", ",", "\"refScope\"", ":", "1", "}", ",", "\"specializeTo\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#specializeTo\"", ",", "\"@type\"", ":", "\"@id\"", ",", "\"refScope\"", ":", "1", "}", ",", "\"string\"", ":", "\"http://www.w3.org/2001/XMLSchema#string\"", ",", "\"subscope\"", ":", "\"https://w3id.org/cwl/salad#JsonldPredicate/subscope\"", ",", "\"symbols\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#symbols\"", ",", "\"@type\"", ":", "\"@id\"", ",", "\"identity\"", ":", "True", "}", ",", "\"type\"", ":", "{", "\"@id\"", ":", "\"https://w3id.org/cwl/salad#type\"", ",", "\"@type\"", ":", "\"@vocab\"", ",", "\"refScope\"", ":", "2", ",", "\"typeDSL\"", ":", "True", "}", ",", "\"typeDSL\"", ":", "\"https://w3id.org/cwl/salad#JsonldPredicate/typeDSL\"", ",", "\"xsd\"", ":", "\"http://www.w3.org/2001/XMLSchema#\"", "}", ")", "for", "salad", "in", "SALAD_FILES", ":", "with", "resource_stream", "(", "__name__", ",", "'metaschema/'", "+", "salad", ")", "as", "stream", ":", "loader", ".", "cache", "[", "\"https://w3id.org/cwl/\"", "+", "salad", "]", "=", "stream", ".", "read", "(", ")", "with", "resource_stream", "(", "__name__", ",", "'metaschema/metaschema.yml'", ")", "as", "stream", ":", "loader", ".", "cache", "[", "\"https://w3id.org/cwl/salad\"", "]", "=", "stream", ".", "read", "(", ")", "j", "=", "yaml", ".", "round_trip_load", "(", "loader", ".", "cache", "[", "\"https://w3id.org/cwl/salad\"", "]", ")", "add_lc_filename", "(", "j", ",", "\"metaschema.yml\"", ")", "j", ",", "_", "=", "loader", ".", "resolve_all", "(", "j", ",", "\"https://w3id.org/cwl/salad#\"", ")", "sch_obj", "=", "make_avro", "(", "j", ",", "loader", ")", "try", ":", "sch_names", "=", "make_avro_schema_from_avro", "(", "sch_obj", ")", "except", "SchemaParseException", ":", "_logger", ".", "error", "(", "\"Metaschema error, avro was:\\n%s\"", ",", "json_dumps", "(", "sch_obj", ",", "indent", "=", "4", ")", ")", "raise", "validate_doc", "(", "sch_names", ",", "j", ",", "loader", ",", "strict", "=", "True", ")", "return", "(", "sch_names", ",", "j", ",", "loader", ")" ]
Instantiate the metaschema.
[ "Instantiate", "the", "metaschema", "." ]
608ba207b9058fe0a9c3db161058ab3782eef015
https://github.com/common-workflow-language/schema_salad/blob/608ba207b9058fe0a9c3db161058ab3782eef015/schema_salad/schema.py#L56-L194
train
common-workflow-language/schema_salad
schema_salad/schema.py
add_namespaces
def add_namespaces(metadata, namespaces): # type: (Mapping[Text, Any], MutableMapping[Text, Text]) -> None """Collect the provided namespaces, checking for conflicts.""" for key, value in metadata.items(): if key not in namespaces: namespaces[key] = value elif namespaces[key] != value: raise validate.ValidationException( "Namespace prefix '{}' has conflicting definitions '{}'" " and '{}'.".format(key, namespaces[key], value))
python
def add_namespaces(metadata, namespaces): # type: (Mapping[Text, Any], MutableMapping[Text, Text]) -> None """Collect the provided namespaces, checking for conflicts.""" for key, value in metadata.items(): if key not in namespaces: namespaces[key] = value elif namespaces[key] != value: raise validate.ValidationException( "Namespace prefix '{}' has conflicting definitions '{}'" " and '{}'.".format(key, namespaces[key], value))
[ "def", "add_namespaces", "(", "metadata", ",", "namespaces", ")", ":", "# type: (Mapping[Text, Any], MutableMapping[Text, Text]) -> None", "for", "key", ",", "value", "in", "metadata", ".", "items", "(", ")", ":", "if", "key", "not", "in", "namespaces", ":", "namespaces", "[", "key", "]", "=", "value", "elif", "namespaces", "[", "key", "]", "!=", "value", ":", "raise", "validate", ".", "ValidationException", "(", "\"Namespace prefix '{}' has conflicting definitions '{}'\"", "\" and '{}'.\"", ".", "format", "(", "key", ",", "namespaces", "[", "key", "]", ",", "value", ")", ")" ]
Collect the provided namespaces, checking for conflicts.
[ "Collect", "the", "provided", "namespaces", "checking", "for", "conflicts", "." ]
608ba207b9058fe0a9c3db161058ab3782eef015
https://github.com/common-workflow-language/schema_salad/blob/608ba207b9058fe0a9c3db161058ab3782eef015/schema_salad/schema.py#L196-L205
train
common-workflow-language/schema_salad
schema_salad/schema.py
collect_namespaces
def collect_namespaces(metadata): # type: (Mapping[Text, Any]) -> Dict[Text, Text] """Walk through the metadata object, collecting namespace declarations.""" namespaces = {} # type: Dict[Text, Text] if "$import_metadata" in metadata: for value in metadata["$import_metadata"].values(): add_namespaces(collect_namespaces(value), namespaces) if "$namespaces" in metadata: add_namespaces(metadata["$namespaces"], namespaces) return namespaces
python
def collect_namespaces(metadata): # type: (Mapping[Text, Any]) -> Dict[Text, Text] """Walk through the metadata object, collecting namespace declarations.""" namespaces = {} # type: Dict[Text, Text] if "$import_metadata" in metadata: for value in metadata["$import_metadata"].values(): add_namespaces(collect_namespaces(value), namespaces) if "$namespaces" in metadata: add_namespaces(metadata["$namespaces"], namespaces) return namespaces
[ "def", "collect_namespaces", "(", "metadata", ")", ":", "# type: (Mapping[Text, Any]) -> Dict[Text, Text]", "namespaces", "=", "{", "}", "# type: Dict[Text, Text]", "if", "\"$import_metadata\"", "in", "metadata", ":", "for", "value", "in", "metadata", "[", "\"$import_metadata\"", "]", ".", "values", "(", ")", ":", "add_namespaces", "(", "collect_namespaces", "(", "value", ")", ",", "namespaces", ")", "if", "\"$namespaces\"", "in", "metadata", ":", "add_namespaces", "(", "metadata", "[", "\"$namespaces\"", "]", ",", "namespaces", ")", "return", "namespaces" ]
Walk through the metadata object, collecting namespace declarations.
[ "Walk", "through", "the", "metadata", "object", "collecting", "namespace", "declarations", "." ]
608ba207b9058fe0a9c3db161058ab3782eef015
https://github.com/common-workflow-language/schema_salad/blob/608ba207b9058fe0a9c3db161058ab3782eef015/schema_salad/schema.py#L208-L217
train
common-workflow-language/schema_salad
schema_salad/schema.py
load_schema
def load_schema(schema_ref, # type: Union[CommentedMap, CommentedSeq, Text] cache=None # type: Dict ): # type: (...) -> Tuple[Loader, Union[Names, SchemaParseException], Dict[Text, Any], Loader] """ Load a schema that can be used to validate documents using load_and_validate. return: document_loader, avsc_names, schema_metadata, metaschema_loader """ metaschema_names, _metaschema_doc, metaschema_loader = get_metaschema() if cache is not None: metaschema_loader.cache.update(cache) schema_doc, schema_metadata = metaschema_loader.resolve_ref(schema_ref, "") if not isinstance(schema_doc, MutableSequence): raise ValueError("Schema reference must resolve to a list.") validate_doc(metaschema_names, schema_doc, metaschema_loader, True) metactx = schema_metadata.get("@context", {}) metactx.update(collect_namespaces(schema_metadata)) schema_ctx = jsonld_context.salad_to_jsonld_context(schema_doc, metactx)[0] # Create the loader that will be used to load the target document. document_loader = Loader(schema_ctx, cache=cache) # Make the Avro validation that will be used to validate the target # document avsc_names = make_avro_schema(schema_doc, document_loader) return document_loader, avsc_names, schema_metadata, metaschema_loader
python
def load_schema(schema_ref, # type: Union[CommentedMap, CommentedSeq, Text] cache=None # type: Dict ): # type: (...) -> Tuple[Loader, Union[Names, SchemaParseException], Dict[Text, Any], Loader] """ Load a schema that can be used to validate documents using load_and_validate. return: document_loader, avsc_names, schema_metadata, metaschema_loader """ metaschema_names, _metaschema_doc, metaschema_loader = get_metaschema() if cache is not None: metaschema_loader.cache.update(cache) schema_doc, schema_metadata = metaschema_loader.resolve_ref(schema_ref, "") if not isinstance(schema_doc, MutableSequence): raise ValueError("Schema reference must resolve to a list.") validate_doc(metaschema_names, schema_doc, metaschema_loader, True) metactx = schema_metadata.get("@context", {}) metactx.update(collect_namespaces(schema_metadata)) schema_ctx = jsonld_context.salad_to_jsonld_context(schema_doc, metactx)[0] # Create the loader that will be used to load the target document. document_loader = Loader(schema_ctx, cache=cache) # Make the Avro validation that will be used to validate the target # document avsc_names = make_avro_schema(schema_doc, document_loader) return document_loader, avsc_names, schema_metadata, metaschema_loader
[ "def", "load_schema", "(", "schema_ref", ",", "# type: Union[CommentedMap, CommentedSeq, Text]", "cache", "=", "None", "# type: Dict", ")", ":", "# type: (...) -> Tuple[Loader, Union[Names, SchemaParseException], Dict[Text, Any], Loader]", "metaschema_names", ",", "_metaschema_doc", ",", "metaschema_loader", "=", "get_metaschema", "(", ")", "if", "cache", "is", "not", "None", ":", "metaschema_loader", ".", "cache", ".", "update", "(", "cache", ")", "schema_doc", ",", "schema_metadata", "=", "metaschema_loader", ".", "resolve_ref", "(", "schema_ref", ",", "\"\"", ")", "if", "not", "isinstance", "(", "schema_doc", ",", "MutableSequence", ")", ":", "raise", "ValueError", "(", "\"Schema reference must resolve to a list.\"", ")", "validate_doc", "(", "metaschema_names", ",", "schema_doc", ",", "metaschema_loader", ",", "True", ")", "metactx", "=", "schema_metadata", ".", "get", "(", "\"@context\"", ",", "{", "}", ")", "metactx", ".", "update", "(", "collect_namespaces", "(", "schema_metadata", ")", ")", "schema_ctx", "=", "jsonld_context", ".", "salad_to_jsonld_context", "(", "schema_doc", ",", "metactx", ")", "[", "0", "]", "# Create the loader that will be used to load the target document.", "document_loader", "=", "Loader", "(", "schema_ctx", ",", "cache", "=", "cache", ")", "# Make the Avro validation that will be used to validate the target", "# document", "avsc_names", "=", "make_avro_schema", "(", "schema_doc", ",", "document_loader", ")", "return", "document_loader", ",", "avsc_names", ",", "schema_metadata", ",", "metaschema_loader" ]
Load a schema that can be used to validate documents using load_and_validate. return: document_loader, avsc_names, schema_metadata, metaschema_loader
[ "Load", "a", "schema", "that", "can", "be", "used", "to", "validate", "documents", "using", "load_and_validate", "." ]
608ba207b9058fe0a9c3db161058ab3782eef015
https://github.com/common-workflow-language/schema_salad/blob/608ba207b9058fe0a9c3db161058ab3782eef015/schema_salad/schema.py#L219-L249
train
common-workflow-language/schema_salad
schema_salad/schema.py
load_and_validate
def load_and_validate(document_loader, # type: Loader avsc_names, # type: Names document, # type: Union[CommentedMap, Text] strict, # type: bool strict_foreign_properties=False # type: bool ): # type: (...) -> Tuple[Any, Dict[Text, Any]] """Load a document and validate it with the provided schema. return data, metadata """ try: if isinstance(document, CommentedMap): data, metadata = document_loader.resolve_all( document, document["id"], checklinks=True, strict_foreign_properties=strict_foreign_properties) else: data, metadata = document_loader.resolve_ref( document, checklinks=True, strict_foreign_properties=strict_foreign_properties) validate_doc(avsc_names, data, document_loader, strict, strict_foreign_properties=strict_foreign_properties) return data, metadata except validate.ValidationException as exc: raise validate.ValidationException(strip_dup_lineno(str(exc)))
python
def load_and_validate(document_loader, # type: Loader avsc_names, # type: Names document, # type: Union[CommentedMap, Text] strict, # type: bool strict_foreign_properties=False # type: bool ): # type: (...) -> Tuple[Any, Dict[Text, Any]] """Load a document and validate it with the provided schema. return data, metadata """ try: if isinstance(document, CommentedMap): data, metadata = document_loader.resolve_all( document, document["id"], checklinks=True, strict_foreign_properties=strict_foreign_properties) else: data, metadata = document_loader.resolve_ref( document, checklinks=True, strict_foreign_properties=strict_foreign_properties) validate_doc(avsc_names, data, document_loader, strict, strict_foreign_properties=strict_foreign_properties) return data, metadata except validate.ValidationException as exc: raise validate.ValidationException(strip_dup_lineno(str(exc)))
[ "def", "load_and_validate", "(", "document_loader", ",", "# type: Loader", "avsc_names", ",", "# type: Names", "document", ",", "# type: Union[CommentedMap, Text]", "strict", ",", "# type: bool", "strict_foreign_properties", "=", "False", "# type: bool", ")", ":", "# type: (...) -> Tuple[Any, Dict[Text, Any]]", "try", ":", "if", "isinstance", "(", "document", ",", "CommentedMap", ")", ":", "data", ",", "metadata", "=", "document_loader", ".", "resolve_all", "(", "document", ",", "document", "[", "\"id\"", "]", ",", "checklinks", "=", "True", ",", "strict_foreign_properties", "=", "strict_foreign_properties", ")", "else", ":", "data", ",", "metadata", "=", "document_loader", ".", "resolve_ref", "(", "document", ",", "checklinks", "=", "True", ",", "strict_foreign_properties", "=", "strict_foreign_properties", ")", "validate_doc", "(", "avsc_names", ",", "data", ",", "document_loader", ",", "strict", ",", "strict_foreign_properties", "=", "strict_foreign_properties", ")", "return", "data", ",", "metadata", "except", "validate", ".", "ValidationException", "as", "exc", ":", "raise", "validate", ".", "ValidationException", "(", "strip_dup_lineno", "(", "str", "(", "exc", ")", ")", ")" ]
Load a document and validate it with the provided schema. return data, metadata
[ "Load", "a", "document", "and", "validate", "it", "with", "the", "provided", "schema", "." ]
608ba207b9058fe0a9c3db161058ab3782eef015
https://github.com/common-workflow-language/schema_salad/blob/608ba207b9058fe0a9c3db161058ab3782eef015/schema_salad/schema.py#L252-L278
train
common-workflow-language/schema_salad
schema_salad/schema.py
validate_doc
def validate_doc(schema_names, # type: Names doc, # type: Union[Dict[Text, Any], List[Dict[Text, Any]], Text, None] loader, # type: Loader strict, # type: bool strict_foreign_properties=False # type: bool ): # type: (...) -> None """Validate a document using the provided schema.""" has_root = False for root in schema_names.names.values(): if ((hasattr(root, 'get_prop') and root.get_prop(u"documentRoot")) or ( u"documentRoot" in root.props)): has_root = True break if not has_root: raise validate.ValidationException( "No document roots defined in the schema") if isinstance(doc, MutableSequence): vdoc = doc elif isinstance(doc, CommentedMap): vdoc = CommentedSeq([doc]) vdoc.lc.add_kv_line_col(0, [doc.lc.line, doc.lc.col]) vdoc.lc.filename = doc.lc.filename else: raise validate.ValidationException("Document must be dict or list") roots = [] for root in schema_names.names.values(): if ((hasattr(root, "get_prop") and root.get_prop(u"documentRoot")) or ( root.props.get(u"documentRoot"))): roots.append(root) anyerrors = [] for pos, item in enumerate(vdoc): sourceline = SourceLine(vdoc, pos, Text) success = False for root in roots: success = validate.validate_ex( root, item, loader.identifiers, strict, foreign_properties=loader.foreign_properties, raise_ex=False, skip_foreign_properties=loader.skip_schemas, strict_foreign_properties=strict_foreign_properties) if success: break if not success: errors = [] # type: List[Text] for root in roots: if hasattr(root, "get_prop"): name = root.get_prop(u"name") elif hasattr(root, "name"): name = root.name try: validate.validate_ex( root, item, loader.identifiers, strict, foreign_properties=loader.foreign_properties, raise_ex=True, skip_foreign_properties=loader.skip_schemas, strict_foreign_properties=strict_foreign_properties) except validate.ClassValidationException as exc: errors = [sourceline.makeError(u"tried `%s` but\n%s" % ( name, validate.indent(str(exc), nolead=False)))] break except validate.ValidationException as exc: errors.append(sourceline.makeError(u"tried `%s` but\n%s" % ( name, validate.indent(str(exc), nolead=False)))) objerr = sourceline.makeError(u"Invalid") for ident in loader.identifiers: if ident in item: objerr = sourceline.makeError( u"Object `%s` is not valid because" % (relname(item[ident]))) break anyerrors.append(u"%s\n%s" % (objerr, validate.indent(bullets(errors, "- ")))) if anyerrors: raise validate.ValidationException( strip_dup_lineno(bullets(anyerrors, "* ")))
python
def validate_doc(schema_names, # type: Names doc, # type: Union[Dict[Text, Any], List[Dict[Text, Any]], Text, None] loader, # type: Loader strict, # type: bool strict_foreign_properties=False # type: bool ): # type: (...) -> None """Validate a document using the provided schema.""" has_root = False for root in schema_names.names.values(): if ((hasattr(root, 'get_prop') and root.get_prop(u"documentRoot")) or ( u"documentRoot" in root.props)): has_root = True break if not has_root: raise validate.ValidationException( "No document roots defined in the schema") if isinstance(doc, MutableSequence): vdoc = doc elif isinstance(doc, CommentedMap): vdoc = CommentedSeq([doc]) vdoc.lc.add_kv_line_col(0, [doc.lc.line, doc.lc.col]) vdoc.lc.filename = doc.lc.filename else: raise validate.ValidationException("Document must be dict or list") roots = [] for root in schema_names.names.values(): if ((hasattr(root, "get_prop") and root.get_prop(u"documentRoot")) or ( root.props.get(u"documentRoot"))): roots.append(root) anyerrors = [] for pos, item in enumerate(vdoc): sourceline = SourceLine(vdoc, pos, Text) success = False for root in roots: success = validate.validate_ex( root, item, loader.identifiers, strict, foreign_properties=loader.foreign_properties, raise_ex=False, skip_foreign_properties=loader.skip_schemas, strict_foreign_properties=strict_foreign_properties) if success: break if not success: errors = [] # type: List[Text] for root in roots: if hasattr(root, "get_prop"): name = root.get_prop(u"name") elif hasattr(root, "name"): name = root.name try: validate.validate_ex( root, item, loader.identifiers, strict, foreign_properties=loader.foreign_properties, raise_ex=True, skip_foreign_properties=loader.skip_schemas, strict_foreign_properties=strict_foreign_properties) except validate.ClassValidationException as exc: errors = [sourceline.makeError(u"tried `%s` but\n%s" % ( name, validate.indent(str(exc), nolead=False)))] break except validate.ValidationException as exc: errors.append(sourceline.makeError(u"tried `%s` but\n%s" % ( name, validate.indent(str(exc), nolead=False)))) objerr = sourceline.makeError(u"Invalid") for ident in loader.identifiers: if ident in item: objerr = sourceline.makeError( u"Object `%s` is not valid because" % (relname(item[ident]))) break anyerrors.append(u"%s\n%s" % (objerr, validate.indent(bullets(errors, "- ")))) if anyerrors: raise validate.ValidationException( strip_dup_lineno(bullets(anyerrors, "* ")))
[ "def", "validate_doc", "(", "schema_names", ",", "# type: Names", "doc", ",", "# type: Union[Dict[Text, Any], List[Dict[Text, Any]], Text, None]", "loader", ",", "# type: Loader", "strict", ",", "# type: bool", "strict_foreign_properties", "=", "False", "# type: bool", ")", ":", "# type: (...) -> None", "has_root", "=", "False", "for", "root", "in", "schema_names", ".", "names", ".", "values", "(", ")", ":", "if", "(", "(", "hasattr", "(", "root", ",", "'get_prop'", ")", "and", "root", ".", "get_prop", "(", "u\"documentRoot\"", ")", ")", "or", "(", "u\"documentRoot\"", "in", "root", ".", "props", ")", ")", ":", "has_root", "=", "True", "break", "if", "not", "has_root", ":", "raise", "validate", ".", "ValidationException", "(", "\"No document roots defined in the schema\"", ")", "if", "isinstance", "(", "doc", ",", "MutableSequence", ")", ":", "vdoc", "=", "doc", "elif", "isinstance", "(", "doc", ",", "CommentedMap", ")", ":", "vdoc", "=", "CommentedSeq", "(", "[", "doc", "]", ")", "vdoc", ".", "lc", ".", "add_kv_line_col", "(", "0", ",", "[", "doc", ".", "lc", ".", "line", ",", "doc", ".", "lc", ".", "col", "]", ")", "vdoc", ".", "lc", ".", "filename", "=", "doc", ".", "lc", ".", "filename", "else", ":", "raise", "validate", ".", "ValidationException", "(", "\"Document must be dict or list\"", ")", "roots", "=", "[", "]", "for", "root", "in", "schema_names", ".", "names", ".", "values", "(", ")", ":", "if", "(", "(", "hasattr", "(", "root", ",", "\"get_prop\"", ")", "and", "root", ".", "get_prop", "(", "u\"documentRoot\"", ")", ")", "or", "(", "root", ".", "props", ".", "get", "(", "u\"documentRoot\"", ")", ")", ")", ":", "roots", ".", "append", "(", "root", ")", "anyerrors", "=", "[", "]", "for", "pos", ",", "item", "in", "enumerate", "(", "vdoc", ")", ":", "sourceline", "=", "SourceLine", "(", "vdoc", ",", "pos", ",", "Text", ")", "success", "=", "False", "for", "root", "in", "roots", ":", "success", "=", "validate", ".", "validate_ex", "(", "root", ",", "item", ",", "loader", ".", "identifiers", ",", "strict", ",", "foreign_properties", "=", "loader", ".", "foreign_properties", ",", "raise_ex", "=", "False", ",", "skip_foreign_properties", "=", "loader", ".", "skip_schemas", ",", "strict_foreign_properties", "=", "strict_foreign_properties", ")", "if", "success", ":", "break", "if", "not", "success", ":", "errors", "=", "[", "]", "# type: List[Text]", "for", "root", "in", "roots", ":", "if", "hasattr", "(", "root", ",", "\"get_prop\"", ")", ":", "name", "=", "root", ".", "get_prop", "(", "u\"name\"", ")", "elif", "hasattr", "(", "root", ",", "\"name\"", ")", ":", "name", "=", "root", ".", "name", "try", ":", "validate", ".", "validate_ex", "(", "root", ",", "item", ",", "loader", ".", "identifiers", ",", "strict", ",", "foreign_properties", "=", "loader", ".", "foreign_properties", ",", "raise_ex", "=", "True", ",", "skip_foreign_properties", "=", "loader", ".", "skip_schemas", ",", "strict_foreign_properties", "=", "strict_foreign_properties", ")", "except", "validate", ".", "ClassValidationException", "as", "exc", ":", "errors", "=", "[", "sourceline", ".", "makeError", "(", "u\"tried `%s` but\\n%s\"", "%", "(", "name", ",", "validate", ".", "indent", "(", "str", "(", "exc", ")", ",", "nolead", "=", "False", ")", ")", ")", "]", "break", "except", "validate", ".", "ValidationException", "as", "exc", ":", "errors", ".", "append", "(", "sourceline", ".", "makeError", "(", "u\"tried `%s` but\\n%s\"", "%", "(", "name", ",", "validate", ".", "indent", "(", "str", "(", "exc", ")", ",", "nolead", "=", "False", ")", ")", ")", ")", "objerr", "=", "sourceline", ".", "makeError", "(", "u\"Invalid\"", ")", "for", "ident", "in", "loader", ".", "identifiers", ":", "if", "ident", "in", "item", ":", "objerr", "=", "sourceline", ".", "makeError", "(", "u\"Object `%s` is not valid because\"", "%", "(", "relname", "(", "item", "[", "ident", "]", ")", ")", ")", "break", "anyerrors", ".", "append", "(", "u\"%s\\n%s\"", "%", "(", "objerr", ",", "validate", ".", "indent", "(", "bullets", "(", "errors", ",", "\"- \"", ")", ")", ")", ")", "if", "anyerrors", ":", "raise", "validate", ".", "ValidationException", "(", "strip_dup_lineno", "(", "bullets", "(", "anyerrors", ",", "\"* \"", ")", ")", ")" ]
Validate a document using the provided schema.
[ "Validate", "a", "document", "using", "the", "provided", "schema", "." ]
608ba207b9058fe0a9c3db161058ab3782eef015
https://github.com/common-workflow-language/schema_salad/blob/608ba207b9058fe0a9c3db161058ab3782eef015/schema_salad/schema.py#L281-L361
train
common-workflow-language/schema_salad
schema_salad/schema.py
get_anon_name
def get_anon_name(rec): # type: (MutableMapping[Text, Any]) -> Text """Calculate a reproducible name for anonymous types.""" if "name" in rec: return rec["name"] anon_name = "" if rec['type'] in ('enum', 'https://w3id.org/cwl/salad#enum'): for sym in rec["symbols"]: anon_name += sym return "enum_"+hashlib.sha1(anon_name.encode("UTF-8")).hexdigest() if rec['type'] in ('record', 'https://w3id.org/cwl/salad#record'): for field in rec["fields"]: anon_name += field["name"] return "record_"+hashlib.sha1(anon_name.encode("UTF-8")).hexdigest() if rec['type'] in ('array', 'https://w3id.org/cwl/salad#array'): return "" raise validate.ValidationException("Expected enum or record, was %s" % rec['type'])
python
def get_anon_name(rec): # type: (MutableMapping[Text, Any]) -> Text """Calculate a reproducible name for anonymous types.""" if "name" in rec: return rec["name"] anon_name = "" if rec['type'] in ('enum', 'https://w3id.org/cwl/salad#enum'): for sym in rec["symbols"]: anon_name += sym return "enum_"+hashlib.sha1(anon_name.encode("UTF-8")).hexdigest() if rec['type'] in ('record', 'https://w3id.org/cwl/salad#record'): for field in rec["fields"]: anon_name += field["name"] return "record_"+hashlib.sha1(anon_name.encode("UTF-8")).hexdigest() if rec['type'] in ('array', 'https://w3id.org/cwl/salad#array'): return "" raise validate.ValidationException("Expected enum or record, was %s" % rec['type'])
[ "def", "get_anon_name", "(", "rec", ")", ":", "# type: (MutableMapping[Text, Any]) -> Text", "if", "\"name\"", "in", "rec", ":", "return", "rec", "[", "\"name\"", "]", "anon_name", "=", "\"\"", "if", "rec", "[", "'type'", "]", "in", "(", "'enum'", ",", "'https://w3id.org/cwl/salad#enum'", ")", ":", "for", "sym", "in", "rec", "[", "\"symbols\"", "]", ":", "anon_name", "+=", "sym", "return", "\"enum_\"", "+", "hashlib", ".", "sha1", "(", "anon_name", ".", "encode", "(", "\"UTF-8\"", ")", ")", ".", "hexdigest", "(", ")", "if", "rec", "[", "'type'", "]", "in", "(", "'record'", ",", "'https://w3id.org/cwl/salad#record'", ")", ":", "for", "field", "in", "rec", "[", "\"fields\"", "]", ":", "anon_name", "+=", "field", "[", "\"name\"", "]", "return", "\"record_\"", "+", "hashlib", ".", "sha1", "(", "anon_name", ".", "encode", "(", "\"UTF-8\"", ")", ")", ".", "hexdigest", "(", ")", "if", "rec", "[", "'type'", "]", "in", "(", "'array'", ",", "'https://w3id.org/cwl/salad#array'", ")", ":", "return", "\"\"", "raise", "validate", ".", "ValidationException", "(", "\"Expected enum or record, was %s\"", "%", "rec", "[", "'type'", "]", ")" ]
Calculate a reproducible name for anonymous types.
[ "Calculate", "a", "reproducible", "name", "for", "anonymous", "types", "." ]
608ba207b9058fe0a9c3db161058ab3782eef015
https://github.com/common-workflow-language/schema_salad/blob/608ba207b9058fe0a9c3db161058ab3782eef015/schema_salad/schema.py#L363-L379
train
common-workflow-language/schema_salad
schema_salad/schema.py
replace_type
def replace_type(items, spec, loader, found, find_embeds=True, deepen=True): # type: (Any, Dict[Text, Any], Loader, Set[Text], bool, bool) -> Any """ Go through and replace types in the 'spec' mapping""" if isinstance(items, MutableMapping): # recursively check these fields for types to replace if items.get("type") in ("record", "enum") and items.get("name"): if items["name"] in found: return items["name"] found.add(items["name"]) if not deepen: return items items = copy.copy(items) if not items.get("name"): items["name"] = get_anon_name(items) for name in ("type", "items", "fields"): if name in items: items[name] = replace_type( items[name], spec, loader, found, find_embeds=find_embeds, deepen=find_embeds) if isinstance(items[name], MutableSequence): items[name] = flatten(items[name]) return items if isinstance(items, MutableSequence): # recursively transform list return [replace_type(i, spec, loader, found, find_embeds=find_embeds, deepen=deepen) for i in items] if isinstance(items, string_types): # found a string which is a symbol corresponding to a type. replace_with = None if items in loader.vocab: # If it's a vocabulary term, first expand it to its fully qualified # URI items = loader.vocab[items] if items in spec: # Look up in specialization map replace_with = spec[items] if replace_with: return replace_type(replace_with, spec, loader, found, find_embeds=find_embeds) found.add(items) return items
python
def replace_type(items, spec, loader, found, find_embeds=True, deepen=True): # type: (Any, Dict[Text, Any], Loader, Set[Text], bool, bool) -> Any """ Go through and replace types in the 'spec' mapping""" if isinstance(items, MutableMapping): # recursively check these fields for types to replace if items.get("type") in ("record", "enum") and items.get("name"): if items["name"] in found: return items["name"] found.add(items["name"]) if not deepen: return items items = copy.copy(items) if not items.get("name"): items["name"] = get_anon_name(items) for name in ("type", "items", "fields"): if name in items: items[name] = replace_type( items[name], spec, loader, found, find_embeds=find_embeds, deepen=find_embeds) if isinstance(items[name], MutableSequence): items[name] = flatten(items[name]) return items if isinstance(items, MutableSequence): # recursively transform list return [replace_type(i, spec, loader, found, find_embeds=find_embeds, deepen=deepen) for i in items] if isinstance(items, string_types): # found a string which is a symbol corresponding to a type. replace_with = None if items in loader.vocab: # If it's a vocabulary term, first expand it to its fully qualified # URI items = loader.vocab[items] if items in spec: # Look up in specialization map replace_with = spec[items] if replace_with: return replace_type(replace_with, spec, loader, found, find_embeds=find_embeds) found.add(items) return items
[ "def", "replace_type", "(", "items", ",", "spec", ",", "loader", ",", "found", ",", "find_embeds", "=", "True", ",", "deepen", "=", "True", ")", ":", "# type: (Any, Dict[Text, Any], Loader, Set[Text], bool, bool) -> Any", "if", "isinstance", "(", "items", ",", "MutableMapping", ")", ":", "# recursively check these fields for types to replace", "if", "items", ".", "get", "(", "\"type\"", ")", "in", "(", "\"record\"", ",", "\"enum\"", ")", "and", "items", ".", "get", "(", "\"name\"", ")", ":", "if", "items", "[", "\"name\"", "]", "in", "found", ":", "return", "items", "[", "\"name\"", "]", "found", ".", "add", "(", "items", "[", "\"name\"", "]", ")", "if", "not", "deepen", ":", "return", "items", "items", "=", "copy", ".", "copy", "(", "items", ")", "if", "not", "items", ".", "get", "(", "\"name\"", ")", ":", "items", "[", "\"name\"", "]", "=", "get_anon_name", "(", "items", ")", "for", "name", "in", "(", "\"type\"", ",", "\"items\"", ",", "\"fields\"", ")", ":", "if", "name", "in", "items", ":", "items", "[", "name", "]", "=", "replace_type", "(", "items", "[", "name", "]", ",", "spec", ",", "loader", ",", "found", ",", "find_embeds", "=", "find_embeds", ",", "deepen", "=", "find_embeds", ")", "if", "isinstance", "(", "items", "[", "name", "]", ",", "MutableSequence", ")", ":", "items", "[", "name", "]", "=", "flatten", "(", "items", "[", "name", "]", ")", "return", "items", "if", "isinstance", "(", "items", ",", "MutableSequence", ")", ":", "# recursively transform list", "return", "[", "replace_type", "(", "i", ",", "spec", ",", "loader", ",", "found", ",", "find_embeds", "=", "find_embeds", ",", "deepen", "=", "deepen", ")", "for", "i", "in", "items", "]", "if", "isinstance", "(", "items", ",", "string_types", ")", ":", "# found a string which is a symbol corresponding to a type.", "replace_with", "=", "None", "if", "items", "in", "loader", ".", "vocab", ":", "# If it's a vocabulary term, first expand it to its fully qualified", "# URI", "items", "=", "loader", ".", "vocab", "[", "items", "]", "if", "items", "in", "spec", ":", "# Look up in specialization map", "replace_with", "=", "spec", "[", "items", "]", "if", "replace_with", ":", "return", "replace_type", "(", "replace_with", ",", "spec", ",", "loader", ",", "found", ",", "find_embeds", "=", "find_embeds", ")", "found", ".", "add", "(", "items", ")", "return", "items" ]
Go through and replace types in the 'spec' mapping
[ "Go", "through", "and", "replace", "types", "in", "the", "spec", "mapping" ]
608ba207b9058fe0a9c3db161058ab3782eef015
https://github.com/common-workflow-language/schema_salad/blob/608ba207b9058fe0a9c3db161058ab3782eef015/schema_salad/schema.py#L381-L426
train