repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
modified_created
def modified_created(instance): """`modified` property must be later or equal to `created` property """ if 'modified' in instance and 'created' in instance and \ instance['modified'] < instance['created']: msg = "'modified' (%s) must be later or equal to 'created' (%s)" return JS...
python
def modified_created(instance): """`modified` property must be later or equal to `created` property """ if 'modified' in instance and 'created' in instance and \ instance['modified'] < instance['created']: msg = "'modified' (%s) must be later or equal to 'created' (%s)" return JS...
[ "def", "modified_created", "(", "instance", ")", ":", "if", "'modified'", "in", "instance", "and", "'created'", "in", "instance", "and", "instance", "[", "'modified'", "]", "<", "instance", "[", "'created'", "]", ":", "msg", "=", "\"'modified' (%s) must be later...
`modified` property must be later or equal to `created` property
[ "modified", "property", "must", "be", "later", "or", "equal", "to", "created", "property" ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L73-L80
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
object_marking_circular_refs
def object_marking_circular_refs(instance): """Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `object_marking_refs` property). """ if instance['type'] != 'marking-definition': return if 'object_marking_refs' in instance: ...
python
def object_marking_circular_refs(instance): """Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `object_marking_refs` property). """ if instance['type'] != 'marking-definition': return if 'object_marking_refs' in instance: ...
[ "def", "object_marking_circular_refs", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'marking-definition'", ":", "return", "if", "'object_marking_refs'", "in", "instance", ":", "for", "ref", "in", "instance", "[", "'object_marking_refs'", ...
Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `object_marking_refs` property).
[ "Ensure", "that", "marking", "definitions", "do", "not", "contain", "circular", "references", "(", "ie", ".", "they", "do", "not", "reference", "themselves", "in", "the", "object_marking_refs", "property", ")", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L83-L95
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
granular_markings_circular_refs
def granular_markings_circular_refs(instance): """Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `granular_markings` property). """ if instance['type'] != 'marking-definition': return if 'granular_markings' in instance: ...
python
def granular_markings_circular_refs(instance): """Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `granular_markings` property). """ if instance['type'] != 'marking-definition': return if 'granular_markings' in instance: ...
[ "def", "granular_markings_circular_refs", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'marking-definition'", ":", "return", "if", "'granular_markings'", "in", "instance", ":", "for", "marking", "in", "instance", "[", "'granular_markings'"...
Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `granular_markings` property).
[ "Ensure", "that", "marking", "definitions", "do", "not", "contain", "circular", "references", "(", "ie", ".", "they", "do", "not", "reference", "themselves", "in", "the", "granular_markings", "property", ")", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L98-L110
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
marking_selector_syntax
def marking_selector_syntax(instance): """Ensure selectors in granular markings refer to items which are actually present in the object. """ if 'granular_markings' not in instance: return list_index_re = re.compile(r"\[(\d+)\]") for marking in instance['granular_markings']: if '...
python
def marking_selector_syntax(instance): """Ensure selectors in granular markings refer to items which are actually present in the object. """ if 'granular_markings' not in instance: return list_index_re = re.compile(r"\[(\d+)\]") for marking in instance['granular_markings']: if '...
[ "def", "marking_selector_syntax", "(", "instance", ")", ":", "if", "'granular_markings'", "not", "in", "instance", ":", "return", "list_index_re", "=", "re", ".", "compile", "(", "r\"\\[(\\d+)\\]\"", ")", "for", "marking", "in", "instance", "[", "'granular_marking...
Ensure selectors in granular markings refer to items which are actually present in the object.
[ "Ensure", "selectors", "in", "granular", "markings", "refer", "to", "items", "which", "are", "actually", "present", "in", "the", "object", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L113-L156
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
observable_object_references
def observable_object_references(instance): """Ensure certain observable object properties reference the correct type of object. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue elif obj['type'] not in enums.OBSERVABLE_PROP_REFS: con...
python
def observable_object_references(instance): """Ensure certain observable object properties reference the correct type of object. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue elif obj['type'] not in enums.OBSERVABLE_PROP_REFS: con...
[ "def", "observable_object_references", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "not", "in", "obj", ":", "continue", "elif", "obj", "[", "'type'", "]", "n...
Ensure certain observable object properties reference the correct type of object.
[ "Ensure", "certain", "observable", "object", "properties", "reference", "the", "correct", "type", "of", "object", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L191-L240
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
artifact_mime_type
def artifact_mime_type(instance): """Ensure the 'mime_type' property of artifact objects comes from the Template column in the IANA media type registry. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'artifact' and 'mime_type' in obj): if enums....
python
def artifact_mime_type(instance): """Ensure the 'mime_type' property of artifact objects comes from the Template column in the IANA media type registry. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'artifact' and 'mime_type' in obj): if enums....
[ "def", "artifact_mime_type", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'artifact'", "and", "'m...
Ensure the 'mime_type' property of artifact objects comes from the Template column in the IANA media type registry.
[ "Ensure", "the", "mime_type", "property", "of", "artifact", "objects", "comes", "from", "the", "Template", "column", "in", "the", "IANA", "media", "type", "registry", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L244-L265
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
character_set
def character_set(instance): """Ensure certain properties of cyber observable objects come from the IANA Character Set list. """ char_re = re.compile(r'^[a-zA-Z0-9_\(\)-]+$') for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'directory' and 'path_enc' in obj):...
python
def character_set(instance): """Ensure certain properties of cyber observable objects come from the IANA Character Set list. """ char_re = re.compile(r'^[a-zA-Z0-9_\(\)-]+$') for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'directory' and 'path_enc' in obj):...
[ "def", "character_set", "(", "instance", ")", ":", "char_re", "=", "re", ".", "compile", "(", "r'^[a-zA-Z0-9_\\(\\)-]+$'", ")", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "...
Ensure certain properties of cyber observable objects come from the IANA Character Set list.
[ "Ensure", "certain", "properties", "of", "cyber", "observable", "objects", "come", "from", "the", "IANA", "Character", "Set", "list", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L269-L303
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
software_language
def software_language(instance): """Ensure the 'language' property of software objects is a valid ISO 639-2 language code. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'software' and 'languages' in obj): for lang in obj['langua...
python
def software_language(instance): """Ensure the 'language' property of software objects is a valid ISO 639-2 language code. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'software' and 'languages' in obj): for lang in obj['langua...
[ "def", "software_language", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'software'", "and", "'la...
Ensure the 'language' property of software objects is a valid ISO 639-2 language code.
[ "Ensure", "the", "language", "property", "of", "software", "objects", "is", "a", "valid", "ISO", "639", "-", "2", "language", "code", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L307-L319
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
types_strict
def types_strict(instance): """Ensure that no custom object types are used, but only the official ones from the specification. """ if instance['type'] not in enums.TYPES: yield JSONError("Object type '%s' is not one of those defined in the" " specification." % instance['t...
python
def types_strict(instance): """Ensure that no custom object types are used, but only the official ones from the specification. """ if instance['type'] not in enums.TYPES: yield JSONError("Object type '%s' is not one of those defined in the" " specification." % instance['t...
[ "def", "types_strict", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "not", "in", "enums", ".", "TYPES", ":", "yield", "JSONError", "(", "\"Object type '%s' is not one of those defined in the\"", "\" specification.\"", "%", "instance", "[", "'type...
Ensure that no custom object types are used, but only the official ones from the specification.
[ "Ensure", "that", "no", "custom", "object", "types", "are", "used", "but", "only", "the", "official", "ones", "from", "the", "specification", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L322-L336
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
properties_strict
def properties_strict(instance): """Ensure that no custom properties are used, but only the official ones from the specification. """ if instance['type'] not in enums.TYPES: return # only check properties for official objects defined_props = enums.PROPERTIES.get(instance['type'], []) f...
python
def properties_strict(instance): """Ensure that no custom properties are used, but only the official ones from the specification. """ if instance['type'] not in enums.TYPES: return # only check properties for official objects defined_props = enums.PROPERTIES.get(instance['type'], []) f...
[ "def", "properties_strict", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "not", "in", "enums", ".", "TYPES", ":", "return", "# only check properties for official objects", "defined_props", "=", "enums", ".", "PROPERTIES", ".", "get", "(", "in...
Ensure that no custom properties are used, but only the official ones from the specification.
[ "Ensure", "that", "no", "custom", "properties", "are", "used", "but", "only", "the", "official", "ones", "from", "the", "specification", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L339-L396
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
patterns
def patterns(instance, options): """Ensure that the syntax of the pattern of an indicator is valid, and that objects and properties referenced by the pattern are valid. """ if instance['type'] != 'indicator' or 'pattern' not in instance: return pattern = instance['pattern'] if not isins...
python
def patterns(instance, options): """Ensure that the syntax of the pattern of an indicator is valid, and that objects and properties referenced by the pattern are valid. """ if instance['type'] != 'indicator' or 'pattern' not in instance: return pattern = instance['pattern'] if not isins...
[ "def", "patterns", "(", "instance", ",", "options", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'indicator'", "or", "'pattern'", "not", "in", "instance", ":", "return", "pattern", "=", "instance", "[", "'pattern'", "]", "if", "not", "isinstance"...
Ensure that the syntax of the pattern of an indicator is valid, and that objects and properties referenced by the pattern are valid.
[ "Ensure", "that", "the", "syntax", "of", "the", "pattern", "of", "an", "indicator", "is", "valid", "and", "that", "objects", "and", "properties", "referenced", "by", "the", "pattern", "are", "valid", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L399-L470
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
list_musts
def list_musts(options): """Construct the list of 'MUST' validators to be run by the validator. """ validator_list = [ timestamp, modified_created, object_marking_circular_refs, granular_markings_circular_refs, marking_selector_syntax, observable_object_refere...
python
def list_musts(options): """Construct the list of 'MUST' validators to be run by the validator. """ validator_list = [ timestamp, modified_created, object_marking_circular_refs, granular_markings_circular_refs, marking_selector_syntax, observable_object_refere...
[ "def", "list_musts", "(", "options", ")", ":", "validator_list", "=", "[", "timestamp", ",", "modified_created", ",", "object_marking_circular_refs", ",", "granular_markings_circular_refs", ",", "marking_selector_syntax", ",", "observable_object_references", ",", "artifact_...
Construct the list of 'MUST' validators to be run by the validator.
[ "Construct", "the", "list", "of", "MUST", "validators", "to", "be", "run", "by", "the", "validator", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L473-L497
oasis-open/cti-stix-validator
stix2validator/v21/enums.py
media_types
def media_types(): """Return a list of the IANA Media (MIME) Types, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(media_types, 'typelist'): tlist = [] categories = [ 'applicati...
python
def media_types(): """Return a list of the IANA Media (MIME) Types, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(media_types, 'typelist'): tlist = [] categories = [ 'applicati...
[ "def", "media_types", "(", ")", ":", "if", "not", "hasattr", "(", "media_types", ",", "'typelist'", ")", ":", "tlist", "=", "[", "]", "categories", "=", "[", "'application'", ",", "'audio'", ",", "'font'", ",", "'image'", ",", "'message'", ",", "'model'"...
Return a list of the IANA Media (MIME) Types, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once.
[ "Return", "a", "list", "of", "the", "IANA", "Media", "(", "MIME", ")", "Types", "or", "an", "empty", "list", "if", "the", "IANA", "website", "is", "unreachable", ".", "Store", "it", "as", "a", "function", "attribute", "so", "that", "we", "only", "build...
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/enums.py#L1618-L1656
oasis-open/cti-stix-validator
stix2validator/v21/enums.py
char_sets
def char_sets(): """Return a list of the IANA Character Sets, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(char_sets, 'setlist'): clist = [] try: data = requests.get('http://w...
python
def char_sets(): """Return a list of the IANA Character Sets, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(char_sets, 'setlist'): clist = [] try: data = requests.get('http://w...
[ "def", "char_sets", "(", ")", ":", "if", "not", "hasattr", "(", "char_sets", ",", "'setlist'", ")", ":", "clist", "=", "[", "]", "try", ":", "data", "=", "requests", ".", "get", "(", "'http://www.iana.org/assignments/character-'", "'sets/character-sets-1.csv'", ...
Return a list of the IANA Character Sets, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once.
[ "Return", "a", "list", "of", "the", "IANA", "Character", "Sets", "or", "an", "empty", "list", "if", "the", "IANA", "website", "is", "unreachable", ".", "Store", "it", "as", "a", "function", "attribute", "so", "that", "we", "only", "build", "the", "list",...
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/enums.py#L1659-L1683
oasis-open/cti-stix-validator
stix2validator/v21/enums.py
protocols
def protocols(): """Return a list of values from the IANA Service Name and Transport Protocol Port Number Registry, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(protocols, 'protlist'): plist ...
python
def protocols(): """Return a list of values from the IANA Service Name and Transport Protocol Port Number Registry, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(protocols, 'protlist'): plist ...
[ "def", "protocols", "(", ")", ":", "if", "not", "hasattr", "(", "protocols", ",", "'protlist'", ")", ":", "plist", "=", "[", "]", "try", ":", "data", "=", "requests", ".", "get", "(", "'http://www.iana.org/assignments/service-names'", "'-port-numbers/service-nam...
Return a list of values from the IANA Service Name and Transport Protocol Port Number Registry, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once.
[ "Return", "a", "list", "of", "values", "from", "the", "IANA", "Service", "Name", "and", "Transport", "Protocol", "Port", "Number", "Registry", "or", "an", "empty", "list", "if", "the", "IANA", "website", "is", "unreachable", ".", "Store", "it", "as", "a", ...
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/enums.py#L1686-L1716
oasis-open/cti-stix-validator
stix2validator/v21/enums.py
ipfix
def ipfix(): """Return a list of values from the list of IANA IP Flow Information Export (IPFIX) Entities, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(ipfix, 'ipflist'): ilist = [] try: ...
python
def ipfix(): """Return a list of values from the list of IANA IP Flow Information Export (IPFIX) Entities, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(ipfix, 'ipflist'): ilist = [] try: ...
[ "def", "ipfix", "(", ")", ":", "if", "not", "hasattr", "(", "ipfix", ",", "'ipflist'", ")", ":", "ilist", "=", "[", "]", "try", ":", "data", "=", "requests", ".", "get", "(", "'http://www.iana.org/assignments/ipfix/ipfix-'", "'information-elements.csv'", ")", ...
Return a list of values from the list of IANA IP Flow Information Export (IPFIX) Entities, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once.
[ "Return", "a", "list", "of", "values", "from", "the", "list", "of", "IANA", "IP", "Flow", "Information", "Export", "(", "IPFIX", ")", "Entities", "or", "an", "empty", "list", "if", "the", "IANA", "website", "is", "unreachable", ".", "Store", "it", "as", ...
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/enums.py#L1719-L1741
oasis-open/cti-stix-validator
stix2validator/output.py
print_level
def print_level(log_function, fmt, level, *args): """Print a formatted message to stdout prepended by spaces. Useful for printing hierarchical information, like bullet lists. Note: If the application is running in "Silent Mode" (i.e., ``_SILENT == True``), this function will return ...
python
def print_level(log_function, fmt, level, *args): """Print a formatted message to stdout prepended by spaces. Useful for printing hierarchical information, like bullet lists. Note: If the application is running in "Silent Mode" (i.e., ``_SILENT == True``), this function will return ...
[ "def", "print_level", "(", "log_function", ",", "fmt", ",", "level", ",", "*", "args", ")", ":", "if", "_SILENT", ":", "return", "msg", "=", "fmt", "%", "args", "spaces", "=", "' '", "*", "level", "log_function", "(", "\"%s%s\"", "%", "(", "spaces",...
Print a formatted message to stdout prepended by spaces. Useful for printing hierarchical information, like bullet lists. Note: If the application is running in "Silent Mode" (i.e., ``_SILENT == True``), this function will return immediately and no message will be printed. Args: ...
[ "Print", "a", "formatted", "message", "to", "stdout", "prepended", "by", "spaces", ".", "Useful", "for", "printing", "hierarchical", "information", "like", "bullet", "lists", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L62-L94
oasis-open/cti-stix-validator
stix2validator/output.py
print_fatal_results
def print_fatal_results(results, level=0): """Print fatal errors that occurred during validation runs. """ print_level(logger.critical, _RED + "[X] Fatal Error: %s", level, results.error)
python
def print_fatal_results(results, level=0): """Print fatal errors that occurred during validation runs. """ print_level(logger.critical, _RED + "[X] Fatal Error: %s", level, results.error)
[ "def", "print_fatal_results", "(", "results", ",", "level", "=", "0", ")", ":", "print_level", "(", "logger", ".", "critical", ",", "_RED", "+", "\"[X] Fatal Error: %s\"", ",", "level", ",", "results", ".", "error", ")" ]
Print fatal errors that occurred during validation runs.
[ "Print", "fatal", "errors", "that", "occurred", "during", "validation", "runs", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L97-L100
oasis-open/cti-stix-validator
stix2validator/output.py
print_schema_results
def print_schema_results(results, level=0): """Print JSON Schema validation errors to stdout. Args: results: An instance of ObjectValidationResults. level: The level at which to print the results. """ for error in results.errors: print_level(logger.error, _RED + "[X] %s", level...
python
def print_schema_results(results, level=0): """Print JSON Schema validation errors to stdout. Args: results: An instance of ObjectValidationResults. level: The level at which to print the results. """ for error in results.errors: print_level(logger.error, _RED + "[X] %s", level...
[ "def", "print_schema_results", "(", "results", ",", "level", "=", "0", ")", ":", "for", "error", "in", "results", ".", "errors", ":", "print_level", "(", "logger", ".", "error", ",", "_RED", "+", "\"[X] %s\"", ",", "level", ",", "error", ")" ]
Print JSON Schema validation errors to stdout. Args: results: An instance of ObjectValidationResults. level: The level at which to print the results.
[ "Print", "JSON", "Schema", "validation", "errors", "to", "stdout", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L103-L112
oasis-open/cti-stix-validator
stix2validator/output.py
print_warning_results
def print_warning_results(results, level=0): """Print warning messages found during validation. """ marker = _YELLOW + "[!] " for warning in results.warnings: print_level(logger.warning, marker + "Warning: %s", level, warning)
python
def print_warning_results(results, level=0): """Print warning messages found during validation. """ marker = _YELLOW + "[!] " for warning in results.warnings: print_level(logger.warning, marker + "Warning: %s", level, warning)
[ "def", "print_warning_results", "(", "results", ",", "level", "=", "0", ")", ":", "marker", "=", "_YELLOW", "+", "\"[!] \"", "for", "warning", "in", "results", ".", "warnings", ":", "print_level", "(", "logger", ".", "warning", ",", "marker", "+", "\"Warni...
Print warning messages found during validation.
[ "Print", "warning", "messages", "found", "during", "validation", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L115-L121
oasis-open/cti-stix-validator
stix2validator/output.py
print_results_header
def print_results_header(identifier, is_valid): """Print a header for the results of either a file or an object. """ print_horizontal_rule() print_level(logger.info, "[-] Results for: %s", 0, identifier) if is_valid: marker = _GREEN + "[+]" verdict = "Valid" log_func = logg...
python
def print_results_header(identifier, is_valid): """Print a header for the results of either a file or an object. """ print_horizontal_rule() print_level(logger.info, "[-] Results for: %s", 0, identifier) if is_valid: marker = _GREEN + "[+]" verdict = "Valid" log_func = logg...
[ "def", "print_results_header", "(", "identifier", ",", "is_valid", ")", ":", "print_horizontal_rule", "(", ")", "print_level", "(", "logger", ".", "info", ",", "\"[-] Results for: %s\"", ",", "0", ",", "identifier", ")", "if", "is_valid", ":", "marker", "=", "...
Print a header for the results of either a file or an object.
[ "Print", "a", "header", "for", "the", "results", "of", "either", "a", "file", "or", "an", "object", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L139-L154
oasis-open/cti-stix-validator
stix2validator/output.py
print_object_results
def print_object_results(obj_result): """Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance. """ print_results_header(obj_result.object_id, obj_result.is_valid) if obj_result.warnings: print_warning_results(obj_result, 1) if obj_re...
python
def print_object_results(obj_result): """Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance. """ print_results_header(obj_result.object_id, obj_result.is_valid) if obj_result.warnings: print_warning_results(obj_result, 1) if obj_re...
[ "def", "print_object_results", "(", "obj_result", ")", ":", "print_results_header", "(", "obj_result", ".", "object_id", ",", "obj_result", ".", "is_valid", ")", "if", "obj_result", ".", "warnings", ":", "print_warning_results", "(", "obj_result", ",", "1", ")", ...
Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance.
[ "Print", "the", "results", "of", "validating", "an", "object", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L157-L169
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: ...
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: ...
[ "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", ".", "...
Print the results of validating a file. Args: file_result: A FileValidationResults instance.
[ "Print", "the", "results", "of", "validating", "a", "file", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L172-L188
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: ...
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: ...
[ "def", "print_results", "(", "results", ")", ":", "if", "not", "isinstance", "(", "results", ",", "list", ")", ":", "results", "=", "[", "results", "]", "for", "r", "in", "results", ":", "try", ":", "r", ".", "log", "(", ")", "except", "AttributeErro...
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", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L191-L207
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_algorit...
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_algorit...
[ "def", "vocab_encryption_algo", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'file'", ":", "try", ":",...
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", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/shoulds.py#L426-L441
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']:...
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']:...
[ "def", "enforce_relationship_refs", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'bundle'", "or", "'objects'", "not", "in", "instance", ":", "return", "rel_references", "=", "set", "(", ")", "\"\"\"Find and store all ids\"\"\"", "for", ...
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" ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/shoulds.py#L1036-L1060
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.e...
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.e...
[ "def", "timestamp_compare", "(", "instance", ")", ":", "compares", "=", "[", "(", "'modified'", ",", "'ge'", ",", "'created'", ")", "]", "additional_compares", "=", "enums", ".", "TIMESTAMP_COMPARE", ".", "get", "(", "instance", ".", "get", "(", "'type'", ...
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", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/musts.py#L87-L104
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 fir...
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 fir...
[ "def", "observable_timestamp_compare", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "compares", "=", "enums", ".", "TIMESTAMP_COMPARE_OBSERVABLE", ".", "get", "(", "obj", ".", "g...
Ensure cyber observable timestamp properties with a comparison requirement are valid.
[ "Ensure", "cyber", "observable", "timestamp", "properties", "with", "a", "comparison", "requirement", "are", "valid", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/musts.py#L108-L123
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 ...
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 ...
[ "def", "language_contents", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'language-content'", "or", "'contents'", "not", "in", "instance", ":", "return", "for", "key", ",", "value", "in", "instance", "[", "'contents'", "]", ".", ...
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", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/musts.py#L521-L537
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_s...
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_s...
[ "def", "list_musts", "(", "options", ")", ":", "validator_list", "=", "[", "timestamp", ",", "timestamp_compare", ",", "observable_timestamp_compare", ",", "object_marking_circular_refs", ",", "granular_markings_circular_refs", ",", "marking_selector_syntax", ",", "observab...
Construct the list of 'MUST' validators to be run by the validator.
[ "Construct", "the", "list", "of", "MUST", "validators", "to", "be", "run", "by", "the", "validator", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/musts.py#L540-L567
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 re...
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 re...
[ "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", ...
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...
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/codes.py#L22-L41
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 impo...
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 impo...
[ "def", "parse_args", "(", "cmd_args", ",", "is_script", "=", "False", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "__doc__", ",", "formatter_class", "=", "NewlinesHelpFormatter", ",", "epilog", "=", "CODES_TABLE", ")", ...
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: Inst...
[ "Parses", "a", "list", "of", "command", "line", "arguments", "into", "a", "ValidationOptions", "object", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/util.py#L125-L286
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): ...
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): ...
[ "def", "cyber_observable_check", "(", "original_function", ")", ":", "def", "new_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "has_cyber_observable_data", "(", "args", "[", "0", "]", ")", ":", "return", "func", "=", "origina...
Decorator for functions that require cyber observable data.
[ "Decorator", "for", "functions", "that", "require", "cyber", "observable", "data", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/util.py#L405-L416
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 = A...
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 = A...
[ "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", ".", ...
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", "." ]
train
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/util.py#L419-L440
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.fu...
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.fu...
[ "def", "render_tag", "(", "self", ",", "context", ",", "kwargs", ",", "nodelist", ")", ":", "# load configuration from passed options", "self", ".", "load_configuration", "(", "*", "*", "kwargs", ")", "# get request from context", "request", "=", "context", "[", "...
render content with "active" urls logic
[ "render", "content", "with", "active", "urls", "logic" ]
train
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/templatetags/activeurl.py#L27-L53
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.loo...
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.loo...
[ "def", "parse", "(", "self", ",", "parser", ")", ":", "# line number of token that started the tag", "lineno", "=", "next", "(", "parser", ".", "stream", ")", ".", "lineno", "# template context", "context", "=", "nodes", ".", "ContextReference", "(", ")", "# par...
parse content of extension
[ "parse", "content", "of", "extension" ]
train
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/ext/django_jinja.py#L17-L46
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.fu...
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.fu...
[ "def", "render_tag", "(", "self", ",", "context", ",", "caller", ",", "*", "*", "kwargs", ")", ":", "# load configuration from passed options", "self", ".", "load_configuration", "(", "*", "*", "kwargs", ")", "# get request from context", "request", "=", "context"...
render content with "active" urls logic
[ "render", "content", "with", "active", "urls", "logic" ]
train
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/ext/django_jinja.py#L48-L72
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}'.forma...
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}'.forma...
[ "def", "get_cache_key", "(", "content", ",", "*", "*", "kwargs", ")", ":", "cache_key", "=", "''", "for", "key", "in", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", ":", "cache_key", "=", "'{cache_key}.{key}:{value}'", ".", "format", "(", "cache_k...
generate cache key
[ "generate", "cache", "key" ]
train
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L42-L68
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 boo...
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 boo...
[ "def", "yesno_to_bool", "(", "value", ",", "varname", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "if", "value", ":", "value", "=", "'yes'", "else", ":", "value", "=", "'no'", "elif", "value", "is", "None", ":", "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", "." ]
train
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L71-L99
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 att...
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 att...
[ "def", "check_active", "(", "url", ",", "element", ",", "*", "*", "kwargs", ")", ":", "menu", "=", "yesno_to_bool", "(", "kwargs", "[", "'menu'", "]", ",", "'menu'", ")", "ignore_params", "=", "yesno_to_bool", "(", "kwargs", "[", "'ignore_params'", "]", ...
check "active" url, apply css_class
[ "check", "active", "url", "apply", "css_class" ]
train
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L102-L185
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 # djang...
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 # djang...
[ "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 fou...
check content for "active" urls
[ "check", "content", "for", "active", "urls" ]
train
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L188-L255
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...
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...
[ "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", ",", "*", "*", ...
check content for "active" urls, store results to django cache
[ "check", "content", "for", "active", "urls", "store", "results", "to", "django", "cache" ]
train
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L258-L278
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 se...
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 se...
[ "def", "load_configuration", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# update passed arguments with default values", "for", "key", "in", "settings", ".", "ACTIVE_URL_KWARGS", ":", "kwargs", ".", "setdefault", "(", "key", ",", "settings", ".", "ACTIVE_URL_...
load configuration, merge with default settings
[ "load", "configuration", "merge", "with", "default", "settings" ]
train
https://github.com/hellysmile/django-activeurl/blob/40d7f01b217641705fc5b7fe387e28e48ce332dc/django_activeurl/utils.py#L26-L39
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 res...
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 res...
[ "def", "_parse_response", "(", "response", ",", "clazz", ",", "is_list", "=", "False", ",", "resource_name", "=", "None", ")", ":", "target", "=", "response", ".", "json", "(", ")", "[", "resource_name", "]", "if", "resource_name", "else", "response", ".",...
Parse a Marathon response into an object or list of objects.
[ "Parse", "a", "Marathon", "response", "into", "an", "object", "or", "list", "of", "objects", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L67-L74
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 = N...
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 = N...
[ "def", "_do_request", "(", "self", ",", "method", ",", "path", ",", "params", "=", "None", ",", "data", "=", "None", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'Accept'", ":", "'application/json'", "}", "if", "self", ...
Query Marathon server.
[ "Query", "Marathon", "server", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L76-L121
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 cro...
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 cro...
[ "def", "_do_sse_request", "(", "self", ",", "path", ",", "params", "=", "None", ")", ":", "urls", "=", "[", "''", ".", "join", "(", "[", "server", ".", "rstrip", "(", "'/'", ")", ",", "path", "]", ")", "for", "server", "in", "self", ".", "servers...
Query Marathon server for events.
[ "Query", "Marathon", "server", "for", "events", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L123-L150
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 su...
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 su...
[ "def", "create_app", "(", "self", ",", "app_id", ",", "app", ",", "minimal", "=", "True", ")", ":", "app", ".", "id", "=", "app_id", "data", "=", "app", ".", "to_json", "(", "minimal", "=", "minimal", ")", "response", "=", "self", ".", "_do_request",...
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.MarathonA...
[ "Create", "and", "start", "an", "app", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L160-L176
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. :...
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. :...
[ "def", "list_apps", "(", "self", ",", "cmd", "=", "None", ",", "embed_tasks", "=", "False", ",", "embed_counts", "=", "False", ",", "embed_deployments", "=", "False", ",", "embed_readiness", "=", "False", ",", "embed_last_task_failure", "=", "False", ",", "e...
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 rea...
[ "List", "all", "apps", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L178-L225
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 :...
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 :...
[ "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", ...
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 ...
[ "Get", "a", "single", "app", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L227-L261
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:`...
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:`...
[ "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'"...
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...
[ "Update", "an", "app", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L276-L299
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 progre...
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 progre...
[ "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", ".", ...
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 ...
[ "Update", "multiple", "apps", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L301-L325
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 ...
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 ...
[ "def", "rollback_app", "(", "self", ",", "app_id", ",", "version", ",", "force", "=", "False", ")", ":", "params", "=", "{", "'force'", ":", "force", "}", "data", "=", "json", ".", "dumps", "(", "{", "'version'", ":", "version", "}", ")", "response",...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L327-L341
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': fo...
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': fo...
[ "def", "delete_app", "(", "self", ",", "app_id", ",", "force", "=", "False", ")", ":", "params", "=", "{", "'force'", ":", "force", "}", "response", "=", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/apps/{app_id}'", ".", "format", "(", "app_id...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L343-L355
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 in...
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 in...
[ "def", "scale_app", "(", "self", ",", "app_id", ",", "instances", "=", "None", ",", "delta", "=", "None", ",", "force", "=", "False", ")", ":", "if", "instances", "is", "None", "and", "delta", "is", "None", ":", "marathon", ".", "log", ".", "error", ...
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,...
[ "Scale", "an", "app", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L357-L386
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', '/v...
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', '/v...
[ "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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L388-L398
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( ...
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( ...
[ "def", "list_groups", "(", "self", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/groups'", ")", "groups", "=", "self", ".", "_parse_response", "(", "response", ",", "MarathonGroup", ",", "is_list",...
List all groups. :param kwargs: arbitrary search filters :returns: list of groups :rtype: list[:class:`marathon.models.group.MarathonGroup`]
[ "List", "all", "groups", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L400-L413
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...
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...
[ "def", "get_group", "(", "self", ",", "group_id", ")", ":", "response", "=", "self", ".", "_do_request", "(", "'GET'", ",", "'/v2/groups/{group_id}'", ".", "format", "(", "group_id", "=", "group_id", ")", ")", "return", "self", ".", "_parse_response", "(", ...
Get a single group. :param str group_id: group ID :returns: group :rtype: :class:`marathon.models.group.MarathonGroup`
[ "Get", "a", "single", "group", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L415-L425
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: :...
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: :...
[ "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", "=", "{", "...
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 ev...
[ "Update", "a", "group", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L427-L450
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 v...
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 v...
[ "def", "rollback_group", "(", "self", ",", "group_id", ",", "version", ",", "force", "=", "False", ")", ":", "params", "=", "{", "'force'", ":", "force", "}", "response", "=", "self", ".", "_do_request", "(", "'PUT'", ",", "'/v2/groups/{group_id}/versions/{v...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L452-L468
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} ...
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} ...
[ "def", "delete_group", "(", "self", ",", "group_id", ",", "force", "=", "False", ")", ":", "params", "=", "{", "'force'", ":", "force", "}", "response", "=", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/groups/{group_id}'", ".", "format", "(", ...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L470-L482
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} respons...
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} respons...
[ "def", "scale_group", "(", "self", ",", "group_id", ",", "scale_by", ")", ":", "data", "=", "{", "'scaleBy'", ":", "scale_by", "}", "response", "=", "self", ".", "_do_request", "(", "'PUT'", ",", "'/v2/groups/{group_id}'", ".", "format", "(", "group_id", "...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L484-L496
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.Marath...
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.Marath...
[ "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", "=...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L498-L516
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 ...
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 ...
[ "def", "kill_given_tasks", "(", "self", ",", "task_ids", ",", "scale", "=", "False", ",", "force", "=", "None", ")", ":", "params", "=", "{", "'scale'", ":", "scale", "}", "if", "force", "is", "not", "None", ":", "params", "[", "'force'", "]", "=", ...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L518-L534
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 provid...
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 provid...
[ "def", "kill_tasks", "(", "self", ",", "app_id", ",", "scale", "=", "False", ",", "wipe", "=", "False", ",", "host", "=", "None", ",", "batch_size", "=", "0", ",", "batch_delay", "=", "0", ")", ":", "def", "batch", "(", "iterable", ",", "size", ")"...
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 si...
[ "Kill", "all", "tasks", "belonging", "to", "app", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L536-L597
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:`marat...
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:`marat...
[ "def", "kill_task", "(", "self", ",", "app_id", ",", "task_id", ",", "scale", "=", "False", ",", "wipe", "=", "False", ")", ":", "params", "=", "{", "'scale'", ":", "scale", ",", "'wipe'", ":", "wipe", "}", "response", "=", "self", ".", "_do_request"...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L599-L618
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 [versio...
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 [versio...
[ "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", ...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L620-L630
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` """ re...
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` """ re...
[ "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", ...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L632-L643
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/eventSubscr...
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/eventSubscr...
[ "def", "create_event_subscription", "(", "self", ",", "url", ")", ":", "params", "=", "{", "'callbackUrl'", ":", "url", "}", "response", "=", "self", ".", "_do_request", "(", "'POST'", ",", "'/v2/eventSubscriptions'", ",", "params", ")", "return", "response", ...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L654-L664
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/eventSu...
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/eventSu...
[ "def", "delete_event_subscription", "(", "self", ",", "url", ")", ":", "params", "=", "{", "'callbackUrl'", ":", "url", "}", "response", "=", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/eventSubscriptions'", ",", "params", ")", "return", "response"...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L666-L676
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, MarathonDeploym...
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, MarathonDeploym...
[ "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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L678-L685
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': 'lastUnu...
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': 'lastUnu...
[ "def", "list_queue", "(", "self", ",", "embed_last_unused_offers", "=", "False", ")", ":", "if", "embed_last_unused_offers", ":", "params", "=", "{", "'embed'", ":", "'lastUnusedOffers'", "}", "else", ":", "params", "=", "{", "}", "response", "=", "self", "....
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L687-L698
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...
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...
[ "def", "delete_deployment", "(", "self", ",", "deployment_id", ",", "force", "=", "False", ")", ":", "if", "force", ":", "params", "=", "{", "'force'", ":", "True", "}", "self", ".", "_do_request", "(", "'DELETE'", ",", "'/v2/deployments/{deployment}'", ".",...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L700-L719
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: iter...
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: iter...
[ "def", "event_stream", "(", "self", ",", "raw", "=", "False", ",", "event_types", "=", "None", ")", ":", "ef", "=", "EventFactory", "(", ")", "params", "=", "{", "'event_type'", ":", "[", "EventFactory", ".", "class_to_event", "[", "et", "]", "if", "is...
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" ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L771-L804
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/0c11661ca2f259f8a903d114ef790...
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/0c11661ca2f259f8a903d114ef790...
[ "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", "fil...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L90-L105
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 (allo...
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 (allo...
[ "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,...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L108-L120
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, ...
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, ...
[ "def", "json_repr", "(", "self", ",", "minimal", "=", "False", ")", ":", "if", "minimal", ":", "return", "{", "to_camel_case", "(", "k", ")", ":", "v", "for", "k", ",", "v", "in", "vars", "(", "self", ")", ".", "items", "(", ")", "if", "(", "v"...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L25-L35
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L38-L43
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=Marathon...
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=Marathon...
[ "def", "to_json", "(", "self", ",", "minimal", "=", "True", ")", ":", "if", "minimal", ":", "return", "json", ".", "dumps", "(", "self", ".", "json_repr", "(", "minimal", "=", "True", ")", ",", "cls", "=", "MarathonMinimalJsonEncoder", ",", "sort_keys", ...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L45-L55
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", ".", ...
Construct a JSON-friendly representation of the object. :param bool minimal: [ignored] :rtype: list
[ "Construct", "a", "JSON", "-", "friendly", "representation", "of", "the", "object", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/constraint.py#L32-L42
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...
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...
[ "def", "from_json", "(", "cls", ",", "obj", ")", ":", "if", "len", "(", "obj", ")", "==", "2", ":", "(", "field", ",", "operator", ")", "=", "obj", "return", "cls", "(", "field", ",", "operator", ")", "if", "len", "(", "obj", ")", ">", "2", "...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/constraint.py#L45-L57
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 maratho...
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 maratho...
[ "def", "from_string", "(", "cls", ",", "constraint", ")", ":", "obj", "=", "constraint", ".", "split", "(", "':'", ")", "marathon_constraint", "=", "cls", ".", "from_json", "(", "obj", ")", "if", "marathon_constraint", ":", "return", "marathon_constraint", "...
:param str constraint: The string representation of a constraint :rtype: :class:`MarathonConstraint`
[ ":", "param", "str", "constraint", ":", "The", "string", "representation", "of", "a", "constraint" ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/constraint.py#L60-L73
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(...
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(...
[ "def", "from_tasks", "(", "cls", ",", "tasks", ")", ":", "endpoints", "=", "[", "[", "MarathonEndpoint", "(", "task", ".", "app_id", ",", "task", ".", "service_ports", "[", "port_index", "]", ",", "task", ".", "host", ",", "task", ".", "id", ",", "po...
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", "." ]
train
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/endpoint.py#L33-L50
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', pref...
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', pref...
[ "def", "_format_newlines", "(", "prefix", ",", "formatted_node", ",", "options", ")", ":", "replacement", "=", "u''", ".", "join", "(", "[", "options", ".", "NEWLINE", ",", "u'\\n'", ",", "prefix", "]", ")", "return", "formatted_node", ".", "replace", "(",...
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", "." ]
train
https://github.com/jml/tree-format/blob/cb17aba273ff043505ab9fd2afc08ce18a44cf44/tree_format/_text.py#L45-L55
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.T...
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.T...
[ "def", "get_band", "(", "self", ",", "tag", ")", ":", "tag", "=", "tag", ".", "strip", "(", "\"#\"", ")", "tag", "=", "tag", ".", "upper", "(", ")", "try", ":", "resp", "=", "requests", ".", "get", "(", "self", ".", "_base_url", "+", "'bands/'", ...
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 th...
[ "Gets", "a", "band", "." ]
train
https://github.com/umbresp/brawlstars/blob/dc8c91b68dc01983c6af3ab68df266a657ec3f7c/brawlstars/client.py#L78-L108
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 ...
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 ...
[ "async", "def", "get_player", "(", "self", ",", "tag", ")", ":", "tag", "=", "tag", ".", "strip", "(", "\"#\"", ")", "tag", "=", "tag", ".", "upper", "(", ")", "try", ":", "async", "with", "self", ".", "session", ".", "get", "(", "self", ".", "...
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. I...
[ "Gets", "a", "player", "." ]
train
https://github.com/umbresp/brawlstars/blob/dc8c91b68dc01983c6af3ab68df266a657ec3f7c/brawlstars/asyncclient.py#L48-L81
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 brawls...
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 brawls...
[ "async", "def", "get_band", "(", "self", ",", "tag", ")", ":", "tag", "=", "tag", ".", "strip", "(", "\"#\"", ")", "tag", "=", "tag", ".", "upper", "(", ")", "try", ":", "async", "with", "self", ".", "session", ".", "get", "(", "self", ".", "_b...
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 th...
[ "Gets", "a", "band", "." ]
train
https://github.com/umbresp/brawlstars/blob/dc8c91b68dc01983c6af3ab68df266a657ec3f7c/brawlstars/asyncclient.py#L83-L116
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...
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...
[ "def", "lazy_module", "(", "modname", ",", "error_strings", "=", "None", ",", "lazy_mod_class", "=", "LazyModule", ",", "level", "=", "'leaf'", ")", ":", "if", "error_strings", "is", "None", ":", "error_strings", "=", "{", "}", "_set_default_errornames", "(", ...
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 han...
[ "Function", "allowing", "lazy", "importing", "of", "a", "module", "into", "the", "namespace", "." ]
train
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L233-L334
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...
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...
[ "def", "lazy_callable", "(", "modname", ",", "*", "names", ",", "*", "*", "kwargs", ")", ":", "if", "not", "names", ":", "modname", ",", "_", ",", "name", "=", "modname", ".", "rpartition", "(", "\".\"", ")", "lazy_mod_class", "=", "_setdef", "(", "k...
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 laz...
[ "Performs", "lazy", "importing", "of", "one", "or", "more", "callables", "." ]
train
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L384-L483
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 _ImportLo...
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 _ImportLo...
[ "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 i...
Ensures that a module, and its parents, are properly loaded
[ "Ensures", "that", "a", "module", "and", "its", "parents", "are", "properly", "loaded" ]
train
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L504-L563
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", "." ]
train
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L584-L590
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 ---------- ...
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 ---------- ...
[ "def", "_clean_lazymodule", "(", "module", ")", ":", "modclass", "=", "type", "(", "module", ")", "_clean_lazy_submod_refs", "(", "module", ")", "modclass", ".", "__getattribute__", "=", "ModuleType", ".", "__getattribute__", "modclass", ".", "__setattr__", "=", ...
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 ...
[ "Removes", "all", "lazy", "behavior", "from", "a", "module", "s", "class", "for", "loading", "." ]
train
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L619-L648
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: ...
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: ...
[ "def", "_reset_lazymodule", "(", "module", ",", "cls_attrs", ")", ":", "modclass", "=", "type", "(", "module", ")", "del", "modclass", ".", "__getattribute__", "del", "modclass", ".", "__setattr__", "try", ":", "del", "modclass", ".", "_LOADING", "except", "...
Resets a module's lazy state from cached data.
[ "Resets", "a", "module", "s", "lazy", "state", "from", "cached", "data", "." ]
train
https://github.com/mnmelo/lazy_import/blob/29c74c83e90adff62d363220fee8cf7d6f0dd3c9/lazy_import/__init__.py#L666-L682
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.PY...
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.PY...
[ "def", "python_2_unicode_compatible", "(", "klass", ")", ":", "if", "six", ".", "PY2", ":", "klass", ".", "__unicode__", "=", "klass", ".", "__str__", "klass", ".", "__str__", "=", "lambda", "self", ":", "self", ".", "__unicode__", "(", ")", ".", "encode...
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", "." ]
train
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/compat.py#L5-L16
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", ")", "r...
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", "." ]
train
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/utils.py#L549-L558
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): ...
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): ...
[ "def", "force_bytes", "(", "s", ",", "encoding", "=", "'utf-8'", ",", "strings_only", "=", "False", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "s", ",", "memoryview", ")", ":", "s", "=", "bytes", "(", "s", ")", "if", "isinstan...
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", "." ]
train
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/utils.py#L624-L655
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): ...
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): ...
[ "def", "memoize", "(", "func", ",", "cache", ",", "num_args", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ")", ":", "mem_args", "=", "args", "[", ":", "num_args", "]", "if", "mem_args", "in", "cache", ":", "return"...
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", "fir...
train
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/utils.py#L664-L681
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_tracebac...
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_tracebac...
[ "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", ")", "...
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", ":", ">...
train
https://github.com/Mangopay/mangopay2-python-sdk/blob/9bbbc0f797581c9fdf7da5a70879bee6643024b7/mangopay/utils.py#L684-L708
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", "." ]
train
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L71-L76
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_defa...
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_defa...
[ "def", "init", "(", "self", ")", ":", "self", ".", "debug", "(", "'Initializing %r'", ",", "self", ")", "proto", "=", "self", ".", "server", ".", "split", "(", "'://'", ")", "[", "0", "]", "if", "proto", "==", "'https'", ":", "if", "hasattr", "(", ...
Prepare the HTTP handler, URL, and HTTP headers for all subsequent requests
[ "Prepare", "the", "HTTP", "handler", "URL", "and", "HTTP", "headers", "for", "all", "subsequent", "requests" ]
train
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L168-L201
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" ]
train
https://github.com/erigones/zabbix-api/blob/2474ab1d1ddb46c26eea70671b3a599b836d42da/zabbix_api.py#L222-L224