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
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
upsight/doctor | doctor/docs/base.py | get_json_object_lines | def get_json_object_lines(annotation: ResourceAnnotation,
properties: Dict[str, Any], field: str,
url_params: Dict, request: bool = False,
object_property: bool = False) -> List[str]:
"""Generate documentation for the given object annotation.
:param doctor.resource.ResourceAnnotation annotation:
Annotation object for the associated handler method.
:param str field: Sphinx field type to use (e.g. '<json').
:param list url_params: A list of url parameter strings.
:param bool request: Whether the schema is for the request or not.
:param bool object_property: If True it indicates this is a property of
an object that we are documenting. This is only set to True when
called recursively when encountering a property that is an object in
order to document the properties of it.
:returns: list of strings, one for each line.
"""
sig_params = annotation.logic._doctor_signature.parameters
required_lines = []
lines = []
default_field = field
for prop in sorted(properties.keys()):
annotated_type = properties[prop]
# If the property is a url parameter override the field to use
# param so that it's not documented in the json body or query params.
field = default_field
if request and prop in url_params:
field = 'param'
types = get_json_types(annotated_type)
description = annotated_type.description
obj_ref = ''
if issubclass(annotated_type, Object):
obj_ref = get_object_reference(annotated_type)
elif (issubclass(annotated_type, Array) and
annotated_type.items is not None and
not isinstance(annotated_type.items, list) and
issubclass(annotated_type.items, Object)):
# This means the type is an array of objects, so we want to
# collect the object as a resource we can document later.
obj_ref = get_object_reference(annotated_type.items)
elif (issubclass(annotated_type, Array) and
isinstance(annotated_type.items, list)):
# This means the type is array and items is a list of types. Iterate
# through each type to see if any are objects that we can document.
for item in annotated_type.items:
if issubclass(item, Object):
# Note: we are just adding them to the global variable
# ALL_RESOURCES when calling the function below and not
# using the return value as this special case is handled
# below in documenting items of an array.
get_object_reference(item)
# Document any enum.
enum = ''
if issubclass(annotated_type, Enum):
enum = ' Must be one of: `{}`'.format(annotated_type.enum)
if annotated_type.case_insensitive:
enum += ' (case-insensitive)'
enum += '.'
# Document type(s) for an array's items.
if (issubclass(annotated_type, Array) and
annotated_type.items is not None):
array_description = get_array_items_description(annotated_type)
# Prevents creating a duplicate object reference link in the docs.
if obj_ref in array_description:
obj_ref = ''
description += array_description
# Document any default value.
default = ''
if (request and prop in sig_params and
sig_params[prop].default != Signature.empty):
default = ' (Defaults to `{}`) '.format(sig_params[prop].default)
field_prop = prop
# If this is a request param and the property is required
# add required text and append lines to required_lines. This
# will make the required properties appear in alphabetical order
# before the optional.
line_template = (
':{field} {types} {prop}: {description}{enum}{default}{obj_ref}')
if request and prop in annotation.params.required:
description = '**Required**. ' + description
required_lines.append(line_template.format(
field=field, types=','.join(types), prop=field_prop,
description=description, enum=enum, obj_ref=obj_ref,
default=default))
else:
lines.append(line_template.format(
field=field, types=','.join(types), prop=field_prop,
description=description, enum=enum, obj_ref=obj_ref,
default=default))
return required_lines + lines | python | def get_json_object_lines(annotation: ResourceAnnotation,
properties: Dict[str, Any], field: str,
url_params: Dict, request: bool = False,
object_property: bool = False) -> List[str]:
"""Generate documentation for the given object annotation.
:param doctor.resource.ResourceAnnotation annotation:
Annotation object for the associated handler method.
:param str field: Sphinx field type to use (e.g. '<json').
:param list url_params: A list of url parameter strings.
:param bool request: Whether the schema is for the request or not.
:param bool object_property: If True it indicates this is a property of
an object that we are documenting. This is only set to True when
called recursively when encountering a property that is an object in
order to document the properties of it.
:returns: list of strings, one for each line.
"""
sig_params = annotation.logic._doctor_signature.parameters
required_lines = []
lines = []
default_field = field
for prop in sorted(properties.keys()):
annotated_type = properties[prop]
# If the property is a url parameter override the field to use
# param so that it's not documented in the json body or query params.
field = default_field
if request and prop in url_params:
field = 'param'
types = get_json_types(annotated_type)
description = annotated_type.description
obj_ref = ''
if issubclass(annotated_type, Object):
obj_ref = get_object_reference(annotated_type)
elif (issubclass(annotated_type, Array) and
annotated_type.items is not None and
not isinstance(annotated_type.items, list) and
issubclass(annotated_type.items, Object)):
# This means the type is an array of objects, so we want to
# collect the object as a resource we can document later.
obj_ref = get_object_reference(annotated_type.items)
elif (issubclass(annotated_type, Array) and
isinstance(annotated_type.items, list)):
# This means the type is array and items is a list of types. Iterate
# through each type to see if any are objects that we can document.
for item in annotated_type.items:
if issubclass(item, Object):
# Note: we are just adding them to the global variable
# ALL_RESOURCES when calling the function below and not
# using the return value as this special case is handled
# below in documenting items of an array.
get_object_reference(item)
# Document any enum.
enum = ''
if issubclass(annotated_type, Enum):
enum = ' Must be one of: `{}`'.format(annotated_type.enum)
if annotated_type.case_insensitive:
enum += ' (case-insensitive)'
enum += '.'
# Document type(s) for an array's items.
if (issubclass(annotated_type, Array) and
annotated_type.items is not None):
array_description = get_array_items_description(annotated_type)
# Prevents creating a duplicate object reference link in the docs.
if obj_ref in array_description:
obj_ref = ''
description += array_description
# Document any default value.
default = ''
if (request and prop in sig_params and
sig_params[prop].default != Signature.empty):
default = ' (Defaults to `{}`) '.format(sig_params[prop].default)
field_prop = prop
# If this is a request param and the property is required
# add required text and append lines to required_lines. This
# will make the required properties appear in alphabetical order
# before the optional.
line_template = (
':{field} {types} {prop}: {description}{enum}{default}{obj_ref}')
if request and prop in annotation.params.required:
description = '**Required**. ' + description
required_lines.append(line_template.format(
field=field, types=','.join(types), prop=field_prop,
description=description, enum=enum, obj_ref=obj_ref,
default=default))
else:
lines.append(line_template.format(
field=field, types=','.join(types), prop=field_prop,
description=description, enum=enum, obj_ref=obj_ref,
default=default))
return required_lines + lines | [
"def",
"get_json_object_lines",
"(",
"annotation",
":",
"ResourceAnnotation",
",",
"properties",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"field",
":",
"str",
",",
"url_params",
":",
"Dict",
",",
"request",
":",
"bool",
"=",
"False",
",",
"object_property",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"str",
"]",
":",
"sig_params",
"=",
"annotation",
".",
"logic",
".",
"_doctor_signature",
".",
"parameters",
"required_lines",
"=",
"[",
"]",
"lines",
"=",
"[",
"]",
"default_field",
"=",
"field",
"for",
"prop",
"in",
"sorted",
"(",
"properties",
".",
"keys",
"(",
")",
")",
":",
"annotated_type",
"=",
"properties",
"[",
"prop",
"]",
"# If the property is a url parameter override the field to use",
"# param so that it's not documented in the json body or query params.",
"field",
"=",
"default_field",
"if",
"request",
"and",
"prop",
"in",
"url_params",
":",
"field",
"=",
"'param'",
"types",
"=",
"get_json_types",
"(",
"annotated_type",
")",
"description",
"=",
"annotated_type",
".",
"description",
"obj_ref",
"=",
"''",
"if",
"issubclass",
"(",
"annotated_type",
",",
"Object",
")",
":",
"obj_ref",
"=",
"get_object_reference",
"(",
"annotated_type",
")",
"elif",
"(",
"issubclass",
"(",
"annotated_type",
",",
"Array",
")",
"and",
"annotated_type",
".",
"items",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"annotated_type",
".",
"items",
",",
"list",
")",
"and",
"issubclass",
"(",
"annotated_type",
".",
"items",
",",
"Object",
")",
")",
":",
"# This means the type is an array of objects, so we want to",
"# collect the object as a resource we can document later.",
"obj_ref",
"=",
"get_object_reference",
"(",
"annotated_type",
".",
"items",
")",
"elif",
"(",
"issubclass",
"(",
"annotated_type",
",",
"Array",
")",
"and",
"isinstance",
"(",
"annotated_type",
".",
"items",
",",
"list",
")",
")",
":",
"# This means the type is array and items is a list of types. Iterate",
"# through each type to see if any are objects that we can document.",
"for",
"item",
"in",
"annotated_type",
".",
"items",
":",
"if",
"issubclass",
"(",
"item",
",",
"Object",
")",
":",
"# Note: we are just adding them to the global variable",
"# ALL_RESOURCES when calling the function below and not",
"# using the return value as this special case is handled",
"# below in documenting items of an array.",
"get_object_reference",
"(",
"item",
")",
"# Document any enum.",
"enum",
"=",
"''",
"if",
"issubclass",
"(",
"annotated_type",
",",
"Enum",
")",
":",
"enum",
"=",
"' Must be one of: `{}`'",
".",
"format",
"(",
"annotated_type",
".",
"enum",
")",
"if",
"annotated_type",
".",
"case_insensitive",
":",
"enum",
"+=",
"' (case-insensitive)'",
"enum",
"+=",
"'.'",
"# Document type(s) for an array's items.",
"if",
"(",
"issubclass",
"(",
"annotated_type",
",",
"Array",
")",
"and",
"annotated_type",
".",
"items",
"is",
"not",
"None",
")",
":",
"array_description",
"=",
"get_array_items_description",
"(",
"annotated_type",
")",
"# Prevents creating a duplicate object reference link in the docs.",
"if",
"obj_ref",
"in",
"array_description",
":",
"obj_ref",
"=",
"''",
"description",
"+=",
"array_description",
"# Document any default value.",
"default",
"=",
"''",
"if",
"(",
"request",
"and",
"prop",
"in",
"sig_params",
"and",
"sig_params",
"[",
"prop",
"]",
".",
"default",
"!=",
"Signature",
".",
"empty",
")",
":",
"default",
"=",
"' (Defaults to `{}`) '",
".",
"format",
"(",
"sig_params",
"[",
"prop",
"]",
".",
"default",
")",
"field_prop",
"=",
"prop",
"# If this is a request param and the property is required",
"# add required text and append lines to required_lines. This",
"# will make the required properties appear in alphabetical order",
"# before the optional.",
"line_template",
"=",
"(",
"':{field} {types} {prop}: {description}{enum}{default}{obj_ref}'",
")",
"if",
"request",
"and",
"prop",
"in",
"annotation",
".",
"params",
".",
"required",
":",
"description",
"=",
"'**Required**. '",
"+",
"description",
"required_lines",
".",
"append",
"(",
"line_template",
".",
"format",
"(",
"field",
"=",
"field",
",",
"types",
"=",
"','",
".",
"join",
"(",
"types",
")",
",",
"prop",
"=",
"field_prop",
",",
"description",
"=",
"description",
",",
"enum",
"=",
"enum",
",",
"obj_ref",
"=",
"obj_ref",
",",
"default",
"=",
"default",
")",
")",
"else",
":",
"lines",
".",
"append",
"(",
"line_template",
".",
"format",
"(",
"field",
"=",
"field",
",",
"types",
"=",
"','",
".",
"join",
"(",
"types",
")",
",",
"prop",
"=",
"field_prop",
",",
"description",
"=",
"description",
",",
"enum",
"=",
"enum",
",",
"obj_ref",
"=",
"obj_ref",
",",
"default",
"=",
"default",
")",
")",
"return",
"required_lines",
"+",
"lines"
] | Generate documentation for the given object annotation.
:param doctor.resource.ResourceAnnotation annotation:
Annotation object for the associated handler method.
:param str field: Sphinx field type to use (e.g. '<json').
:param list url_params: A list of url parameter strings.
:param bool request: Whether the schema is for the request or not.
:param bool object_property: If True it indicates this is a property of
an object that we are documenting. This is only set to True when
called recursively when encountering a property that is an object in
order to document the properties of it.
:returns: list of strings, one for each line. | [
"Generate",
"documentation",
"for",
"the",
"given",
"object",
"annotation",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L221-L316 |
upsight/doctor | doctor/docs/base.py | get_json_lines | def get_json_lines(annotation: ResourceAnnotation, field: str, route: str,
request: bool = False) -> List:
"""Generate documentation lines for the given annotation.
This only documents schemas of type "object", or type "list" where each
"item" is an object. Other types are ignored (but a warning is logged).
:param doctor.resource.ResourceAnnotation annotation:
Annotation object for the associated handler method.
:param str field: Sphinx field type to use (e.g. '<json').
:param str route: The route the annotation is attached to.
:param bool request: Whether the resource annotation is for the request or
not.
:returns: list of strings, one for each line.
"""
url_params = URL_PARAMS_RE.findall(route)
if not request:
return_type = annotation.logic._doctor_signature.return_annotation
# Check if our return annotation is a Response that supplied a
# type we can use to document. If so, use that type for api docs.
# e.g. def logic() -> Response[MyType]
if issubclass(return_type, Response):
if return_type.__args__ is not None:
return_type = return_type.__args__[0]
if issubclass(return_type, Array):
if issubclass(return_type.items, Object):
properties = return_type.items.properties
field += 'arr'
else:
return []
elif issubclass(return_type, Object):
properties = return_type.properties
else:
return []
else:
# If we defined a req_obj_type for the logic, use that type's
# properties instead of the function signature.
if annotation.logic._doctor_req_obj_type:
properties = annotation.logic._doctor_req_obj_type.properties
else:
parameters = annotation.annotated_parameters
properties = {k: p.annotation for k, p in parameters.items()}
return get_json_object_lines(annotation, properties, field, url_params,
request) | python | def get_json_lines(annotation: ResourceAnnotation, field: str, route: str,
request: bool = False) -> List:
"""Generate documentation lines for the given annotation.
This only documents schemas of type "object", or type "list" where each
"item" is an object. Other types are ignored (but a warning is logged).
:param doctor.resource.ResourceAnnotation annotation:
Annotation object for the associated handler method.
:param str field: Sphinx field type to use (e.g. '<json').
:param str route: The route the annotation is attached to.
:param bool request: Whether the resource annotation is for the request or
not.
:returns: list of strings, one for each line.
"""
url_params = URL_PARAMS_RE.findall(route)
if not request:
return_type = annotation.logic._doctor_signature.return_annotation
# Check if our return annotation is a Response that supplied a
# type we can use to document. If so, use that type for api docs.
# e.g. def logic() -> Response[MyType]
if issubclass(return_type, Response):
if return_type.__args__ is not None:
return_type = return_type.__args__[0]
if issubclass(return_type, Array):
if issubclass(return_type.items, Object):
properties = return_type.items.properties
field += 'arr'
else:
return []
elif issubclass(return_type, Object):
properties = return_type.properties
else:
return []
else:
# If we defined a req_obj_type for the logic, use that type's
# properties instead of the function signature.
if annotation.logic._doctor_req_obj_type:
properties = annotation.logic._doctor_req_obj_type.properties
else:
parameters = annotation.annotated_parameters
properties = {k: p.annotation for k, p in parameters.items()}
return get_json_object_lines(annotation, properties, field, url_params,
request) | [
"def",
"get_json_lines",
"(",
"annotation",
":",
"ResourceAnnotation",
",",
"field",
":",
"str",
",",
"route",
":",
"str",
",",
"request",
":",
"bool",
"=",
"False",
")",
"->",
"List",
":",
"url_params",
"=",
"URL_PARAMS_RE",
".",
"findall",
"(",
"route",
")",
"if",
"not",
"request",
":",
"return_type",
"=",
"annotation",
".",
"logic",
".",
"_doctor_signature",
".",
"return_annotation",
"# Check if our return annotation is a Response that supplied a",
"# type we can use to document. If so, use that type for api docs.",
"# e.g. def logic() -> Response[MyType]",
"if",
"issubclass",
"(",
"return_type",
",",
"Response",
")",
":",
"if",
"return_type",
".",
"__args__",
"is",
"not",
"None",
":",
"return_type",
"=",
"return_type",
".",
"__args__",
"[",
"0",
"]",
"if",
"issubclass",
"(",
"return_type",
",",
"Array",
")",
":",
"if",
"issubclass",
"(",
"return_type",
".",
"items",
",",
"Object",
")",
":",
"properties",
"=",
"return_type",
".",
"items",
".",
"properties",
"field",
"+=",
"'arr'",
"else",
":",
"return",
"[",
"]",
"elif",
"issubclass",
"(",
"return_type",
",",
"Object",
")",
":",
"properties",
"=",
"return_type",
".",
"properties",
"else",
":",
"return",
"[",
"]",
"else",
":",
"# If we defined a req_obj_type for the logic, use that type's",
"# properties instead of the function signature.",
"if",
"annotation",
".",
"logic",
".",
"_doctor_req_obj_type",
":",
"properties",
"=",
"annotation",
".",
"logic",
".",
"_doctor_req_obj_type",
".",
"properties",
"else",
":",
"parameters",
"=",
"annotation",
".",
"annotated_parameters",
"properties",
"=",
"{",
"k",
":",
"p",
".",
"annotation",
"for",
"k",
",",
"p",
"in",
"parameters",
".",
"items",
"(",
")",
"}",
"return",
"get_json_object_lines",
"(",
"annotation",
",",
"properties",
",",
"field",
",",
"url_params",
",",
"request",
")"
] | Generate documentation lines for the given annotation.
This only documents schemas of type "object", or type "list" where each
"item" is an object. Other types are ignored (but a warning is logged).
:param doctor.resource.ResourceAnnotation annotation:
Annotation object for the associated handler method.
:param str field: Sphinx field type to use (e.g. '<json').
:param str route: The route the annotation is attached to.
:param bool request: Whether the resource annotation is for the request or
not.
:returns: list of strings, one for each line. | [
"Generate",
"documentation",
"lines",
"for",
"the",
"given",
"annotation",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L319-L362 |
upsight/doctor | doctor/docs/base.py | get_resource_object_doc_lines | def get_resource_object_doc_lines() -> List[str]:
"""Generate documentation lines for all collected resource objects.
As API documentation is generated we keep a running list of objects used
in request parameters and responses. This section will generate
documentation for each object and provide an inline reference in the API
documentation.
:returns: A list of lines required to generate the documentation.
"""
# First loop through all resources and make sure to add any properties that
# are objects and not already in `ALL_RESOURCES`. We iterate over a copy
# since we will be modifying the dict during the loop.
for resource_name, a_type in ALL_RESOURCES.copy().items():
for prop_a_type in a_type.properties.values():
if issubclass(prop_a_type, Object):
resource_name = prop_a_type.title
if resource_name is None:
class_name = prop_a_type.__name__
resource_name = class_name_to_resource_name(class_name)
ALL_RESOURCES[resource_name] = prop_a_type
elif (issubclass(prop_a_type, Array) and
prop_a_type.items is not None and
not isinstance(prop_a_type.items, list) and
issubclass(prop_a_type.items, Object)):
# This means the type is an array of objects, so we want to
# collect the object as a resource we can document later.
resource_name = prop_a_type.items.title
if resource_name is None:
class_name = prop_a_type.items.__name__
resource_name = class_name_to_resource_name(class_name)
ALL_RESOURCES[resource_name] = prop_a_type.items
# If we don't have any resources to document, just return.
if not ALL_RESOURCES:
return []
lines = ['Resource Objects', '----------------']
for resource_name in sorted(ALL_RESOURCES.keys()):
a_type = ALL_RESOURCES[resource_name]
# First add a reference to the resource
resource_ref = '_resource-{}'.format(
'-'.join(resource_name.lower().split(' ')))
lines.extend(['.. {}:'.format(resource_ref), ''])
# Add resource name heading
lines.extend([resource_name, '#' * len(resource_name)])
# Add resource description
lines.extend([a_type.description, ''])
# Only document attributes if it has properties defined.
if a_type.properties:
# Add attributes documentation.
lines.extend(['Attributes', '**********'])
for prop in a_type.properties:
prop_a_type = a_type.properties[prop]
description = a_type.properties[prop].description.strip()
# Add any object reference if the property is an object or
# an array of objects.
obj_ref = ''
if issubclass(prop_a_type, Object):
obj_ref = get_object_reference(prop_a_type)
elif (issubclass(prop_a_type, Array) and
prop_a_type.items is not None and
not isinstance(prop_a_type.items, list) and
issubclass(prop_a_type.items, Object)):
# This means the type is an array of objects.
obj_ref = get_object_reference(prop_a_type.items)
elif (issubclass(prop_a_type, Array) and
prop_a_type.items is not None):
description += get_array_items_description(prop_a_type)
native_type = a_type.properties[prop].native_type.__name__
if prop in a_type.required:
description = '**Required**. ' + description
lines.append('* **{}** (*{}*) - {}{}'.format(
prop, native_type, description, obj_ref).strip())
lines.append('')
# Add example of object.
lines.extend(['Example', '*******'])
example = a_type.get_example()
pretty_json = json.dumps(example, separators=(',', ': '), indent=4,
sort_keys=True)
pretty_json_lines = prefix_lines(pretty_json, ' ')
lines.extend(['.. code-block:: json', ''])
lines.extend(pretty_json_lines)
return lines | python | def get_resource_object_doc_lines() -> List[str]:
"""Generate documentation lines for all collected resource objects.
As API documentation is generated we keep a running list of objects used
in request parameters and responses. This section will generate
documentation for each object and provide an inline reference in the API
documentation.
:returns: A list of lines required to generate the documentation.
"""
# First loop through all resources and make sure to add any properties that
# are objects and not already in `ALL_RESOURCES`. We iterate over a copy
# since we will be modifying the dict during the loop.
for resource_name, a_type in ALL_RESOURCES.copy().items():
for prop_a_type in a_type.properties.values():
if issubclass(prop_a_type, Object):
resource_name = prop_a_type.title
if resource_name is None:
class_name = prop_a_type.__name__
resource_name = class_name_to_resource_name(class_name)
ALL_RESOURCES[resource_name] = prop_a_type
elif (issubclass(prop_a_type, Array) and
prop_a_type.items is not None and
not isinstance(prop_a_type.items, list) and
issubclass(prop_a_type.items, Object)):
# This means the type is an array of objects, so we want to
# collect the object as a resource we can document later.
resource_name = prop_a_type.items.title
if resource_name is None:
class_name = prop_a_type.items.__name__
resource_name = class_name_to_resource_name(class_name)
ALL_RESOURCES[resource_name] = prop_a_type.items
# If we don't have any resources to document, just return.
if not ALL_RESOURCES:
return []
lines = ['Resource Objects', '----------------']
for resource_name in sorted(ALL_RESOURCES.keys()):
a_type = ALL_RESOURCES[resource_name]
# First add a reference to the resource
resource_ref = '_resource-{}'.format(
'-'.join(resource_name.lower().split(' ')))
lines.extend(['.. {}:'.format(resource_ref), ''])
# Add resource name heading
lines.extend([resource_name, '#' * len(resource_name)])
# Add resource description
lines.extend([a_type.description, ''])
# Only document attributes if it has properties defined.
if a_type.properties:
# Add attributes documentation.
lines.extend(['Attributes', '**********'])
for prop in a_type.properties:
prop_a_type = a_type.properties[prop]
description = a_type.properties[prop].description.strip()
# Add any object reference if the property is an object or
# an array of objects.
obj_ref = ''
if issubclass(prop_a_type, Object):
obj_ref = get_object_reference(prop_a_type)
elif (issubclass(prop_a_type, Array) and
prop_a_type.items is not None and
not isinstance(prop_a_type.items, list) and
issubclass(prop_a_type.items, Object)):
# This means the type is an array of objects.
obj_ref = get_object_reference(prop_a_type.items)
elif (issubclass(prop_a_type, Array) and
prop_a_type.items is not None):
description += get_array_items_description(prop_a_type)
native_type = a_type.properties[prop].native_type.__name__
if prop in a_type.required:
description = '**Required**. ' + description
lines.append('* **{}** (*{}*) - {}{}'.format(
prop, native_type, description, obj_ref).strip())
lines.append('')
# Add example of object.
lines.extend(['Example', '*******'])
example = a_type.get_example()
pretty_json = json.dumps(example, separators=(',', ': '), indent=4,
sort_keys=True)
pretty_json_lines = prefix_lines(pretty_json, ' ')
lines.extend(['.. code-block:: json', ''])
lines.extend(pretty_json_lines)
return lines | [
"def",
"get_resource_object_doc_lines",
"(",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# First loop through all resources and make sure to add any properties that",
"# are objects and not already in `ALL_RESOURCES`. We iterate over a copy",
"# since we will be modifying the dict during the loop.",
"for",
"resource_name",
",",
"a_type",
"in",
"ALL_RESOURCES",
".",
"copy",
"(",
")",
".",
"items",
"(",
")",
":",
"for",
"prop_a_type",
"in",
"a_type",
".",
"properties",
".",
"values",
"(",
")",
":",
"if",
"issubclass",
"(",
"prop_a_type",
",",
"Object",
")",
":",
"resource_name",
"=",
"prop_a_type",
".",
"title",
"if",
"resource_name",
"is",
"None",
":",
"class_name",
"=",
"prop_a_type",
".",
"__name__",
"resource_name",
"=",
"class_name_to_resource_name",
"(",
"class_name",
")",
"ALL_RESOURCES",
"[",
"resource_name",
"]",
"=",
"prop_a_type",
"elif",
"(",
"issubclass",
"(",
"prop_a_type",
",",
"Array",
")",
"and",
"prop_a_type",
".",
"items",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"prop_a_type",
".",
"items",
",",
"list",
")",
"and",
"issubclass",
"(",
"prop_a_type",
".",
"items",
",",
"Object",
")",
")",
":",
"# This means the type is an array of objects, so we want to",
"# collect the object as a resource we can document later.",
"resource_name",
"=",
"prop_a_type",
".",
"items",
".",
"title",
"if",
"resource_name",
"is",
"None",
":",
"class_name",
"=",
"prop_a_type",
".",
"items",
".",
"__name__",
"resource_name",
"=",
"class_name_to_resource_name",
"(",
"class_name",
")",
"ALL_RESOURCES",
"[",
"resource_name",
"]",
"=",
"prop_a_type",
".",
"items",
"# If we don't have any resources to document, just return.",
"if",
"not",
"ALL_RESOURCES",
":",
"return",
"[",
"]",
"lines",
"=",
"[",
"'Resource Objects'",
",",
"'----------------'",
"]",
"for",
"resource_name",
"in",
"sorted",
"(",
"ALL_RESOURCES",
".",
"keys",
"(",
")",
")",
":",
"a_type",
"=",
"ALL_RESOURCES",
"[",
"resource_name",
"]",
"# First add a reference to the resource",
"resource_ref",
"=",
"'_resource-{}'",
".",
"format",
"(",
"'-'",
".",
"join",
"(",
"resource_name",
".",
"lower",
"(",
")",
".",
"split",
"(",
"' '",
")",
")",
")",
"lines",
".",
"extend",
"(",
"[",
"'.. {}:'",
".",
"format",
"(",
"resource_ref",
")",
",",
"''",
"]",
")",
"# Add resource name heading",
"lines",
".",
"extend",
"(",
"[",
"resource_name",
",",
"'#'",
"*",
"len",
"(",
"resource_name",
")",
"]",
")",
"# Add resource description",
"lines",
".",
"extend",
"(",
"[",
"a_type",
".",
"description",
",",
"''",
"]",
")",
"# Only document attributes if it has properties defined.",
"if",
"a_type",
".",
"properties",
":",
"# Add attributes documentation.",
"lines",
".",
"extend",
"(",
"[",
"'Attributes'",
",",
"'**********'",
"]",
")",
"for",
"prop",
"in",
"a_type",
".",
"properties",
":",
"prop_a_type",
"=",
"a_type",
".",
"properties",
"[",
"prop",
"]",
"description",
"=",
"a_type",
".",
"properties",
"[",
"prop",
"]",
".",
"description",
".",
"strip",
"(",
")",
"# Add any object reference if the property is an object or",
"# an array of objects.",
"obj_ref",
"=",
"''",
"if",
"issubclass",
"(",
"prop_a_type",
",",
"Object",
")",
":",
"obj_ref",
"=",
"get_object_reference",
"(",
"prop_a_type",
")",
"elif",
"(",
"issubclass",
"(",
"prop_a_type",
",",
"Array",
")",
"and",
"prop_a_type",
".",
"items",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"prop_a_type",
".",
"items",
",",
"list",
")",
"and",
"issubclass",
"(",
"prop_a_type",
".",
"items",
",",
"Object",
")",
")",
":",
"# This means the type is an array of objects.",
"obj_ref",
"=",
"get_object_reference",
"(",
"prop_a_type",
".",
"items",
")",
"elif",
"(",
"issubclass",
"(",
"prop_a_type",
",",
"Array",
")",
"and",
"prop_a_type",
".",
"items",
"is",
"not",
"None",
")",
":",
"description",
"+=",
"get_array_items_description",
"(",
"prop_a_type",
")",
"native_type",
"=",
"a_type",
".",
"properties",
"[",
"prop",
"]",
".",
"native_type",
".",
"__name__",
"if",
"prop",
"in",
"a_type",
".",
"required",
":",
"description",
"=",
"'**Required**. '",
"+",
"description",
"lines",
".",
"append",
"(",
"'* **{}** (*{}*) - {}{}'",
".",
"format",
"(",
"prop",
",",
"native_type",
",",
"description",
",",
"obj_ref",
")",
".",
"strip",
"(",
")",
")",
"lines",
".",
"append",
"(",
"''",
")",
"# Add example of object.",
"lines",
".",
"extend",
"(",
"[",
"'Example'",
",",
"'*******'",
"]",
")",
"example",
"=",
"a_type",
".",
"get_example",
"(",
")",
"pretty_json",
"=",
"json",
".",
"dumps",
"(",
"example",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
"pretty_json_lines",
"=",
"prefix_lines",
"(",
"pretty_json",
",",
"' '",
")",
"lines",
".",
"extend",
"(",
"[",
"'.. code-block:: json'",
",",
"''",
"]",
")",
"lines",
".",
"extend",
"(",
"pretty_json_lines",
")",
"return",
"lines"
] | Generate documentation lines for all collected resource objects.
As API documentation is generated we keep a running list of objects used
in request parameters and responses. This section will generate
documentation for each object and provide an inline reference in the API
documentation.
:returns: A list of lines required to generate the documentation. | [
"Generate",
"documentation",
"lines",
"for",
"all",
"collected",
"resource",
"objects",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L365-L448 |
upsight/doctor | doctor/docs/base.py | get_name | def get_name(value) -> str:
"""Return a best guess at the qualified name for a class or function.
:param value: A class or function object.
:type value: class or function
:returns str:
"""
if value.__module__ == '__builtin__':
return value.__name__
else:
return '.'.join((value.__module__, value.__name__)) | python | def get_name(value) -> str:
"""Return a best guess at the qualified name for a class or function.
:param value: A class or function object.
:type value: class or function
:returns str:
"""
if value.__module__ == '__builtin__':
return value.__name__
else:
return '.'.join((value.__module__, value.__name__)) | [
"def",
"get_name",
"(",
"value",
")",
"->",
"str",
":",
"if",
"value",
".",
"__module__",
"==",
"'__builtin__'",
":",
"return",
"value",
".",
"__name__",
"else",
":",
"return",
"'.'",
".",
"join",
"(",
"(",
"value",
".",
"__module__",
",",
"value",
".",
"__name__",
")",
")"
] | Return a best guess at the qualified name for a class or function.
:param value: A class or function object.
:type value: class or function
:returns str: | [
"Return",
"a",
"best",
"guess",
"at",
"the",
"qualified",
"name",
"for",
"a",
"class",
"or",
"function",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L451-L461 |
upsight/doctor | doctor/docs/base.py | normalize_route | def normalize_route(route: str) -> str:
"""Strip some of the ugly regexp characters from the given pattern.
>>> normalize_route('^/user/<user_id:int>/?$')
u'/user/(user_id:int)/'
"""
normalized_route = str(route).lstrip('^').rstrip('$').rstrip('?')
normalized_route = normalized_route.replace('<', '(').replace('>', ')')
return normalized_route | python | def normalize_route(route: str) -> str:
"""Strip some of the ugly regexp characters from the given pattern.
>>> normalize_route('^/user/<user_id:int>/?$')
u'/user/(user_id:int)/'
"""
normalized_route = str(route).lstrip('^').rstrip('$').rstrip('?')
normalized_route = normalized_route.replace('<', '(').replace('>', ')')
return normalized_route | [
"def",
"normalize_route",
"(",
"route",
":",
"str",
")",
"->",
"str",
":",
"normalized_route",
"=",
"str",
"(",
"route",
")",
".",
"lstrip",
"(",
"'^'",
")",
".",
"rstrip",
"(",
"'$'",
")",
".",
"rstrip",
"(",
"'?'",
")",
"normalized_route",
"=",
"normalized_route",
".",
"replace",
"(",
"'<'",
",",
"'('",
")",
".",
"replace",
"(",
"'>'",
",",
"')'",
")",
"return",
"normalized_route"
] | Strip some of the ugly regexp characters from the given pattern.
>>> normalize_route('^/user/<user_id:int>/?$')
u'/user/(user_id:int)/' | [
"Strip",
"some",
"of",
"the",
"ugly",
"regexp",
"characters",
"from",
"the",
"given",
"pattern",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L464-L472 |
upsight/doctor | doctor/docs/base.py | prefix_lines | def prefix_lines(lines, prefix):
"""Add the prefix to each of the lines.
>>> prefix_lines(['foo', 'bar'], ' ')
[' foo', ' bar']
>>> prefix_lines('foo\\nbar', ' ')
[' foo', ' bar']
:param list or str lines: A string or a list of strings. If a string is
passed, the string is split using splitlines().
:param str prefix: Prefix to add to the lines. Usually an indent.
:returns: list
"""
if isinstance(lines, bytes):
lines = lines.decode('utf-8')
if isinstance(lines, str):
lines = lines.splitlines()
return [prefix + line for line in lines] | python | def prefix_lines(lines, prefix):
"""Add the prefix to each of the lines.
>>> prefix_lines(['foo', 'bar'], ' ')
[' foo', ' bar']
>>> prefix_lines('foo\\nbar', ' ')
[' foo', ' bar']
:param list or str lines: A string or a list of strings. If a string is
passed, the string is split using splitlines().
:param str prefix: Prefix to add to the lines. Usually an indent.
:returns: list
"""
if isinstance(lines, bytes):
lines = lines.decode('utf-8')
if isinstance(lines, str):
lines = lines.splitlines()
return [prefix + line for line in lines] | [
"def",
"prefix_lines",
"(",
"lines",
",",
"prefix",
")",
":",
"if",
"isinstance",
"(",
"lines",
",",
"bytes",
")",
":",
"lines",
"=",
"lines",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"lines",
",",
"str",
")",
":",
"lines",
"=",
"lines",
".",
"splitlines",
"(",
")",
"return",
"[",
"prefix",
"+",
"line",
"for",
"line",
"in",
"lines",
"]"
] | Add the prefix to each of the lines.
>>> prefix_lines(['foo', 'bar'], ' ')
[' foo', ' bar']
>>> prefix_lines('foo\\nbar', ' ')
[' foo', ' bar']
:param list or str lines: A string or a list of strings. If a string is
passed, the string is split using splitlines().
:param str prefix: Prefix to add to the lines. Usually an indent.
:returns: list | [
"Add",
"the",
"prefix",
"to",
"each",
"of",
"the",
"lines",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L475-L492 |
upsight/doctor | doctor/docs/base.py | class_name_to_resource_name | def class_name_to_resource_name(class_name: str) -> str:
"""Converts a camel case class name to a resource name with spaces.
>>> class_name_to_resource_name('FooBarObject')
'Foo Bar Object'
:param class_name: The name to convert.
:returns: The resource name.
"""
s = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', class_name)
return re.sub('([a-z0-9])([A-Z])', r'\1 \2', s) | python | def class_name_to_resource_name(class_name: str) -> str:
"""Converts a camel case class name to a resource name with spaces.
>>> class_name_to_resource_name('FooBarObject')
'Foo Bar Object'
:param class_name: The name to convert.
:returns: The resource name.
"""
s = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', class_name)
return re.sub('([a-z0-9])([A-Z])', r'\1 \2', s) | [
"def",
"class_name_to_resource_name",
"(",
"class_name",
":",
"str",
")",
"->",
"str",
":",
"s",
"=",
"re",
".",
"sub",
"(",
"'(.)([A-Z][a-z]+)'",
",",
"r'\\1 \\2'",
",",
"class_name",
")",
"return",
"re",
".",
"sub",
"(",
"'([a-z0-9])([A-Z])'",
",",
"r'\\1 \\2'",
",",
"s",
")"
] | Converts a camel case class name to a resource name with spaces.
>>> class_name_to_resource_name('FooBarObject')
'Foo Bar Object'
:param class_name: The name to convert.
:returns: The resource name. | [
"Converts",
"a",
"camel",
"case",
"class",
"name",
"to",
"a",
"resource",
"name",
"with",
"spaces",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L495-L505 |
upsight/doctor | doctor/docs/base.py | BaseDirective._prepare_env | def _prepare_env(self): # pragma: no cover
"""Setup the document's environment, if necessary."""
env = self.state.document.settings.env
if not hasattr(env, self.directive_name):
# Track places where we use this directive, so we can check for
# outdated documents in the future.
state = DirectiveState()
setattr(env, self.directive_name, state)
else:
state = getattr(env, self.directive_name)
return env, state | python | def _prepare_env(self): # pragma: no cover
"""Setup the document's environment, if necessary."""
env = self.state.document.settings.env
if not hasattr(env, self.directive_name):
# Track places where we use this directive, so we can check for
# outdated documents in the future.
state = DirectiveState()
setattr(env, self.directive_name, state)
else:
state = getattr(env, self.directive_name)
return env, state | [
"def",
"_prepare_env",
"(",
"self",
")",
":",
"# pragma: no cover",
"env",
"=",
"self",
".",
"state",
".",
"document",
".",
"settings",
".",
"env",
"if",
"not",
"hasattr",
"(",
"env",
",",
"self",
".",
"directive_name",
")",
":",
"# Track places where we use this directive, so we can check for",
"# outdated documents in the future.",
"state",
"=",
"DirectiveState",
"(",
")",
"setattr",
"(",
"env",
",",
"self",
".",
"directive_name",
",",
"state",
")",
"else",
":",
"state",
"=",
"getattr",
"(",
"env",
",",
"self",
".",
"directive_name",
")",
"return",
"env",
",",
"state"
] | Setup the document's environment, if necessary. | [
"Setup",
"the",
"document",
"s",
"environment",
"if",
"necessary",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L551-L561 |
upsight/doctor | doctor/docs/base.py | BaseDirective._render_rst | def _render_rst(self): # pragma: no cover
"""Render lines of reStructuredText for items yielded by
:meth:`~doctor.docs.base.BaseHarness.iter_annotations`.
"""
# Create a mapping of headers to annotations. We want to group
# all annotations by a header, but they could be in multiple handlers
# so we create a map of them here with the heading as the key and
# the list of associated annotations as a list. This is so we can
# sort them alphabetically to make reading the api docs easier.
heading_to_annotations_map = defaultdict(list)
for heading, route, handler, annotations in (
self.harness.iter_annotations()):
# Set the route and handler as attributes so we can retrieve them
# when we loop through them all below.
for annotation in annotations:
annotation.route = route
annotation.handler = handler
heading_to_annotations_map[heading].append(annotation)
headings = list(heading_to_annotations_map.keys())
headings.sort()
previous_heading = None
for heading in headings:
annotations = heading_to_annotations_map.get(heading)
# Sort all the annotations by title.
annotations.sort(key=lambda a: a.title)
# Only emit a new heading if the resource has changed. This
# esnures that documented endpoints for the same resource all
# end up under a single heading.
if previous_heading != heading:
previous_heading = heading
yield HEADING_TOKEN + heading
for annotation in annotations:
route = annotation.route
normalized_route = normalize_route(route)
handler = annotation.handler
# Adds a title for the endpoint.
if annotation.title is not None:
yield annotation.title
yield '#' * len(annotation.title)
docstring = get_description_lines(getattr(annotation.logic,
'__doc__', None))
# Documents the logic function associated with the annotation.
docstring.append(':Logic Func: :func:`~{}.{}`'.format(
annotation.logic.__module__, annotation.logic.__name__))
field = '<json'
if annotation.http_method in ('DELETE', 'GET'):
field = 'query'
docstring.extend(get_json_lines(
annotation, field=field, route=normalized_route,
request=True)
)
# Document any request headers.
defined_headers = list(self.harness._get_headers(
str(route), annotation).keys())
defined_headers.sort()
for header in defined_headers:
definition = self.harness.header_definitions.get(
header, '').strip()
docstring.append(':reqheader {}: {}'.format(
header, definition))
# Document response if a type was defined.
if annotation.return_annotation != Parameter.empty:
docstring.extend(get_json_lines(
annotation, field='>json', route=normalized_route))
docstring.extend(self._make_example(route, handler, annotation))
for line in http_directive(annotation.http_method,
normalized_route, docstring):
yield line
# Document resource objects.
for line in get_resource_object_doc_lines():
yield line | python | def _render_rst(self): # pragma: no cover
"""Render lines of reStructuredText for items yielded by
:meth:`~doctor.docs.base.BaseHarness.iter_annotations`.
"""
# Create a mapping of headers to annotations. We want to group
# all annotations by a header, but they could be in multiple handlers
# so we create a map of them here with the heading as the key and
# the list of associated annotations as a list. This is so we can
# sort them alphabetically to make reading the api docs easier.
heading_to_annotations_map = defaultdict(list)
for heading, route, handler, annotations in (
self.harness.iter_annotations()):
# Set the route and handler as attributes so we can retrieve them
# when we loop through them all below.
for annotation in annotations:
annotation.route = route
annotation.handler = handler
heading_to_annotations_map[heading].append(annotation)
headings = list(heading_to_annotations_map.keys())
headings.sort()
previous_heading = None
for heading in headings:
annotations = heading_to_annotations_map.get(heading)
# Sort all the annotations by title.
annotations.sort(key=lambda a: a.title)
# Only emit a new heading if the resource has changed. This
# esnures that documented endpoints for the same resource all
# end up under a single heading.
if previous_heading != heading:
previous_heading = heading
yield HEADING_TOKEN + heading
for annotation in annotations:
route = annotation.route
normalized_route = normalize_route(route)
handler = annotation.handler
# Adds a title for the endpoint.
if annotation.title is not None:
yield annotation.title
yield '#' * len(annotation.title)
docstring = get_description_lines(getattr(annotation.logic,
'__doc__', None))
# Documents the logic function associated with the annotation.
docstring.append(':Logic Func: :func:`~{}.{}`'.format(
annotation.logic.__module__, annotation.logic.__name__))
field = '<json'
if annotation.http_method in ('DELETE', 'GET'):
field = 'query'
docstring.extend(get_json_lines(
annotation, field=field, route=normalized_route,
request=True)
)
# Document any request headers.
defined_headers = list(self.harness._get_headers(
str(route), annotation).keys())
defined_headers.sort()
for header in defined_headers:
definition = self.harness.header_definitions.get(
header, '').strip()
docstring.append(':reqheader {}: {}'.format(
header, definition))
# Document response if a type was defined.
if annotation.return_annotation != Parameter.empty:
docstring.extend(get_json_lines(
annotation, field='>json', route=normalized_route))
docstring.extend(self._make_example(route, handler, annotation))
for line in http_directive(annotation.http_method,
normalized_route, docstring):
yield line
# Document resource objects.
for line in get_resource_object_doc_lines():
yield line | [
"def",
"_render_rst",
"(",
"self",
")",
":",
"# pragma: no cover",
"# Create a mapping of headers to annotations. We want to group",
"# all annotations by a header, but they could be in multiple handlers",
"# so we create a map of them here with the heading as the key and",
"# the list of associated annotations as a list. This is so we can",
"# sort them alphabetically to make reading the api docs easier.",
"heading_to_annotations_map",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"heading",
",",
"route",
",",
"handler",
",",
"annotations",
"in",
"(",
"self",
".",
"harness",
".",
"iter_annotations",
"(",
")",
")",
":",
"# Set the route and handler as attributes so we can retrieve them",
"# when we loop through them all below.",
"for",
"annotation",
"in",
"annotations",
":",
"annotation",
".",
"route",
"=",
"route",
"annotation",
".",
"handler",
"=",
"handler",
"heading_to_annotations_map",
"[",
"heading",
"]",
".",
"append",
"(",
"annotation",
")",
"headings",
"=",
"list",
"(",
"heading_to_annotations_map",
".",
"keys",
"(",
")",
")",
"headings",
".",
"sort",
"(",
")",
"previous_heading",
"=",
"None",
"for",
"heading",
"in",
"headings",
":",
"annotations",
"=",
"heading_to_annotations_map",
".",
"get",
"(",
"heading",
")",
"# Sort all the annotations by title.",
"annotations",
".",
"sort",
"(",
"key",
"=",
"lambda",
"a",
":",
"a",
".",
"title",
")",
"# Only emit a new heading if the resource has changed. This",
"# esnures that documented endpoints for the same resource all",
"# end up under a single heading.",
"if",
"previous_heading",
"!=",
"heading",
":",
"previous_heading",
"=",
"heading",
"yield",
"HEADING_TOKEN",
"+",
"heading",
"for",
"annotation",
"in",
"annotations",
":",
"route",
"=",
"annotation",
".",
"route",
"normalized_route",
"=",
"normalize_route",
"(",
"route",
")",
"handler",
"=",
"annotation",
".",
"handler",
"# Adds a title for the endpoint.",
"if",
"annotation",
".",
"title",
"is",
"not",
"None",
":",
"yield",
"annotation",
".",
"title",
"yield",
"'#'",
"*",
"len",
"(",
"annotation",
".",
"title",
")",
"docstring",
"=",
"get_description_lines",
"(",
"getattr",
"(",
"annotation",
".",
"logic",
",",
"'__doc__'",
",",
"None",
")",
")",
"# Documents the logic function associated with the annotation.",
"docstring",
".",
"append",
"(",
"':Logic Func: :func:`~{}.{}`'",
".",
"format",
"(",
"annotation",
".",
"logic",
".",
"__module__",
",",
"annotation",
".",
"logic",
".",
"__name__",
")",
")",
"field",
"=",
"'<json'",
"if",
"annotation",
".",
"http_method",
"in",
"(",
"'DELETE'",
",",
"'GET'",
")",
":",
"field",
"=",
"'query'",
"docstring",
".",
"extend",
"(",
"get_json_lines",
"(",
"annotation",
",",
"field",
"=",
"field",
",",
"route",
"=",
"normalized_route",
",",
"request",
"=",
"True",
")",
")",
"# Document any request headers.",
"defined_headers",
"=",
"list",
"(",
"self",
".",
"harness",
".",
"_get_headers",
"(",
"str",
"(",
"route",
")",
",",
"annotation",
")",
".",
"keys",
"(",
")",
")",
"defined_headers",
".",
"sort",
"(",
")",
"for",
"header",
"in",
"defined_headers",
":",
"definition",
"=",
"self",
".",
"harness",
".",
"header_definitions",
".",
"get",
"(",
"header",
",",
"''",
")",
".",
"strip",
"(",
")",
"docstring",
".",
"append",
"(",
"':reqheader {}: {}'",
".",
"format",
"(",
"header",
",",
"definition",
")",
")",
"# Document response if a type was defined.",
"if",
"annotation",
".",
"return_annotation",
"!=",
"Parameter",
".",
"empty",
":",
"docstring",
".",
"extend",
"(",
"get_json_lines",
"(",
"annotation",
",",
"field",
"=",
"'>json'",
",",
"route",
"=",
"normalized_route",
")",
")",
"docstring",
".",
"extend",
"(",
"self",
".",
"_make_example",
"(",
"route",
",",
"handler",
",",
"annotation",
")",
")",
"for",
"line",
"in",
"http_directive",
"(",
"annotation",
".",
"http_method",
",",
"normalized_route",
",",
"docstring",
")",
":",
"yield",
"line",
"# Document resource objects.",
"for",
"line",
"in",
"get_resource_object_doc_lines",
"(",
")",
":",
"yield",
"line"
] | Render lines of reStructuredText for items yielded by
:meth:`~doctor.docs.base.BaseHarness.iter_annotations`. | [
"Render",
"lines",
"of",
"reStructuredText",
"for",
"items",
"yielded",
"by",
":",
"meth",
":",
"~doctor",
".",
"docs",
".",
"base",
".",
"BaseHarness",
".",
"iter_annotations",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L563-L640 |
upsight/doctor | doctor/docs/base.py | BaseDirective.run | def run(self): # pragma: no cover
"""Called by Sphinx to generate documentation for this directive."""
if self.directive_name is None:
raise NotImplementedError('directive_name must be implemented by '
'subclasses of BaseDirective')
env, state = self._prepare_env()
state.doc_names.add(env.docname)
directive_name = '<{}>'.format(self.directive_name)
node = nodes.section()
node.document = self.state.document
result = ViewList()
for line in self._render_rst():
if line.startswith(HEADING_TOKEN):
# Remove heading token, then append 2 lines, one with
# the heading text, and the other with the dashes to
# underline the heading.
heading = line[HEADING_TOKEN_LENGTH:]
result.append(heading, directive_name)
result.append('-' * len(heading), directive_name)
else:
result.append(line, directive_name)
nested_parse_with_titles(self.state, result, node)
return node.children | python | def run(self): # pragma: no cover
"""Called by Sphinx to generate documentation for this directive."""
if self.directive_name is None:
raise NotImplementedError('directive_name must be implemented by '
'subclasses of BaseDirective')
env, state = self._prepare_env()
state.doc_names.add(env.docname)
directive_name = '<{}>'.format(self.directive_name)
node = nodes.section()
node.document = self.state.document
result = ViewList()
for line in self._render_rst():
if line.startswith(HEADING_TOKEN):
# Remove heading token, then append 2 lines, one with
# the heading text, and the other with the dashes to
# underline the heading.
heading = line[HEADING_TOKEN_LENGTH:]
result.append(heading, directive_name)
result.append('-' * len(heading), directive_name)
else:
result.append(line, directive_name)
nested_parse_with_titles(self.state, result, node)
return node.children | [
"def",
"run",
"(",
"self",
")",
":",
"# pragma: no cover",
"if",
"self",
".",
"directive_name",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'directive_name must be implemented by '",
"'subclasses of BaseDirective'",
")",
"env",
",",
"state",
"=",
"self",
".",
"_prepare_env",
"(",
")",
"state",
".",
"doc_names",
".",
"add",
"(",
"env",
".",
"docname",
")",
"directive_name",
"=",
"'<{}>'",
".",
"format",
"(",
"self",
".",
"directive_name",
")",
"node",
"=",
"nodes",
".",
"section",
"(",
")",
"node",
".",
"document",
"=",
"self",
".",
"state",
".",
"document",
"result",
"=",
"ViewList",
"(",
")",
"for",
"line",
"in",
"self",
".",
"_render_rst",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"HEADING_TOKEN",
")",
":",
"# Remove heading token, then append 2 lines, one with",
"# the heading text, and the other with the dashes to",
"# underline the heading.",
"heading",
"=",
"line",
"[",
"HEADING_TOKEN_LENGTH",
":",
"]",
"result",
".",
"append",
"(",
"heading",
",",
"directive_name",
")",
"result",
".",
"append",
"(",
"'-'",
"*",
"len",
"(",
"heading",
")",
",",
"directive_name",
")",
"else",
":",
"result",
".",
"append",
"(",
"line",
",",
"directive_name",
")",
"nested_parse_with_titles",
"(",
"self",
".",
"state",
",",
"result",
",",
"node",
")",
"return",
"node",
".",
"children"
] | Called by Sphinx to generate documentation for this directive. | [
"Called",
"by",
"Sphinx",
"to",
"generate",
"documentation",
"for",
"this",
"directive",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L642-L664 |
upsight/doctor | doctor/docs/base.py | BaseDirective.get_outdated_docs | def get_outdated_docs(
cls, app, env, added, changed, removed): # pragma: no cover
"""Handler for Sphinx's env-get-outdated event.
This handler gives a Sphinx extension a chance to indicate that some
set of documents are out of date and need to be re-rendered. The
implementation here is stupid, for now, and always says that anything
that uses the directive needs to be re-rendered.
We should make it smarter, at some point, and have it figure out which
modules are used by the associated handlers, and whether they have
actually been updated since the last time the given document was
rendered.
"""
state = getattr(env, cls.directive_name, None)
if state and state.doc_names:
# This is stupid for now, and always says everything that uses
# this autodoc generation needs to be updated. We should make this
# smarter at some point and actually figure out what modules are
# touched, and whether they have been changed.
return sorted(state.doc_names)
else:
return [] | python | def get_outdated_docs(
cls, app, env, added, changed, removed): # pragma: no cover
"""Handler for Sphinx's env-get-outdated event.
This handler gives a Sphinx extension a chance to indicate that some
set of documents are out of date and need to be re-rendered. The
implementation here is stupid, for now, and always says that anything
that uses the directive needs to be re-rendered.
We should make it smarter, at some point, and have it figure out which
modules are used by the associated handlers, and whether they have
actually been updated since the last time the given document was
rendered.
"""
state = getattr(env, cls.directive_name, None)
if state and state.doc_names:
# This is stupid for now, and always says everything that uses
# this autodoc generation needs to be updated. We should make this
# smarter at some point and actually figure out what modules are
# touched, and whether they have been changed.
return sorted(state.doc_names)
else:
return [] | [
"def",
"get_outdated_docs",
"(",
"cls",
",",
"app",
",",
"env",
",",
"added",
",",
"changed",
",",
"removed",
")",
":",
"# pragma: no cover",
"state",
"=",
"getattr",
"(",
"env",
",",
"cls",
".",
"directive_name",
",",
"None",
")",
"if",
"state",
"and",
"state",
".",
"doc_names",
":",
"# This is stupid for now, and always says everything that uses",
"# this autodoc generation needs to be updated. We should make this",
"# smarter at some point and actually figure out what modules are",
"# touched, and whether they have been changed.",
"return",
"sorted",
"(",
"state",
".",
"doc_names",
")",
"else",
":",
"return",
"[",
"]"
] | Handler for Sphinx's env-get-outdated event.
This handler gives a Sphinx extension a chance to indicate that some
set of documents are out of date and need to be re-rendered. The
implementation here is stupid, for now, and always says that anything
that uses the directive needs to be re-rendered.
We should make it smarter, at some point, and have it figure out which
modules are used by the associated handlers, and whether they have
actually been updated since the last time the given document was
rendered. | [
"Handler",
"for",
"Sphinx",
"s",
"env",
"-",
"get",
"-",
"outdated",
"event",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L667-L689 |
upsight/doctor | doctor/docs/base.py | BaseDirective.purge_docs | def purge_docs(cls, app, env, docname): # pragma: no cover
"""Handler for Sphinx's env-purge-doc event.
This event is emitted when all traces of a source file should be cleaned
from the environment (that is, if the source file is removed, or before
it is freshly read). This is for extensions that keep their own caches
in attributes of the environment.
For example, there is a cache of all modules on the environment. When a
source file has been changed, the cache's entries for the file are
cleared, since the module declarations could have been removed from the
file.
"""
state = getattr(env, cls.directive_name, None)
if state and docname in state.doc_names:
state.doc_names.remove(docname) | python | def purge_docs(cls, app, env, docname): # pragma: no cover
"""Handler for Sphinx's env-purge-doc event.
This event is emitted when all traces of a source file should be cleaned
from the environment (that is, if the source file is removed, or before
it is freshly read). This is for extensions that keep their own caches
in attributes of the environment.
For example, there is a cache of all modules on the environment. When a
source file has been changed, the cache's entries for the file are
cleared, since the module declarations could have been removed from the
file.
"""
state = getattr(env, cls.directive_name, None)
if state and docname in state.doc_names:
state.doc_names.remove(docname) | [
"def",
"purge_docs",
"(",
"cls",
",",
"app",
",",
"env",
",",
"docname",
")",
":",
"# pragma: no cover",
"state",
"=",
"getattr",
"(",
"env",
",",
"cls",
".",
"directive_name",
",",
"None",
")",
"if",
"state",
"and",
"docname",
"in",
"state",
".",
"doc_names",
":",
"state",
".",
"doc_names",
".",
"remove",
"(",
"docname",
")"
] | Handler for Sphinx's env-purge-doc event.
This event is emitted when all traces of a source file should be cleaned
from the environment (that is, if the source file is removed, or before
it is freshly read). This is for extensions that keep their own caches
in attributes of the environment.
For example, there is a cache of all modules on the environment. When a
source file has been changed, the cache's entries for the file are
cleared, since the module declarations could have been removed from the
file. | [
"Handler",
"for",
"Sphinx",
"s",
"env",
"-",
"purge",
"-",
"doc",
"event",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L692-L707 |
upsight/doctor | doctor/docs/base.py | BaseDirective.setup | def setup(cls, app): # pragma: no cover
"""Called by Sphinx to setup an extension."""
if cls.directive_name is None:
raise NotImplementedError('directive_name must be set by '
'subclasses of BaseDirective')
if not app.registry.has_domain('http'):
setup_httpdomain(app)
app.add_config_value('{}_harness'.format(cls.directive_name),
None, 'env')
app.add_directive(cls.directive_name, cls)
app.connect('builder-inited', cls.run_setup)
app.connect('build-finished', cls.run_teardown)
app.connect('env-get-outdated', cls.get_outdated_docs)
app.connect('env-purge-doc', cls.purge_docs) | python | def setup(cls, app): # pragma: no cover
"""Called by Sphinx to setup an extension."""
if cls.directive_name is None:
raise NotImplementedError('directive_name must be set by '
'subclasses of BaseDirective')
if not app.registry.has_domain('http'):
setup_httpdomain(app)
app.add_config_value('{}_harness'.format(cls.directive_name),
None, 'env')
app.add_directive(cls.directive_name, cls)
app.connect('builder-inited', cls.run_setup)
app.connect('build-finished', cls.run_teardown)
app.connect('env-get-outdated', cls.get_outdated_docs)
app.connect('env-purge-doc', cls.purge_docs) | [
"def",
"setup",
"(",
"cls",
",",
"app",
")",
":",
"# pragma: no cover",
"if",
"cls",
".",
"directive_name",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'directive_name must be set by '",
"'subclasses of BaseDirective'",
")",
"if",
"not",
"app",
".",
"registry",
".",
"has_domain",
"(",
"'http'",
")",
":",
"setup_httpdomain",
"(",
"app",
")",
"app",
".",
"add_config_value",
"(",
"'{}_harness'",
".",
"format",
"(",
"cls",
".",
"directive_name",
")",
",",
"None",
",",
"'env'",
")",
"app",
".",
"add_directive",
"(",
"cls",
".",
"directive_name",
",",
"cls",
")",
"app",
".",
"connect",
"(",
"'builder-inited'",
",",
"cls",
".",
"run_setup",
")",
"app",
".",
"connect",
"(",
"'build-finished'",
",",
"cls",
".",
"run_teardown",
")",
"app",
".",
"connect",
"(",
"'env-get-outdated'",
",",
"cls",
".",
"get_outdated_docs",
")",
"app",
".",
"connect",
"(",
"'env-purge-doc'",
",",
"cls",
".",
"purge_docs",
")"
] | Called by Sphinx to setup an extension. | [
"Called",
"by",
"Sphinx",
"to",
"setup",
"an",
"extension",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L723-L736 |
upsight/doctor | doctor/docs/base.py | BaseHarness.define_header_values | def define_header_values(self, http_method, route, values, update=False):
"""Define header values for a given request.
By default, header values are determined from the class attribute
`headers`. But if you want to change the headers used in the
documentation for a specific route, this method lets you do that.
:param str http_method: An HTTP method, like "get".
:param str route: The route to match.
:param dict values: A dictionary of headers for the example request.
:param bool update: If True, the values will be merged into the default
headers for the request. If False, the values will replace
the default headers.
"""
self.defined_header_values[(http_method.lower(), route)] = {
'update': update,
'values': values
} | python | def define_header_values(self, http_method, route, values, update=False):
"""Define header values for a given request.
By default, header values are determined from the class attribute
`headers`. But if you want to change the headers used in the
documentation for a specific route, this method lets you do that.
:param str http_method: An HTTP method, like "get".
:param str route: The route to match.
:param dict values: A dictionary of headers for the example request.
:param bool update: If True, the values will be merged into the default
headers for the request. If False, the values will replace
the default headers.
"""
self.defined_header_values[(http_method.lower(), route)] = {
'update': update,
'values': values
} | [
"def",
"define_header_values",
"(",
"self",
",",
"http_method",
",",
"route",
",",
"values",
",",
"update",
"=",
"False",
")",
":",
"self",
".",
"defined_header_values",
"[",
"(",
"http_method",
".",
"lower",
"(",
")",
",",
"route",
")",
"]",
"=",
"{",
"'update'",
":",
"update",
",",
"'values'",
":",
"values",
"}"
] | Define header values for a given request.
By default, header values are determined from the class attribute
`headers`. But if you want to change the headers used in the
documentation for a specific route, this method lets you do that.
:param str http_method: An HTTP method, like "get".
:param str route: The route to match.
:param dict values: A dictionary of headers for the example request.
:param bool update: If True, the values will be merged into the default
headers for the request. If False, the values will replace
the default headers. | [
"Define",
"header",
"values",
"for",
"a",
"given",
"request",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L768-L785 |
upsight/doctor | doctor/docs/base.py | BaseHarness.define_example_values | def define_example_values(self, http_method, route, values, update=False):
"""Define example values for a given request.
By default, example values are determined from the example properties
in the schema. But if you want to change the example used in the
documentation for a specific route, and this method lets you do that.
:param str http_method: An HTTP method, like "get".
:param str route: The route to match.
:param dict values: A dictionary of parameters for the example request.
:param bool update: If True, the values will be merged into the default
example values for the request. If False, the values will replace
the default example values.
"""
self.defined_example_values[(http_method.lower(), route)] = {
'update': update,
'values': values
} | python | def define_example_values(self, http_method, route, values, update=False):
"""Define example values for a given request.
By default, example values are determined from the example properties
in the schema. But if you want to change the example used in the
documentation for a specific route, and this method lets you do that.
:param str http_method: An HTTP method, like "get".
:param str route: The route to match.
:param dict values: A dictionary of parameters for the example request.
:param bool update: If True, the values will be merged into the default
example values for the request. If False, the values will replace
the default example values.
"""
self.defined_example_values[(http_method.lower(), route)] = {
'update': update,
'values': values
} | [
"def",
"define_example_values",
"(",
"self",
",",
"http_method",
",",
"route",
",",
"values",
",",
"update",
"=",
"False",
")",
":",
"self",
".",
"defined_example_values",
"[",
"(",
"http_method",
".",
"lower",
"(",
")",
",",
"route",
")",
"]",
"=",
"{",
"'update'",
":",
"update",
",",
"'values'",
":",
"values",
"}"
] | Define example values for a given request.
By default, example values are determined from the example properties
in the schema. But if you want to change the example used in the
documentation for a specific route, and this method lets you do that.
:param str http_method: An HTTP method, like "get".
:param str route: The route to match.
:param dict values: A dictionary of parameters for the example request.
:param bool update: If True, the values will be merged into the default
example values for the request. If False, the values will replace
the default example values. | [
"Define",
"example",
"values",
"for",
"a",
"given",
"request",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L787-L804 |
upsight/doctor | doctor/docs/base.py | BaseHarness._get_annotation_heading | def _get_annotation_heading(self, handler, route, heading=None):
"""Returns the heading text for an annotation.
Attempts to get the name of the heading from the handler attribute
`schematic_title` first.
If `schematic_title` it is not present, it attempts to generate
the title from the class path.
This path: advertiser_api.handlers.foo_bar.FooListHandler
would translate to 'Foo Bar'
If the file name with the resource is generically named handlers.py
or it doesn't have a full path then we attempt to get the resource
name from the class name.
So FooListHandler and FooHandler would translate to 'Foo'.
If the handler class name starts with 'Internal', then that will
be appended to the heading.
So InternalFooListHandler would translate to 'Foo (Internal)'
:param mixed handler: The handler class. Will be a flask resource class
:param str route: The route to the handler.
:returns: The text for the heading as a string.
"""
if hasattr(handler, '_doctor_heading'):
return handler._doctor_heading
heading = ''
handler_path = str(handler)
try:
handler_file_name = handler_path.split('.')[-2]
except IndexError:
# In the event there is no path and we just have the class name,
# get heading from the class name by setting us up to enter the
# first if statement.
handler_file_name = 'handler'
# Get heading from class name
if handler_file_name.startswith('handler'):
class_name = handler_path.split('.')[-1]
internal = False
for word in CAMEL_CASE_RE.findall(class_name):
if word == 'Internal':
internal = True
continue
elif word.startswith(('List', 'Handler', 'Resource')):
# We've hit the end of the class name that contains
# words we are interested in.
break
heading += '%s ' % (word,)
if internal:
heading = heading.strip()
heading += ' (Internal)'
# Get heading from handler file name
else:
heading = ' '.join(handler_file_name.split('_')).title()
if 'internal' in route:
heading += ' (Internal)'
return heading.strip() | python | def _get_annotation_heading(self, handler, route, heading=None):
"""Returns the heading text for an annotation.
Attempts to get the name of the heading from the handler attribute
`schematic_title` first.
If `schematic_title` it is not present, it attempts to generate
the title from the class path.
This path: advertiser_api.handlers.foo_bar.FooListHandler
would translate to 'Foo Bar'
If the file name with the resource is generically named handlers.py
or it doesn't have a full path then we attempt to get the resource
name from the class name.
So FooListHandler and FooHandler would translate to 'Foo'.
If the handler class name starts with 'Internal', then that will
be appended to the heading.
So InternalFooListHandler would translate to 'Foo (Internal)'
:param mixed handler: The handler class. Will be a flask resource class
:param str route: The route to the handler.
:returns: The text for the heading as a string.
"""
if hasattr(handler, '_doctor_heading'):
return handler._doctor_heading
heading = ''
handler_path = str(handler)
try:
handler_file_name = handler_path.split('.')[-2]
except IndexError:
# In the event there is no path and we just have the class name,
# get heading from the class name by setting us up to enter the
# first if statement.
handler_file_name = 'handler'
# Get heading from class name
if handler_file_name.startswith('handler'):
class_name = handler_path.split('.')[-1]
internal = False
for word in CAMEL_CASE_RE.findall(class_name):
if word == 'Internal':
internal = True
continue
elif word.startswith(('List', 'Handler', 'Resource')):
# We've hit the end of the class name that contains
# words we are interested in.
break
heading += '%s ' % (word,)
if internal:
heading = heading.strip()
heading += ' (Internal)'
# Get heading from handler file name
else:
heading = ' '.join(handler_file_name.split('_')).title()
if 'internal' in route:
heading += ' (Internal)'
return heading.strip() | [
"def",
"_get_annotation_heading",
"(",
"self",
",",
"handler",
",",
"route",
",",
"heading",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"handler",
",",
"'_doctor_heading'",
")",
":",
"return",
"handler",
".",
"_doctor_heading",
"heading",
"=",
"''",
"handler_path",
"=",
"str",
"(",
"handler",
")",
"try",
":",
"handler_file_name",
"=",
"handler_path",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"2",
"]",
"except",
"IndexError",
":",
"# In the event there is no path and we just have the class name,",
"# get heading from the class name by setting us up to enter the",
"# first if statement.",
"handler_file_name",
"=",
"'handler'",
"# Get heading from class name",
"if",
"handler_file_name",
".",
"startswith",
"(",
"'handler'",
")",
":",
"class_name",
"=",
"handler_path",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"internal",
"=",
"False",
"for",
"word",
"in",
"CAMEL_CASE_RE",
".",
"findall",
"(",
"class_name",
")",
":",
"if",
"word",
"==",
"'Internal'",
":",
"internal",
"=",
"True",
"continue",
"elif",
"word",
".",
"startswith",
"(",
"(",
"'List'",
",",
"'Handler'",
",",
"'Resource'",
")",
")",
":",
"# We've hit the end of the class name that contains",
"# words we are interested in.",
"break",
"heading",
"+=",
"'%s '",
"%",
"(",
"word",
",",
")",
"if",
"internal",
":",
"heading",
"=",
"heading",
".",
"strip",
"(",
")",
"heading",
"+=",
"' (Internal)'",
"# Get heading from handler file name",
"else",
":",
"heading",
"=",
"' '",
".",
"join",
"(",
"handler_file_name",
".",
"split",
"(",
"'_'",
")",
")",
".",
"title",
"(",
")",
"if",
"'internal'",
"in",
"route",
":",
"heading",
"+=",
"' (Internal)'",
"return",
"heading",
".",
"strip",
"(",
")"
] | Returns the heading text for an annotation.
Attempts to get the name of the heading from the handler attribute
`schematic_title` first.
If `schematic_title` it is not present, it attempts to generate
the title from the class path.
This path: advertiser_api.handlers.foo_bar.FooListHandler
would translate to 'Foo Bar'
If the file name with the resource is generically named handlers.py
or it doesn't have a full path then we attempt to get the resource
name from the class name.
So FooListHandler and FooHandler would translate to 'Foo'.
If the handler class name starts with 'Internal', then that will
be appended to the heading.
So InternalFooListHandler would translate to 'Foo (Internal)'
:param mixed handler: The handler class. Will be a flask resource class
:param str route: The route to the handler.
:returns: The text for the heading as a string. | [
"Returns",
"the",
"heading",
"text",
"for",
"an",
"annotation",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L856-L913 |
upsight/doctor | doctor/docs/base.py | BaseHarness._get_headers | def _get_headers(self, route: str, annotation: ResourceAnnotation) -> Dict:
"""Gets headers for the provided route.
:param route: The route to get example values for.
:type route: werkzeug.routing.Rule for a flask api.
:param annotation: Schema annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnotation
:retruns: A dict containing headers.
"""
headers = self.headers.copy()
defined_header_values = self.defined_header_values.get(
(annotation.http_method.lower(), str(route)))
if defined_header_values is not None:
if defined_header_values['update']:
headers.update(defined_header_values['values'])
else:
headers = defined_header_values['values']
return headers | python | def _get_headers(self, route: str, annotation: ResourceAnnotation) -> Dict:
"""Gets headers for the provided route.
:param route: The route to get example values for.
:type route: werkzeug.routing.Rule for a flask api.
:param annotation: Schema annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnotation
:retruns: A dict containing headers.
"""
headers = self.headers.copy()
defined_header_values = self.defined_header_values.get(
(annotation.http_method.lower(), str(route)))
if defined_header_values is not None:
if defined_header_values['update']:
headers.update(defined_header_values['values'])
else:
headers = defined_header_values['values']
return headers | [
"def",
"_get_headers",
"(",
"self",
",",
"route",
":",
"str",
",",
"annotation",
":",
"ResourceAnnotation",
")",
"->",
"Dict",
":",
"headers",
"=",
"self",
".",
"headers",
".",
"copy",
"(",
")",
"defined_header_values",
"=",
"self",
".",
"defined_header_values",
".",
"get",
"(",
"(",
"annotation",
".",
"http_method",
".",
"lower",
"(",
")",
",",
"str",
"(",
"route",
")",
")",
")",
"if",
"defined_header_values",
"is",
"not",
"None",
":",
"if",
"defined_header_values",
"[",
"'update'",
"]",
":",
"headers",
".",
"update",
"(",
"defined_header_values",
"[",
"'values'",
"]",
")",
"else",
":",
"headers",
"=",
"defined_header_values",
"[",
"'values'",
"]",
"return",
"headers"
] | Gets headers for the provided route.
:param route: The route to get example values for.
:type route: werkzeug.routing.Rule for a flask api.
:param annotation: Schema annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnotation
:retruns: A dict containing headers. | [
"Gets",
"headers",
"for",
"the",
"provided",
"route",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L915-L932 |
upsight/doctor | doctor/docs/base.py | BaseHarness._get_example_values | def _get_example_values(self, route: str,
annotation: ResourceAnnotation) -> Dict[str, Any]:
"""Gets example values for all properties in the annotation's schema.
:param route: The route to get example values for.
:type route: werkzeug.routing.Rule for a flask api.
:param annotation: Schema annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnotation
:retruns: A dict containing property names as keys and example values
as values.
"""
defined_values = self.defined_example_values.get(
(annotation.http_method.lower(), str(route)))
if defined_values and not defined_values['update']:
return defined_values['values']
# If we defined a req_obj_type for the logic, use that type's
# example values instead of the annotated parameters.
if annotation.logic._doctor_req_obj_type:
values = annotation.logic._doctor_req_obj_type.get_example()
else:
values = {
k: v.annotation.get_example()
for k, v in annotation.annotated_parameters.items()
}
if defined_values:
values.update(defined_values['values'])
# If this is a GET route, we need to json dumps any parameters that
# are lists or dicts. Otherwise we'll get a 400 error for those params
if annotation.http_method == 'GET':
for k, v in values.items():
if isinstance(v, (list, dict)):
values[k] = json.dumps(v)
return values | python | def _get_example_values(self, route: str,
annotation: ResourceAnnotation) -> Dict[str, Any]:
"""Gets example values for all properties in the annotation's schema.
:param route: The route to get example values for.
:type route: werkzeug.routing.Rule for a flask api.
:param annotation: Schema annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnotation
:retruns: A dict containing property names as keys and example values
as values.
"""
defined_values = self.defined_example_values.get(
(annotation.http_method.lower(), str(route)))
if defined_values and not defined_values['update']:
return defined_values['values']
# If we defined a req_obj_type for the logic, use that type's
# example values instead of the annotated parameters.
if annotation.logic._doctor_req_obj_type:
values = annotation.logic._doctor_req_obj_type.get_example()
else:
values = {
k: v.annotation.get_example()
for k, v in annotation.annotated_parameters.items()
}
if defined_values:
values.update(defined_values['values'])
# If this is a GET route, we need to json dumps any parameters that
# are lists or dicts. Otherwise we'll get a 400 error for those params
if annotation.http_method == 'GET':
for k, v in values.items():
if isinstance(v, (list, dict)):
values[k] = json.dumps(v)
return values | [
"def",
"_get_example_values",
"(",
"self",
",",
"route",
":",
"str",
",",
"annotation",
":",
"ResourceAnnotation",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"defined_values",
"=",
"self",
".",
"defined_example_values",
".",
"get",
"(",
"(",
"annotation",
".",
"http_method",
".",
"lower",
"(",
")",
",",
"str",
"(",
"route",
")",
")",
")",
"if",
"defined_values",
"and",
"not",
"defined_values",
"[",
"'update'",
"]",
":",
"return",
"defined_values",
"[",
"'values'",
"]",
"# If we defined a req_obj_type for the logic, use that type's",
"# example values instead of the annotated parameters.",
"if",
"annotation",
".",
"logic",
".",
"_doctor_req_obj_type",
":",
"values",
"=",
"annotation",
".",
"logic",
".",
"_doctor_req_obj_type",
".",
"get_example",
"(",
")",
"else",
":",
"values",
"=",
"{",
"k",
":",
"v",
".",
"annotation",
".",
"get_example",
"(",
")",
"for",
"k",
",",
"v",
"in",
"annotation",
".",
"annotated_parameters",
".",
"items",
"(",
")",
"}",
"if",
"defined_values",
":",
"values",
".",
"update",
"(",
"defined_values",
"[",
"'values'",
"]",
")",
"# If this is a GET route, we need to json dumps any parameters that",
"# are lists or dicts. Otherwise we'll get a 400 error for those params",
"if",
"annotation",
".",
"http_method",
"==",
"'GET'",
":",
"for",
"k",
",",
"v",
"in",
"values",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"values",
"[",
"k",
"]",
"=",
"json",
".",
"dumps",
"(",
"v",
")",
"return",
"values"
] | Gets example values for all properties in the annotation's schema.
:param route: The route to get example values for.
:type route: werkzeug.routing.Rule for a flask api.
:param annotation: Schema annotation for the method to be requested.
:type annotation: doctor.resource.ResourceAnnotation
:retruns: A dict containing property names as keys and example values
as values. | [
"Gets",
"example",
"values",
"for",
"all",
"properties",
"in",
"the",
"annotation",
"s",
"schema",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/docs/base.py#L934-L968 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/autoload/device_names.py | get_device_name | def get_device_name(file_name, sys_obj_id, delimiter=":"):
"""Get device name by its SNMP sysObjectID property from the file map
:param str file_name:
:param str sys_obj_id:
:param str delimiter:
:rtype: str
"""
try:
with open(file_name, "rb") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=delimiter)
for row in csv_reader:
if len(row) >= 2 and row[0] == sys_obj_id:
return row[1]
except IOError:
pass # file does not exists
return sys_obj_id | python | def get_device_name(file_name, sys_obj_id, delimiter=":"):
"""Get device name by its SNMP sysObjectID property from the file map
:param str file_name:
:param str sys_obj_id:
:param str delimiter:
:rtype: str
"""
try:
with open(file_name, "rb") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=delimiter)
for row in csv_reader:
if len(row) >= 2 and row[0] == sys_obj_id:
return row[1]
except IOError:
pass # file does not exists
return sys_obj_id | [
"def",
"get_device_name",
"(",
"file_name",
",",
"sys_obj_id",
",",
"delimiter",
"=",
"\":\"",
")",
":",
"try",
":",
"with",
"open",
"(",
"file_name",
",",
"\"rb\"",
")",
"as",
"csv_file",
":",
"csv_reader",
"=",
"csv",
".",
"reader",
"(",
"csv_file",
",",
"delimiter",
"=",
"delimiter",
")",
"for",
"row",
"in",
"csv_reader",
":",
"if",
"len",
"(",
"row",
")",
">=",
"2",
"and",
"row",
"[",
"0",
"]",
"==",
"sys_obj_id",
":",
"return",
"row",
"[",
"1",
"]",
"except",
"IOError",
":",
"pass",
"# file does not exists",
"return",
"sys_obj_id"
] | Get device name by its SNMP sysObjectID property from the file map
:param str file_name:
:param str sys_obj_id:
:param str delimiter:
:rtype: str | [
"Get",
"device",
"name",
"by",
"its",
"SNMP",
"sysObjectID",
"property",
"from",
"the",
"file",
"map"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/autoload/device_names.py#L4-L22 |
horejsek/python-sqlpuzzle | sqlpuzzle/_queries/select.py | Select.has | def has(self, querypart_name, value=None):
"""
Returns ``True`` if ``querypart_name`` with ``value`` is set. For example
you can check if you already used condition by ``sql.has('where')``.
If you want to check for more information, for example if that condition
also contain ID, you can do this by ``sql.has('where', 'id')``.
"""
if super().has(querypart_name, value):
return True
if not value:
return super().has('select_options', querypart_name)
return False | python | def has(self, querypart_name, value=None):
"""
Returns ``True`` if ``querypart_name`` with ``value`` is set. For example
you can check if you already used condition by ``sql.has('where')``.
If you want to check for more information, for example if that condition
also contain ID, you can do this by ``sql.has('where', 'id')``.
"""
if super().has(querypart_name, value):
return True
if not value:
return super().has('select_options', querypart_name)
return False | [
"def",
"has",
"(",
"self",
",",
"querypart_name",
",",
"value",
"=",
"None",
")",
":",
"if",
"super",
"(",
")",
".",
"has",
"(",
"querypart_name",
",",
"value",
")",
":",
"return",
"True",
"if",
"not",
"value",
":",
"return",
"super",
"(",
")",
".",
"has",
"(",
"'select_options'",
",",
"querypart_name",
")",
"return",
"False"
] | Returns ``True`` if ``querypart_name`` with ``value`` is set. For example
you can check if you already used condition by ``sql.has('where')``.
If you want to check for more information, for example if that condition
also contain ID, you can do this by ``sql.has('where', 'id')``. | [
"Returns",
"True",
"if",
"querypart_name",
"with",
"value",
"is",
"set",
".",
"For",
"example",
"you",
"can",
"check",
"if",
"you",
"already",
"used",
"condition",
"by",
"sql",
".",
"has",
"(",
"where",
")",
"."
] | train | https://github.com/horejsek/python-sqlpuzzle/blob/d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd/sqlpuzzle/_queries/select.py#L61-L73 |
horejsek/python-sqlpuzzle | sqlpuzzle/_queries/select.py | Select.group_by | def group_by(self, *args, **kwds):
"""
Default ordering is ``ASC``.
``group_by`` accept ``dict`` as you would expect, but note that ``dict``
does not have same order. Same for named arguments.
.. code-block:: python
>>> sqlpuzzle.select('c').from_('t').group_by('a', ('b', 'desc'))
<Select: SELECT "c" FROM "t" GROUP BY "a", "b" DESC>
"""
self._group_by.group_by(*args, **kwds)
return self | python | def group_by(self, *args, **kwds):
"""
Default ordering is ``ASC``.
``group_by`` accept ``dict`` as you would expect, but note that ``dict``
does not have same order. Same for named arguments.
.. code-block:: python
>>> sqlpuzzle.select('c').from_('t').group_by('a', ('b', 'desc'))
<Select: SELECT "c" FROM "t" GROUP BY "a", "b" DESC>
"""
self._group_by.group_by(*args, **kwds)
return self | [
"def",
"group_by",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"self",
".",
"_group_by",
".",
"group_by",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"return",
"self"
] | Default ordering is ``ASC``.
``group_by`` accept ``dict`` as you would expect, but note that ``dict``
does not have same order. Same for named arguments.
.. code-block:: python
>>> sqlpuzzle.select('c').from_('t').group_by('a', ('b', 'desc'))
<Select: SELECT "c" FROM "t" GROUP BY "a", "b" DESC> | [
"Default",
"ordering",
"is",
"ASC",
"."
] | train | https://github.com/horejsek/python-sqlpuzzle/blob/d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd/sqlpuzzle/_queries/select.py#L146-L159 |
horejsek/python-sqlpuzzle | sqlpuzzle/_queries/select.py | Select.order_by | def order_by(self, *args, **kwds):
"""
Default ordering is ``ASC``.
``order_by`` accept ``dict`` as you would expect, but note that ``dict``
does not have same order.
.. code-block:: python
>>> sqlpuzzle.select('c').from_('t').order_by('a', ('b', 'desc'))
<Select: SELECT "c" FROM "t" ORDER BY "a", "b" DESC>
"""
self._order_by.order_by(*args, **kwds)
return self | python | def order_by(self, *args, **kwds):
"""
Default ordering is ``ASC``.
``order_by`` accept ``dict`` as you would expect, but note that ``dict``
does not have same order.
.. code-block:: python
>>> sqlpuzzle.select('c').from_('t').order_by('a', ('b', 'desc'))
<Select: SELECT "c" FROM "t" ORDER BY "a", "b" DESC>
"""
self._order_by.order_by(*args, **kwds)
return self | [
"def",
"order_by",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"self",
".",
"_order_by",
".",
"order_by",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"return",
"self"
] | Default ordering is ``ASC``.
``order_by`` accept ``dict`` as you would expect, but note that ``dict``
does not have same order.
.. code-block:: python
>>> sqlpuzzle.select('c').from_('t').order_by('a', ('b', 'desc'))
<Select: SELECT "c" FROM "t" ORDER BY "a", "b" DESC> | [
"Default",
"ordering",
"is",
"ASC",
"."
] | train | https://github.com/horejsek/python-sqlpuzzle/blob/d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd/sqlpuzzle/_queries/select.py#L161-L174 |
Workiva/furious | example/context_completion_with_results.py | context_complete | def context_complete(context_id):
"""Log out that the context is complete."""
logging.info('Context %s is.......... DONE.', context_id)
from furious.context import get_current_async_with_context
_, context = get_current_async_with_context()
if not context:
logging.error("Could not load context")
return
for task_id, result in context.result.items():
logging.info("#########################")
logging.info("Task Id: %s and Result: %s", task_id, result)
return context_id | python | def context_complete(context_id):
"""Log out that the context is complete."""
logging.info('Context %s is.......... DONE.', context_id)
from furious.context import get_current_async_with_context
_, context = get_current_async_with_context()
if not context:
logging.error("Could not load context")
return
for task_id, result in context.result.items():
logging.info("#########################")
logging.info("Task Id: %s and Result: %s", task_id, result)
return context_id | [
"def",
"context_complete",
"(",
"context_id",
")",
":",
"logging",
".",
"info",
"(",
"'Context %s is.......... DONE.'",
",",
"context_id",
")",
"from",
"furious",
".",
"context",
"import",
"get_current_async_with_context",
"_",
",",
"context",
"=",
"get_current_async_with_context",
"(",
")",
"if",
"not",
"context",
":",
"logging",
".",
"error",
"(",
"\"Could not load context\"",
")",
"return",
"for",
"task_id",
",",
"result",
"in",
"context",
".",
"result",
".",
"items",
"(",
")",
":",
"logging",
".",
"info",
"(",
"\"#########################\"",
")",
"logging",
".",
"info",
"(",
"\"Task Id: %s and Result: %s\"",
",",
"task_id",
",",
"result",
")",
"return",
"context_id"
] | Log out that the context is complete. | [
"Log",
"out",
"that",
"the",
"context",
"is",
"complete",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/context_completion_with_results.py#L63-L79 |
Workiva/furious | example/batcher/__init__.py | process_messages | def process_messages(tag, retries=0):
"""Processes the messages pulled fromm a queue based off the tag passed in.
Will insert another processor if any work was processed or the retry count
is under the max retry count. Will update a aggregated stats object with
the data in the payload of the messages processed.
:param tag: :class: `str` Tag to query the queue on
:param retry: :class: `int` Number of retries the job has processed
"""
from furious.batcher import bump_batch
from furious.batcher import MESSAGE_DEFAULT_QUEUE
from furious.batcher import MessageIterator
from furious.batcher import MessageProcessor
from google.appengine.api import memcache
# since we don't have a flag for checking complete we'll re-insert a
# processor task with a retry count to catch any work that may still be
# filtering in. If we've hit our max retry count we just bail out and
# consider the job complete.
if retries > 5:
logging.info("Process messages hit max retry and is exiting")
return
# create a message iteragor for the tag in batches of 500
message_iterator = MessageIterator(tag, MESSAGE_DEFAULT_QUEUE, 500)
client = memcache.Client()
# get the stats object from cache
stats = client.gets(tag)
# json decode it if it exists otherwise get the default state.
stats = json.loads(stats) if stats else get_default_stats()
work_processed = False
# loop through the messages pulled from the queue.
for message in message_iterator:
work_processed = True
value = int(message.get("value", 0))
color = message.get("color").lower()
# update the total stats with the value pulled
set_stats(stats["totals"], value)
# update the specific color status via the value pulled
set_stats(stats["colors"][color], value)
# insert the stats back into cache
json_stats = json.dumps(stats)
# try and do an add first to see if it's new. We can't trush get due to
# a race condition.
if not client.add(tag, json_stats):
# if we couldn't add than lets do a compare and set to safely
# update the stats
if not client.cas(tag, json_stats):
raise Exception("Transaction Collision.")
# bump the process batch id
bump_batch(tag)
if work_processed:
# reset the retries as we've processed work
retries = 0
else:
# no work was processed so increment the retries
retries += 1
# insert another processor
processor = MessageProcessor(
target=process_messages, args=("colors",),
kwargs={'retries': retries}, tag="colors")
processor.start() | python | def process_messages(tag, retries=0):
"""Processes the messages pulled fromm a queue based off the tag passed in.
Will insert another processor if any work was processed or the retry count
is under the max retry count. Will update a aggregated stats object with
the data in the payload of the messages processed.
:param tag: :class: `str` Tag to query the queue on
:param retry: :class: `int` Number of retries the job has processed
"""
from furious.batcher import bump_batch
from furious.batcher import MESSAGE_DEFAULT_QUEUE
from furious.batcher import MessageIterator
from furious.batcher import MessageProcessor
from google.appengine.api import memcache
# since we don't have a flag for checking complete we'll re-insert a
# processor task with a retry count to catch any work that may still be
# filtering in. If we've hit our max retry count we just bail out and
# consider the job complete.
if retries > 5:
logging.info("Process messages hit max retry and is exiting")
return
# create a message iteragor for the tag in batches of 500
message_iterator = MessageIterator(tag, MESSAGE_DEFAULT_QUEUE, 500)
client = memcache.Client()
# get the stats object from cache
stats = client.gets(tag)
# json decode it if it exists otherwise get the default state.
stats = json.loads(stats) if stats else get_default_stats()
work_processed = False
# loop through the messages pulled from the queue.
for message in message_iterator:
work_processed = True
value = int(message.get("value", 0))
color = message.get("color").lower()
# update the total stats with the value pulled
set_stats(stats["totals"], value)
# update the specific color status via the value pulled
set_stats(stats["colors"][color], value)
# insert the stats back into cache
json_stats = json.dumps(stats)
# try and do an add first to see if it's new. We can't trush get due to
# a race condition.
if not client.add(tag, json_stats):
# if we couldn't add than lets do a compare and set to safely
# update the stats
if not client.cas(tag, json_stats):
raise Exception("Transaction Collision.")
# bump the process batch id
bump_batch(tag)
if work_processed:
# reset the retries as we've processed work
retries = 0
else:
# no work was processed so increment the retries
retries += 1
# insert another processor
processor = MessageProcessor(
target=process_messages, args=("colors",),
kwargs={'retries': retries}, tag="colors")
processor.start() | [
"def",
"process_messages",
"(",
"tag",
",",
"retries",
"=",
"0",
")",
":",
"from",
"furious",
".",
"batcher",
"import",
"bump_batch",
"from",
"furious",
".",
"batcher",
"import",
"MESSAGE_DEFAULT_QUEUE",
"from",
"furious",
".",
"batcher",
"import",
"MessageIterator",
"from",
"furious",
".",
"batcher",
"import",
"MessageProcessor",
"from",
"google",
".",
"appengine",
".",
"api",
"import",
"memcache",
"# since we don't have a flag for checking complete we'll re-insert a",
"# processor task with a retry count to catch any work that may still be",
"# filtering in. If we've hit our max retry count we just bail out and",
"# consider the job complete.",
"if",
"retries",
">",
"5",
":",
"logging",
".",
"info",
"(",
"\"Process messages hit max retry and is exiting\"",
")",
"return",
"# create a message iteragor for the tag in batches of 500",
"message_iterator",
"=",
"MessageIterator",
"(",
"tag",
",",
"MESSAGE_DEFAULT_QUEUE",
",",
"500",
")",
"client",
"=",
"memcache",
".",
"Client",
"(",
")",
"# get the stats object from cache",
"stats",
"=",
"client",
".",
"gets",
"(",
"tag",
")",
"# json decode it if it exists otherwise get the default state.",
"stats",
"=",
"json",
".",
"loads",
"(",
"stats",
")",
"if",
"stats",
"else",
"get_default_stats",
"(",
")",
"work_processed",
"=",
"False",
"# loop through the messages pulled from the queue.",
"for",
"message",
"in",
"message_iterator",
":",
"work_processed",
"=",
"True",
"value",
"=",
"int",
"(",
"message",
".",
"get",
"(",
"\"value\"",
",",
"0",
")",
")",
"color",
"=",
"message",
".",
"get",
"(",
"\"color\"",
")",
".",
"lower",
"(",
")",
"# update the total stats with the value pulled",
"set_stats",
"(",
"stats",
"[",
"\"totals\"",
"]",
",",
"value",
")",
"# update the specific color status via the value pulled",
"set_stats",
"(",
"stats",
"[",
"\"colors\"",
"]",
"[",
"color",
"]",
",",
"value",
")",
"# insert the stats back into cache",
"json_stats",
"=",
"json",
".",
"dumps",
"(",
"stats",
")",
"# try and do an add first to see if it's new. We can't trush get due to",
"# a race condition.",
"if",
"not",
"client",
".",
"add",
"(",
"tag",
",",
"json_stats",
")",
":",
"# if we couldn't add than lets do a compare and set to safely",
"# update the stats",
"if",
"not",
"client",
".",
"cas",
"(",
"tag",
",",
"json_stats",
")",
":",
"raise",
"Exception",
"(",
"\"Transaction Collision.\"",
")",
"# bump the process batch id",
"bump_batch",
"(",
"tag",
")",
"if",
"work_processed",
":",
"# reset the retries as we've processed work",
"retries",
"=",
"0",
"else",
":",
"# no work was processed so increment the retries",
"retries",
"+=",
"1",
"# insert another processor",
"processor",
"=",
"MessageProcessor",
"(",
"target",
"=",
"process_messages",
",",
"args",
"=",
"(",
"\"colors\"",
",",
")",
",",
"kwargs",
"=",
"{",
"'retries'",
":",
"retries",
"}",
",",
"tag",
"=",
"\"colors\"",
")",
"processor",
".",
"start",
"(",
")"
] | Processes the messages pulled fromm a queue based off the tag passed in.
Will insert another processor if any work was processed or the retry count
is under the max retry count. Will update a aggregated stats object with
the data in the payload of the messages processed.
:param tag: :class: `str` Tag to query the queue on
:param retry: :class: `int` Number of retries the job has processed | [
"Processes",
"the",
"messages",
"pulled",
"fromm",
"a",
"queue",
"based",
"off",
"the",
"tag",
"passed",
"in",
".",
"Will",
"insert",
"another",
"processor",
"if",
"any",
"work",
"was",
"processed",
"or",
"the",
"retry",
"count",
"is",
"under",
"the",
"max",
"retry",
"count",
".",
"Will",
"update",
"a",
"aggregated",
"stats",
"object",
"with",
"the",
"data",
"in",
"the",
"payload",
"of",
"the",
"messages",
"processed",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/batcher/__init__.py#L125-L201 |
Workiva/furious | example/batcher/__init__.py | set_stats | def set_stats(stats, value):
"""Updates the stats with the value passed in.
:param stats: :class: `dict`
:param value: :class: `int`
"""
stats["total_count"] += 1
stats["value"] += value
stats["average"] = stats["value"] / stats["total_count"]
# this is just a basic example and not the best way to track aggregation.
# for max and min old there are cases where this will not work correctly.
if value > stats["max"]:
stats["max"] = value
if value < stats["min"] or stats["min"] == 0:
stats["min"] = value | python | def set_stats(stats, value):
"""Updates the stats with the value passed in.
:param stats: :class: `dict`
:param value: :class: `int`
"""
stats["total_count"] += 1
stats["value"] += value
stats["average"] = stats["value"] / stats["total_count"]
# this is just a basic example and not the best way to track aggregation.
# for max and min old there are cases where this will not work correctly.
if value > stats["max"]:
stats["max"] = value
if value < stats["min"] or stats["min"] == 0:
stats["min"] = value | [
"def",
"set_stats",
"(",
"stats",
",",
"value",
")",
":",
"stats",
"[",
"\"total_count\"",
"]",
"+=",
"1",
"stats",
"[",
"\"value\"",
"]",
"+=",
"value",
"stats",
"[",
"\"average\"",
"]",
"=",
"stats",
"[",
"\"value\"",
"]",
"/",
"stats",
"[",
"\"total_count\"",
"]",
"# this is just a basic example and not the best way to track aggregation.",
"# for max and min old there are cases where this will not work correctly.",
"if",
"value",
">",
"stats",
"[",
"\"max\"",
"]",
":",
"stats",
"[",
"\"max\"",
"]",
"=",
"value",
"if",
"value",
"<",
"stats",
"[",
"\"min\"",
"]",
"or",
"stats",
"[",
"\"min\"",
"]",
"==",
"0",
":",
"stats",
"[",
"\"min\"",
"]",
"=",
"value"
] | Updates the stats with the value passed in.
:param stats: :class: `dict`
:param value: :class: `int` | [
"Updates",
"the",
"stats",
"with",
"the",
"value",
"passed",
"in",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/batcher/__init__.py#L204-L220 |
Workiva/furious | example/batcher/__init__.py | get_default_stats | def get_default_stats():
"""Returns a :class: `dict` of the default stats structure."""
default_stats = {
"total_count": 0,
"max": 0,
"min": 0,
"value": 0,
"average": 0,
"last_update": None,
}
return {
"totals": default_stats,
"colors": {
"red": default_stats.copy(),
"blue": default_stats.copy(),
"yellow": default_stats.copy(),
"green": default_stats.copy(),
"black": default_stats.copy(),
}
} | python | def get_default_stats():
"""Returns a :class: `dict` of the default stats structure."""
default_stats = {
"total_count": 0,
"max": 0,
"min": 0,
"value": 0,
"average": 0,
"last_update": None,
}
return {
"totals": default_stats,
"colors": {
"red": default_stats.copy(),
"blue": default_stats.copy(),
"yellow": default_stats.copy(),
"green": default_stats.copy(),
"black": default_stats.copy(),
}
} | [
"def",
"get_default_stats",
"(",
")",
":",
"default_stats",
"=",
"{",
"\"total_count\"",
":",
"0",
",",
"\"max\"",
":",
"0",
",",
"\"min\"",
":",
"0",
",",
"\"value\"",
":",
"0",
",",
"\"average\"",
":",
"0",
",",
"\"last_update\"",
":",
"None",
",",
"}",
"return",
"{",
"\"totals\"",
":",
"default_stats",
",",
"\"colors\"",
":",
"{",
"\"red\"",
":",
"default_stats",
".",
"copy",
"(",
")",
",",
"\"blue\"",
":",
"default_stats",
".",
"copy",
"(",
")",
",",
"\"yellow\"",
":",
"default_stats",
".",
"copy",
"(",
")",
",",
"\"green\"",
":",
"default_stats",
".",
"copy",
"(",
")",
",",
"\"black\"",
":",
"default_stats",
".",
"copy",
"(",
")",
",",
"}",
"}"
] | Returns a :class: `dict` of the default stats structure. | [
"Returns",
"a",
":",
"class",
":",
"dict",
"of",
"the",
"default",
"stats",
"structure",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/example/batcher/__init__.py#L223-L244 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/networking_utils.py | serialize_to_json | def serialize_to_json(result, unpicklable=False):
"""Serializes output as JSON and writes it to console output wrapped with special prefix and suffix
:param result: Result to return
:param unpicklable: If True adds JSON can be deserialized as real object.
When False will be deserialized as dictionary
"""
json = jsonpickle.encode(result, unpicklable=unpicklable)
result_for_output = str(json)
return result_for_output | python | def serialize_to_json(result, unpicklable=False):
"""Serializes output as JSON and writes it to console output wrapped with special prefix and suffix
:param result: Result to return
:param unpicklable: If True adds JSON can be deserialized as real object.
When False will be deserialized as dictionary
"""
json = jsonpickle.encode(result, unpicklable=unpicklable)
result_for_output = str(json)
return result_for_output | [
"def",
"serialize_to_json",
"(",
"result",
",",
"unpicklable",
"=",
"False",
")",
":",
"json",
"=",
"jsonpickle",
".",
"encode",
"(",
"result",
",",
"unpicklable",
"=",
"unpicklable",
")",
"result_for_output",
"=",
"str",
"(",
"json",
")",
"return",
"result_for_output"
] | Serializes output as JSON and writes it to console output wrapped with special prefix and suffix
:param result: Result to return
:param unpicklable: If True adds JSON can be deserialized as real object.
When False will be deserialized as dictionary | [
"Serializes",
"output",
"as",
"JSON",
"and",
"writes",
"it",
"to",
"console",
"output",
"wrapped",
"with",
"special",
"prefix",
"and",
"suffix"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/networking_utils.py#L30-L40 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/configuration_runner.py | ConfigurationRunner.save | def save(self, folder_path='', configuration_type='running', vrf_management_name=None, return_artifact=False):
"""Backup 'startup-config' or 'running-config' from device to provided file_system [ftp|tftp]
Also possible to backup config to localhost
:param folder_path: tftp/ftp server where file be saved
:param configuration_type: type of configuration that will be saved (StartUp or Running)
:param vrf_management_name: Virtual Routing and Forwarding management name
:return: status message / exception
:rtype: OrchestrationSavedArtifact or str
"""
if hasattr(self.resource_config, "vrf_management_name"):
vrf_management_name = vrf_management_name or self.resource_config.vrf_management_name
self._validate_configuration_type(configuration_type)
folder_path = self.get_path(folder_path)
system_name = re.sub('\s+', '_', self.resource_config.name)[:23]
time_stamp = time.strftime("%d%m%y-%H%M%S", time.localtime())
destination_filename = '{0}-{1}-{2}'.format(system_name, configuration_type.lower(), time_stamp)
full_path = join(folder_path, destination_filename)
folder_path = self.get_path(full_path)
self.save_flow.execute_flow(folder_path=folder_path,
configuration_type=configuration_type.lower(),
vrf_management_name=vrf_management_name)
if return_artifact:
artifact_type = full_path.split(':')[0]
identifier = full_path.replace("{0}:".format(artifact_type), "")
return OrchestrationSavedArtifact(identifier=identifier, artifact_type=artifact_type)
return destination_filename | python | def save(self, folder_path='', configuration_type='running', vrf_management_name=None, return_artifact=False):
"""Backup 'startup-config' or 'running-config' from device to provided file_system [ftp|tftp]
Also possible to backup config to localhost
:param folder_path: tftp/ftp server where file be saved
:param configuration_type: type of configuration that will be saved (StartUp or Running)
:param vrf_management_name: Virtual Routing and Forwarding management name
:return: status message / exception
:rtype: OrchestrationSavedArtifact or str
"""
if hasattr(self.resource_config, "vrf_management_name"):
vrf_management_name = vrf_management_name or self.resource_config.vrf_management_name
self._validate_configuration_type(configuration_type)
folder_path = self.get_path(folder_path)
system_name = re.sub('\s+', '_', self.resource_config.name)[:23]
time_stamp = time.strftime("%d%m%y-%H%M%S", time.localtime())
destination_filename = '{0}-{1}-{2}'.format(system_name, configuration_type.lower(), time_stamp)
full_path = join(folder_path, destination_filename)
folder_path = self.get_path(full_path)
self.save_flow.execute_flow(folder_path=folder_path,
configuration_type=configuration_type.lower(),
vrf_management_name=vrf_management_name)
if return_artifact:
artifact_type = full_path.split(':')[0]
identifier = full_path.replace("{0}:".format(artifact_type), "")
return OrchestrationSavedArtifact(identifier=identifier, artifact_type=artifact_type)
return destination_filename | [
"def",
"save",
"(",
"self",
",",
"folder_path",
"=",
"''",
",",
"configuration_type",
"=",
"'running'",
",",
"vrf_management_name",
"=",
"None",
",",
"return_artifact",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"resource_config",
",",
"\"vrf_management_name\"",
")",
":",
"vrf_management_name",
"=",
"vrf_management_name",
"or",
"self",
".",
"resource_config",
".",
"vrf_management_name",
"self",
".",
"_validate_configuration_type",
"(",
"configuration_type",
")",
"folder_path",
"=",
"self",
".",
"get_path",
"(",
"folder_path",
")",
"system_name",
"=",
"re",
".",
"sub",
"(",
"'\\s+'",
",",
"'_'",
",",
"self",
".",
"resource_config",
".",
"name",
")",
"[",
":",
"23",
"]",
"time_stamp",
"=",
"time",
".",
"strftime",
"(",
"\"%d%m%y-%H%M%S\"",
",",
"time",
".",
"localtime",
"(",
")",
")",
"destination_filename",
"=",
"'{0}-{1}-{2}'",
".",
"format",
"(",
"system_name",
",",
"configuration_type",
".",
"lower",
"(",
")",
",",
"time_stamp",
")",
"full_path",
"=",
"join",
"(",
"folder_path",
",",
"destination_filename",
")",
"folder_path",
"=",
"self",
".",
"get_path",
"(",
"full_path",
")",
"self",
".",
"save_flow",
".",
"execute_flow",
"(",
"folder_path",
"=",
"folder_path",
",",
"configuration_type",
"=",
"configuration_type",
".",
"lower",
"(",
")",
",",
"vrf_management_name",
"=",
"vrf_management_name",
")",
"if",
"return_artifact",
":",
"artifact_type",
"=",
"full_path",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"identifier",
"=",
"full_path",
".",
"replace",
"(",
"\"{0}:\"",
".",
"format",
"(",
"artifact_type",
")",
",",
"\"\"",
")",
"return",
"OrchestrationSavedArtifact",
"(",
"identifier",
"=",
"identifier",
",",
"artifact_type",
"=",
"artifact_type",
")",
"return",
"destination_filename"
] | Backup 'startup-config' or 'running-config' from device to provided file_system [ftp|tftp]
Also possible to backup config to localhost
:param folder_path: tftp/ftp server where file be saved
:param configuration_type: type of configuration that will be saved (StartUp or Running)
:param vrf_management_name: Virtual Routing and Forwarding management name
:return: status message / exception
:rtype: OrchestrationSavedArtifact or str | [
"Backup",
"startup",
"-",
"config",
"or",
"running",
"-",
"config",
"from",
"device",
"to",
"provided",
"file_system",
"[",
"ftp|tftp",
"]",
"Also",
"possible",
"to",
"backup",
"config",
"to",
"localhost",
":",
"param",
"folder_path",
":",
"tftp",
"/",
"ftp",
"server",
"where",
"file",
"be",
"saved",
":",
"param",
"configuration_type",
":",
"type",
"of",
"configuration",
"that",
"will",
"be",
"saved",
"(",
"StartUp",
"or",
"Running",
")",
":",
"param",
"vrf_management_name",
":",
"Virtual",
"Routing",
"and",
"Forwarding",
"management",
"name",
":",
"return",
":",
"status",
"message",
"/",
"exception",
":",
"rtype",
":",
"OrchestrationSavedArtifact",
"or",
"str"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/configuration_runner.py#L70-L99 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/configuration_runner.py | ConfigurationRunner.restore | def restore(self, path, configuration_type="running", restore_method="override", vrf_management_name=None):
"""Restore configuration on device from provided configuration file
Restore configuration from local file system or ftp/tftp server into 'running-config' or 'startup-config'.
:param path: relative path to the file on the remote host tftp://server/sourcefile
:param configuration_type: the configuration type to restore (StartUp or Running)
:param restore_method: override current config or not
:param vrf_management_name: Virtual Routing and Forwarding management name
:return: exception on crash
"""
if hasattr(self.resource_config, "vrf_management_name"):
vrf_management_name = vrf_management_name or self.resource_config.vrf_management_name
self._validate_configuration_type(configuration_type)
path = self.get_path(path)
self.restore_flow.execute_flow(path=path,
configuration_type=configuration_type.lower(),
restore_method=restore_method.lower(),
vrf_management_name=vrf_management_name) | python | def restore(self, path, configuration_type="running", restore_method="override", vrf_management_name=None):
"""Restore configuration on device from provided configuration file
Restore configuration from local file system or ftp/tftp server into 'running-config' or 'startup-config'.
:param path: relative path to the file on the remote host tftp://server/sourcefile
:param configuration_type: the configuration type to restore (StartUp or Running)
:param restore_method: override current config or not
:param vrf_management_name: Virtual Routing and Forwarding management name
:return: exception on crash
"""
if hasattr(self.resource_config, "vrf_management_name"):
vrf_management_name = vrf_management_name or self.resource_config.vrf_management_name
self._validate_configuration_type(configuration_type)
path = self.get_path(path)
self.restore_flow.execute_flow(path=path,
configuration_type=configuration_type.lower(),
restore_method=restore_method.lower(),
vrf_management_name=vrf_management_name) | [
"def",
"restore",
"(",
"self",
",",
"path",
",",
"configuration_type",
"=",
"\"running\"",
",",
"restore_method",
"=",
"\"override\"",
",",
"vrf_management_name",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"resource_config",
",",
"\"vrf_management_name\"",
")",
":",
"vrf_management_name",
"=",
"vrf_management_name",
"or",
"self",
".",
"resource_config",
".",
"vrf_management_name",
"self",
".",
"_validate_configuration_type",
"(",
"configuration_type",
")",
"path",
"=",
"self",
".",
"get_path",
"(",
"path",
")",
"self",
".",
"restore_flow",
".",
"execute_flow",
"(",
"path",
"=",
"path",
",",
"configuration_type",
"=",
"configuration_type",
".",
"lower",
"(",
")",
",",
"restore_method",
"=",
"restore_method",
".",
"lower",
"(",
")",
",",
"vrf_management_name",
"=",
"vrf_management_name",
")"
] | Restore configuration on device from provided configuration file
Restore configuration from local file system or ftp/tftp server into 'running-config' or 'startup-config'.
:param path: relative path to the file on the remote host tftp://server/sourcefile
:param configuration_type: the configuration type to restore (StartUp or Running)
:param restore_method: override current config or not
:param vrf_management_name: Virtual Routing and Forwarding management name
:return: exception on crash | [
"Restore",
"configuration",
"on",
"device",
"from",
"provided",
"configuration",
"file",
"Restore",
"configuration",
"from",
"local",
"file",
"system",
"or",
"ftp",
"/",
"tftp",
"server",
"into",
"running",
"-",
"config",
"or",
"startup",
"-",
"config",
".",
":",
"param",
"path",
":",
"relative",
"path",
"to",
"the",
"file",
"on",
"the",
"remote",
"host",
"tftp",
":",
"//",
"server",
"/",
"sourcefile",
":",
"param",
"configuration_type",
":",
"the",
"configuration",
"type",
"to",
"restore",
"(",
"StartUp",
"or",
"Running",
")",
":",
"param",
"restore_method",
":",
"override",
"current",
"config",
"or",
"not",
":",
"param",
"vrf_management_name",
":",
"Virtual",
"Routing",
"and",
"Forwarding",
"management",
"name",
":",
"return",
":",
"exception",
"on",
"crash"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/configuration_runner.py#L102-L120 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/configuration_runner.py | ConfigurationRunner.orchestration_save | def orchestration_save(self, mode="shallow", custom_params=None):
"""Orchestration Save command
:param mode:
:param custom_params: json with all required action to configure or remove vlans from certain port
:return Serialized OrchestrationSavedArtifact to json
:rtype json
"""
save_params = {'folder_path': '', 'configuration_type': 'running', 'return_artifact': True}
params = dict()
if custom_params:
params = jsonpickle.decode(custom_params)
save_params.update(params.get('custom_params', {}))
save_params['folder_path'] = self.get_path(save_params['folder_path'])
saved_artifact = self.save(**save_params)
saved_artifact_info = OrchestrationSavedArtifactInfo(resource_name=self.resource_config.name,
created_date=datetime.datetime.now(),
restore_rules=self.get_restore_rules(),
saved_artifact=saved_artifact)
save_response = OrchestrationSaveResult(saved_artifacts_info=saved_artifact_info)
self._validate_artifact_info(saved_artifact_info)
return serialize_to_json(save_response) | python | def orchestration_save(self, mode="shallow", custom_params=None):
"""Orchestration Save command
:param mode:
:param custom_params: json with all required action to configure or remove vlans from certain port
:return Serialized OrchestrationSavedArtifact to json
:rtype json
"""
save_params = {'folder_path': '', 'configuration_type': 'running', 'return_artifact': True}
params = dict()
if custom_params:
params = jsonpickle.decode(custom_params)
save_params.update(params.get('custom_params', {}))
save_params['folder_path'] = self.get_path(save_params['folder_path'])
saved_artifact = self.save(**save_params)
saved_artifact_info = OrchestrationSavedArtifactInfo(resource_name=self.resource_config.name,
created_date=datetime.datetime.now(),
restore_rules=self.get_restore_rules(),
saved_artifact=saved_artifact)
save_response = OrchestrationSaveResult(saved_artifacts_info=saved_artifact_info)
self._validate_artifact_info(saved_artifact_info)
return serialize_to_json(save_response) | [
"def",
"orchestration_save",
"(",
"self",
",",
"mode",
"=",
"\"shallow\"",
",",
"custom_params",
"=",
"None",
")",
":",
"save_params",
"=",
"{",
"'folder_path'",
":",
"''",
",",
"'configuration_type'",
":",
"'running'",
",",
"'return_artifact'",
":",
"True",
"}",
"params",
"=",
"dict",
"(",
")",
"if",
"custom_params",
":",
"params",
"=",
"jsonpickle",
".",
"decode",
"(",
"custom_params",
")",
"save_params",
".",
"update",
"(",
"params",
".",
"get",
"(",
"'custom_params'",
",",
"{",
"}",
")",
")",
"save_params",
"[",
"'folder_path'",
"]",
"=",
"self",
".",
"get_path",
"(",
"save_params",
"[",
"'folder_path'",
"]",
")",
"saved_artifact",
"=",
"self",
".",
"save",
"(",
"*",
"*",
"save_params",
")",
"saved_artifact_info",
"=",
"OrchestrationSavedArtifactInfo",
"(",
"resource_name",
"=",
"self",
".",
"resource_config",
".",
"name",
",",
"created_date",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
",",
"restore_rules",
"=",
"self",
".",
"get_restore_rules",
"(",
")",
",",
"saved_artifact",
"=",
"saved_artifact",
")",
"save_response",
"=",
"OrchestrationSaveResult",
"(",
"saved_artifacts_info",
"=",
"saved_artifact_info",
")",
"self",
".",
"_validate_artifact_info",
"(",
"saved_artifact_info",
")",
"return",
"serialize_to_json",
"(",
"save_response",
")"
] | Orchestration Save command
:param mode:
:param custom_params: json with all required action to configure or remove vlans from certain port
:return Serialized OrchestrationSavedArtifact to json
:rtype json | [
"Orchestration",
"Save",
"command"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/configuration_runner.py#L123-L149 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/configuration_runner.py | ConfigurationRunner.orchestration_restore | def orchestration_restore(self, saved_artifact_info, custom_params=None):
"""Orchestration restore
:param saved_artifact_info: json with all required data to restore configuration on the device
:param custom_params: custom parameters
"""
if saved_artifact_info is None or saved_artifact_info == '':
raise Exception('ConfigurationOperations', 'saved_artifact_info is None or empty')
saved_artifact_info = JsonRequestDeserializer(jsonpickle.decode(saved_artifact_info))
if not hasattr(saved_artifact_info, 'saved_artifacts_info'):
raise Exception('ConfigurationOperations', 'Saved_artifacts_info is missing')
saved_config = saved_artifact_info.saved_artifacts_info
params = None
if custom_params:
params = JsonRequestDeserializer(jsonpickle.decode(custom_params))
_validate_custom_params(params)
self._validate_artifact_info(saved_config)
if saved_config.restore_rules.requires_same_resource \
and saved_config.resource_name.lower() != self.resource_config.name.lower():
raise Exception('ConfigurationOperations', 'Incompatible resource, expected {}'.format(self.resource_config.name))
restore_params = {'configuration_type': 'running',
'restore_method': 'override',
'vrf_management_name': None,
'path': '{}:{}'.format(saved_config.saved_artifact.artifact_type,
saved_config.saved_artifact.identifier)}
if hasattr(params, 'custom_params'):
if hasattr(params.custom_params, 'restore_method'):
restore_params['restore_method'] = params.custom_params.restore_method
if hasattr(params.custom_params, 'configuration_type'):
restore_params['configuration_type'] = params.custom_params.configuration_type
if hasattr(params.custom_params, 'vrf_management_name'):
restore_params['vrf_management_name'] = params.custom_params.vrf_management_name
if 'startup' in saved_config.saved_artifact.identifier.split('/')[-1]:
restore_params['configuration_type'] = 'startup'
self.restore(**restore_params) | python | def orchestration_restore(self, saved_artifact_info, custom_params=None):
"""Orchestration restore
:param saved_artifact_info: json with all required data to restore configuration on the device
:param custom_params: custom parameters
"""
if saved_artifact_info is None or saved_artifact_info == '':
raise Exception('ConfigurationOperations', 'saved_artifact_info is None or empty')
saved_artifact_info = JsonRequestDeserializer(jsonpickle.decode(saved_artifact_info))
if not hasattr(saved_artifact_info, 'saved_artifacts_info'):
raise Exception('ConfigurationOperations', 'Saved_artifacts_info is missing')
saved_config = saved_artifact_info.saved_artifacts_info
params = None
if custom_params:
params = JsonRequestDeserializer(jsonpickle.decode(custom_params))
_validate_custom_params(params)
self._validate_artifact_info(saved_config)
if saved_config.restore_rules.requires_same_resource \
and saved_config.resource_name.lower() != self.resource_config.name.lower():
raise Exception('ConfigurationOperations', 'Incompatible resource, expected {}'.format(self.resource_config.name))
restore_params = {'configuration_type': 'running',
'restore_method': 'override',
'vrf_management_name': None,
'path': '{}:{}'.format(saved_config.saved_artifact.artifact_type,
saved_config.saved_artifact.identifier)}
if hasattr(params, 'custom_params'):
if hasattr(params.custom_params, 'restore_method'):
restore_params['restore_method'] = params.custom_params.restore_method
if hasattr(params.custom_params, 'configuration_type'):
restore_params['configuration_type'] = params.custom_params.configuration_type
if hasattr(params.custom_params, 'vrf_management_name'):
restore_params['vrf_management_name'] = params.custom_params.vrf_management_name
if 'startup' in saved_config.saved_artifact.identifier.split('/')[-1]:
restore_params['configuration_type'] = 'startup'
self.restore(**restore_params) | [
"def",
"orchestration_restore",
"(",
"self",
",",
"saved_artifact_info",
",",
"custom_params",
"=",
"None",
")",
":",
"if",
"saved_artifact_info",
"is",
"None",
"or",
"saved_artifact_info",
"==",
"''",
":",
"raise",
"Exception",
"(",
"'ConfigurationOperations'",
",",
"'saved_artifact_info is None or empty'",
")",
"saved_artifact_info",
"=",
"JsonRequestDeserializer",
"(",
"jsonpickle",
".",
"decode",
"(",
"saved_artifact_info",
")",
")",
"if",
"not",
"hasattr",
"(",
"saved_artifact_info",
",",
"'saved_artifacts_info'",
")",
":",
"raise",
"Exception",
"(",
"'ConfigurationOperations'",
",",
"'Saved_artifacts_info is missing'",
")",
"saved_config",
"=",
"saved_artifact_info",
".",
"saved_artifacts_info",
"params",
"=",
"None",
"if",
"custom_params",
":",
"params",
"=",
"JsonRequestDeserializer",
"(",
"jsonpickle",
".",
"decode",
"(",
"custom_params",
")",
")",
"_validate_custom_params",
"(",
"params",
")",
"self",
".",
"_validate_artifact_info",
"(",
"saved_config",
")",
"if",
"saved_config",
".",
"restore_rules",
".",
"requires_same_resource",
"and",
"saved_config",
".",
"resource_name",
".",
"lower",
"(",
")",
"!=",
"self",
".",
"resource_config",
".",
"name",
".",
"lower",
"(",
")",
":",
"raise",
"Exception",
"(",
"'ConfigurationOperations'",
",",
"'Incompatible resource, expected {}'",
".",
"format",
"(",
"self",
".",
"resource_config",
".",
"name",
")",
")",
"restore_params",
"=",
"{",
"'configuration_type'",
":",
"'running'",
",",
"'restore_method'",
":",
"'override'",
",",
"'vrf_management_name'",
":",
"None",
",",
"'path'",
":",
"'{}:{}'",
".",
"format",
"(",
"saved_config",
".",
"saved_artifact",
".",
"artifact_type",
",",
"saved_config",
".",
"saved_artifact",
".",
"identifier",
")",
"}",
"if",
"hasattr",
"(",
"params",
",",
"'custom_params'",
")",
":",
"if",
"hasattr",
"(",
"params",
".",
"custom_params",
",",
"'restore_method'",
")",
":",
"restore_params",
"[",
"'restore_method'",
"]",
"=",
"params",
".",
"custom_params",
".",
"restore_method",
"if",
"hasattr",
"(",
"params",
".",
"custom_params",
",",
"'configuration_type'",
")",
":",
"restore_params",
"[",
"'configuration_type'",
"]",
"=",
"params",
".",
"custom_params",
".",
"configuration_type",
"if",
"hasattr",
"(",
"params",
".",
"custom_params",
",",
"'vrf_management_name'",
")",
":",
"restore_params",
"[",
"'vrf_management_name'",
"]",
"=",
"params",
".",
"custom_params",
".",
"vrf_management_name",
"if",
"'startup'",
"in",
"saved_config",
".",
"saved_artifact",
".",
"identifier",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
":",
"restore_params",
"[",
"'configuration_type'",
"]",
"=",
"'startup'",
"self",
".",
"restore",
"(",
"*",
"*",
"restore_params",
")"
] | Orchestration restore
:param saved_artifact_info: json with all required data to restore configuration on the device
:param custom_params: custom parameters | [
"Orchestration",
"restore"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/configuration_runner.py#L152-L196 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/configuration_runner.py | ConfigurationRunner.get_path | def get_path(self, path=''):
"""
Validate incoming path, if path is empty, build it from resource attributes,
If path is invalid - raise exception
:param path: path to remote file storage
:return: valid path or :raise Exception:
"""
if not path:
host = self.resource_config.backup_location
if ':' not in host:
scheme = self.resource_config.backup_type
if not scheme or scheme.lower() == self.DEFAULT_FILE_SYSTEM.lower():
scheme = self.file_system
scheme = re.sub('(:|/+).*$', '', scheme, re.DOTALL)
host = re.sub('^/+', '', host)
host = '{}://{}'.format(scheme, host)
path = host
url = UrlParser.parse_url(path)
if url[UrlParser.SCHEME].lower() in AUTHORIZATION_REQUIRED_STORAGE:
if UrlParser.USERNAME not in url or not url[UrlParser.USERNAME]:
url[UrlParser.USERNAME] = self.resource_config.backup_user
if UrlParser.PASSWORD not in url or not url[UrlParser.PASSWORD]:
url[UrlParser.PASSWORD] = self._api.DecryptPassword(self.resource_config.backup_password).Value
try:
result = UrlParser.build_url(url)
except Exception as e:
self._logger.error('Failed to build url: {}'.format(e))
raise Exception('ConfigurationOperations', 'Failed to build path url to remote host')
return result | python | def get_path(self, path=''):
"""
Validate incoming path, if path is empty, build it from resource attributes,
If path is invalid - raise exception
:param path: path to remote file storage
:return: valid path or :raise Exception:
"""
if not path:
host = self.resource_config.backup_location
if ':' not in host:
scheme = self.resource_config.backup_type
if not scheme or scheme.lower() == self.DEFAULT_FILE_SYSTEM.lower():
scheme = self.file_system
scheme = re.sub('(:|/+).*$', '', scheme, re.DOTALL)
host = re.sub('^/+', '', host)
host = '{}://{}'.format(scheme, host)
path = host
url = UrlParser.parse_url(path)
if url[UrlParser.SCHEME].lower() in AUTHORIZATION_REQUIRED_STORAGE:
if UrlParser.USERNAME not in url or not url[UrlParser.USERNAME]:
url[UrlParser.USERNAME] = self.resource_config.backup_user
if UrlParser.PASSWORD not in url or not url[UrlParser.PASSWORD]:
url[UrlParser.PASSWORD] = self._api.DecryptPassword(self.resource_config.backup_password).Value
try:
result = UrlParser.build_url(url)
except Exception as e:
self._logger.error('Failed to build url: {}'.format(e))
raise Exception('ConfigurationOperations', 'Failed to build path url to remote host')
return result | [
"def",
"get_path",
"(",
"self",
",",
"path",
"=",
"''",
")",
":",
"if",
"not",
"path",
":",
"host",
"=",
"self",
".",
"resource_config",
".",
"backup_location",
"if",
"':'",
"not",
"in",
"host",
":",
"scheme",
"=",
"self",
".",
"resource_config",
".",
"backup_type",
"if",
"not",
"scheme",
"or",
"scheme",
".",
"lower",
"(",
")",
"==",
"self",
".",
"DEFAULT_FILE_SYSTEM",
".",
"lower",
"(",
")",
":",
"scheme",
"=",
"self",
".",
"file_system",
"scheme",
"=",
"re",
".",
"sub",
"(",
"'(:|/+).*$'",
",",
"''",
",",
"scheme",
",",
"re",
".",
"DOTALL",
")",
"host",
"=",
"re",
".",
"sub",
"(",
"'^/+'",
",",
"''",
",",
"host",
")",
"host",
"=",
"'{}://{}'",
".",
"format",
"(",
"scheme",
",",
"host",
")",
"path",
"=",
"host",
"url",
"=",
"UrlParser",
".",
"parse_url",
"(",
"path",
")",
"if",
"url",
"[",
"UrlParser",
".",
"SCHEME",
"]",
".",
"lower",
"(",
")",
"in",
"AUTHORIZATION_REQUIRED_STORAGE",
":",
"if",
"UrlParser",
".",
"USERNAME",
"not",
"in",
"url",
"or",
"not",
"url",
"[",
"UrlParser",
".",
"USERNAME",
"]",
":",
"url",
"[",
"UrlParser",
".",
"USERNAME",
"]",
"=",
"self",
".",
"resource_config",
".",
"backup_user",
"if",
"UrlParser",
".",
"PASSWORD",
"not",
"in",
"url",
"or",
"not",
"url",
"[",
"UrlParser",
".",
"PASSWORD",
"]",
":",
"url",
"[",
"UrlParser",
".",
"PASSWORD",
"]",
"=",
"self",
".",
"_api",
".",
"DecryptPassword",
"(",
"self",
".",
"resource_config",
".",
"backup_password",
")",
".",
"Value",
"try",
":",
"result",
"=",
"UrlParser",
".",
"build_url",
"(",
"url",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_logger",
".",
"error",
"(",
"'Failed to build url: {}'",
".",
"format",
"(",
"e",
")",
")",
"raise",
"Exception",
"(",
"'ConfigurationOperations'",
",",
"'Failed to build path url to remote host'",
")",
"return",
"result"
] | Validate incoming path, if path is empty, build it from resource attributes,
If path is invalid - raise exception
:param path: path to remote file storage
:return: valid path or :raise Exception: | [
"Validate",
"incoming",
"path",
"if",
"path",
"is",
"empty",
"build",
"it",
"from",
"resource",
"attributes",
"If",
"path",
"is",
"invalid",
"-",
"raise",
"exception"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/configuration_runner.py#L198-L230 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/configuration_runner.py | ConfigurationRunner._validate_configuration_type | def _validate_configuration_type(self, configuration_type):
"""Validate configuration type
:param configuration_type: configuration_type, should be Startup or Running
:raise Exception:
"""
if configuration_type.lower() != 'running' and configuration_type.lower() != 'startup':
raise Exception(self.__class__.__name__, 'Configuration Type is invalid. Should be startup or running') | python | def _validate_configuration_type(self, configuration_type):
"""Validate configuration type
:param configuration_type: configuration_type, should be Startup or Running
:raise Exception:
"""
if configuration_type.lower() != 'running' and configuration_type.lower() != 'startup':
raise Exception(self.__class__.__name__, 'Configuration Type is invalid. Should be startup or running') | [
"def",
"_validate_configuration_type",
"(",
"self",
",",
"configuration_type",
")",
":",
"if",
"configuration_type",
".",
"lower",
"(",
")",
"!=",
"'running'",
"and",
"configuration_type",
".",
"lower",
"(",
")",
"!=",
"'startup'",
":",
"raise",
"Exception",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"'Configuration Type is invalid. Should be startup or running'",
")"
] | Validate configuration type
:param configuration_type: configuration_type, should be Startup or Running
:raise Exception: | [
"Validate",
"configuration",
"type"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/configuration_runner.py#L232-L240 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/runners/configuration_runner.py | ConfigurationRunner._validate_artifact_info | def _validate_artifact_info(self, saved_config):
"""Validate OrchestrationSavedArtifactInfo object for key components
:param OrchestrationSavedArtifactInfo saved_config: object to validate
"""
is_fail = False
fail_attribute = ''
for class_attribute in self.REQUIRED_SAVE_ATTRIBUTES_LIST:
if type(class_attribute) is tuple:
if not hasattr(saved_config, class_attribute[0]):
is_fail = True
fail_attribute = class_attribute[0]
elif not hasattr(getattr(saved_config, class_attribute[0]), class_attribute[1]):
is_fail = True
fail_attribute = class_attribute[1]
else:
if not hasattr(saved_config, class_attribute):
is_fail = True
fail_attribute = class_attribute
if is_fail:
raise Exception('ConfigurationOperations',
'Mandatory field {0} is missing in Saved Artifact Info request json'.format(
fail_attribute)) | python | def _validate_artifact_info(self, saved_config):
"""Validate OrchestrationSavedArtifactInfo object for key components
:param OrchestrationSavedArtifactInfo saved_config: object to validate
"""
is_fail = False
fail_attribute = ''
for class_attribute in self.REQUIRED_SAVE_ATTRIBUTES_LIST:
if type(class_attribute) is tuple:
if not hasattr(saved_config, class_attribute[0]):
is_fail = True
fail_attribute = class_attribute[0]
elif not hasattr(getattr(saved_config, class_attribute[0]), class_attribute[1]):
is_fail = True
fail_attribute = class_attribute[1]
else:
if not hasattr(saved_config, class_attribute):
is_fail = True
fail_attribute = class_attribute
if is_fail:
raise Exception('ConfigurationOperations',
'Mandatory field {0} is missing in Saved Artifact Info request json'.format(
fail_attribute)) | [
"def",
"_validate_artifact_info",
"(",
"self",
",",
"saved_config",
")",
":",
"is_fail",
"=",
"False",
"fail_attribute",
"=",
"''",
"for",
"class_attribute",
"in",
"self",
".",
"REQUIRED_SAVE_ATTRIBUTES_LIST",
":",
"if",
"type",
"(",
"class_attribute",
")",
"is",
"tuple",
":",
"if",
"not",
"hasattr",
"(",
"saved_config",
",",
"class_attribute",
"[",
"0",
"]",
")",
":",
"is_fail",
"=",
"True",
"fail_attribute",
"=",
"class_attribute",
"[",
"0",
"]",
"elif",
"not",
"hasattr",
"(",
"getattr",
"(",
"saved_config",
",",
"class_attribute",
"[",
"0",
"]",
")",
",",
"class_attribute",
"[",
"1",
"]",
")",
":",
"is_fail",
"=",
"True",
"fail_attribute",
"=",
"class_attribute",
"[",
"1",
"]",
"else",
":",
"if",
"not",
"hasattr",
"(",
"saved_config",
",",
"class_attribute",
")",
":",
"is_fail",
"=",
"True",
"fail_attribute",
"=",
"class_attribute",
"if",
"is_fail",
":",
"raise",
"Exception",
"(",
"'ConfigurationOperations'",
",",
"'Mandatory field {0} is missing in Saved Artifact Info request json'",
".",
"format",
"(",
"fail_attribute",
")",
")"
] | Validate OrchestrationSavedArtifactInfo object for key components
:param OrchestrationSavedArtifactInfo saved_config: object to validate | [
"Validate",
"OrchestrationSavedArtifactInfo",
"object",
"for",
"key",
"components"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/configuration_runner.py#L242-L265 |
eumis/pyviews | pyviews/core/ioc.py | register | def register(key, initializer: callable, param=None):
'''Adds resolver to global container'''
get_current_scope().container.register(key, initializer, param) | python | def register(key, initializer: callable, param=None):
'''Adds resolver to global container'''
get_current_scope().container.register(key, initializer, param) | [
"def",
"register",
"(",
"key",
",",
"initializer",
":",
"callable",
",",
"param",
"=",
"None",
")",
":",
"get_current_scope",
"(",
")",
".",
"container",
".",
"register",
"(",
"key",
",",
"initializer",
",",
"param",
")"
] | Adds resolver to global container | [
"Adds",
"resolver",
"to",
"global",
"container"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/ioc.py#L81-L83 |
eumis/pyviews | pyviews/core/ioc.py | register_single | def register_single(key, value, param=None):
'''Generates resolver to return singleton value and adds it to global container'''
get_current_scope().container.register(key, lambda: value, param) | python | def register_single(key, value, param=None):
'''Generates resolver to return singleton value and adds it to global container'''
get_current_scope().container.register(key, lambda: value, param) | [
"def",
"register_single",
"(",
"key",
",",
"value",
",",
"param",
"=",
"None",
")",
":",
"get_current_scope",
"(",
")",
".",
"container",
".",
"register",
"(",
"key",
",",
"lambda",
":",
"value",
",",
"param",
")"
] | Generates resolver to return singleton value and adds it to global container | [
"Generates",
"resolver",
"to",
"return",
"singleton",
"value",
"and",
"adds",
"it",
"to",
"global",
"container"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/ioc.py#L85-L87 |
eumis/pyviews | pyviews/core/ioc.py | wrap_with_scope | def wrap_with_scope(func, scope_name=None):
'''Wraps function with scope. If scope_name is None current scope is used'''
if scope_name is None:
scope_name = get_current_scope().name
return lambda *args, scope=scope_name, **kwargs: \
_call_with_scope(func, scope, args, kwargs) | python | def wrap_with_scope(func, scope_name=None):
'''Wraps function with scope. If scope_name is None current scope is used'''
if scope_name is None:
scope_name = get_current_scope().name
return lambda *args, scope=scope_name, **kwargs: \
_call_with_scope(func, scope, args, kwargs) | [
"def",
"wrap_with_scope",
"(",
"func",
",",
"scope_name",
"=",
"None",
")",
":",
"if",
"scope_name",
"is",
"None",
":",
"scope_name",
"=",
"get_current_scope",
"(",
")",
".",
"name",
"return",
"lambda",
"*",
"args",
",",
"scope",
"=",
"scope_name",
",",
"*",
"*",
"kwargs",
":",
"_call_with_scope",
"(",
"func",
",",
"scope",
",",
"args",
",",
"kwargs",
")"
] | Wraps function with scope. If scope_name is None current scope is used | [
"Wraps",
"function",
"with",
"scope",
".",
"If",
"scope_name",
"is",
"None",
"current",
"scope",
"is",
"used"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/ioc.py#L99-L104 |
eumis/pyviews | pyviews/core/ioc.py | inject | def inject(*injections):
'''Resolves dependencies using global container and passed it with optional parameters'''
def _decorate(func):
def _decorated(*args, **kwargs):
args = list(args)
keys_to_inject = [name for name in injections if name not in kwargs]
for key in keys_to_inject:
kwargs[key] = get_current_scope().container.get(key)
return func(*args, **kwargs)
return _decorated
return _decorate | python | def inject(*injections):
'''Resolves dependencies using global container and passed it with optional parameters'''
def _decorate(func):
def _decorated(*args, **kwargs):
args = list(args)
keys_to_inject = [name for name in injections if name not in kwargs]
for key in keys_to_inject:
kwargs[key] = get_current_scope().container.get(key)
return func(*args, **kwargs)
return _decorated
return _decorate | [
"def",
"inject",
"(",
"*",
"injections",
")",
":",
"def",
"_decorate",
"(",
"func",
")",
":",
"def",
"_decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"list",
"(",
"args",
")",
"keys_to_inject",
"=",
"[",
"name",
"for",
"name",
"in",
"injections",
"if",
"name",
"not",
"in",
"kwargs",
"]",
"for",
"key",
"in",
"keys_to_inject",
":",
"kwargs",
"[",
"key",
"]",
"=",
"get_current_scope",
"(",
")",
".",
"container",
".",
"get",
"(",
"key",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_decorated",
"return",
"_decorate"
] | Resolves dependencies using global container and passed it with optional parameters | [
"Resolves",
"dependencies",
"using",
"global",
"container",
"and",
"passed",
"it",
"with",
"optional",
"parameters"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/ioc.py#L126-L136 |
eumis/pyviews | pyviews/core/ioc.py | Container.register | def register(self, key, initializer: callable, param=None):
'''Add resolver to container'''
if not callable(initializer):
raise DependencyError('Initializer {0} is not callable'.format(initializer))
if key not in self._initializers:
self._initializers[key] = {}
self._initializers[key][param] = initializer | python | def register(self, key, initializer: callable, param=None):
'''Add resolver to container'''
if not callable(initializer):
raise DependencyError('Initializer {0} is not callable'.format(initializer))
if key not in self._initializers:
self._initializers[key] = {}
self._initializers[key][param] = initializer | [
"def",
"register",
"(",
"self",
",",
"key",
",",
"initializer",
":",
"callable",
",",
"param",
"=",
"None",
")",
":",
"if",
"not",
"callable",
"(",
"initializer",
")",
":",
"raise",
"DependencyError",
"(",
"'Initializer {0} is not callable'",
".",
"format",
"(",
"initializer",
")",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_initializers",
":",
"self",
".",
"_initializers",
"[",
"key",
"]",
"=",
"{",
"}",
"self",
".",
"_initializers",
"[",
"key",
"]",
"[",
"param",
"]",
"=",
"initializer"
] | Add resolver to container | [
"Add",
"resolver",
"to",
"container"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/ioc.py#L16-L22 |
eumis/pyviews | pyviews/core/ioc.py | Container.get | def get(self, key, param=None):
'''Resolve dependecy'''
try:
return self._initializers[key][param]()
except KeyError:
if key in self._factories:
return self._factories[key](param)
raise DependencyError('Dependency "{0}" is not found'.format(key)) | python | def get(self, key, param=None):
'''Resolve dependecy'''
try:
return self._initializers[key][param]()
except KeyError:
if key in self._factories:
return self._factories[key](param)
raise DependencyError('Dependency "{0}" is not found'.format(key)) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"param",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_initializers",
"[",
"key",
"]",
"[",
"param",
"]",
"(",
")",
"except",
"KeyError",
":",
"if",
"key",
"in",
"self",
".",
"_factories",
":",
"return",
"self",
".",
"_factories",
"[",
"key",
"]",
"(",
"param",
")",
"raise",
"DependencyError",
"(",
"'Dependency \"{0}\" is not found'",
".",
"format",
"(",
"key",
")",
")"
] | Resolve dependecy | [
"Resolve",
"dependecy"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/ioc.py#L28-L35 |
upsight/doctor | doctor/flask.py | handle_http | def handle_http(handler: Resource, args: Tuple, kwargs: Dict, logic: Callable):
"""Handle a Flask HTTP request
:param handler: flask_restful.Resource: An instance of a Flask Restful
resource class.
:param tuple args: Any positional arguments passed to the wrapper method.
:param dict kwargs: Any keyword arguments passed to the wrapper method.
:param callable logic: The callable to invoke to actually perform the
business logic for this request.
"""
try:
# We are checking mimetype here instead of content_type because
# mimetype is just the content-type, where as content_type can
# contain encoding, charset, and language information. e.g.
# `Content-Type: application/json; charset=UTF8`
if (request.mimetype == 'application/json' and
request.method in HTTP_METHODS_WITH_JSON_BODY):
# This is a proper typed JSON request. The parameters will be
# encoded into the request body as a JSON blob.
if not logic._doctor_req_obj_type:
request_params = map_param_names(
request.json, logic._doctor_signature.parameters)
else:
request_params = request.json
else:
# Try to parse things from normal HTTP parameters
request_params = parse_form_and_query_params(
request.values, logic._doctor_signature.parameters)
params = request_params
# Only filter out additional params if a req_obj_type was not specified.
if not logic._doctor_req_obj_type:
# Filter out any params not part of the logic signature.
all_params = logic._doctor_params.all
params = {k: v for k, v in params.items() if k in all_params}
params.update(**kwargs)
# Check for required params
missing = []
for required in logic._doctor_params.required:
if required not in params:
missing.append(required)
if missing:
verb = 'are'
if len(missing) == 1:
verb = 'is'
missing = missing[0]
error = '{} {} required.'.format(missing, verb)
raise InvalidValueError(error)
# Validate and coerce parameters to the appropriate types.
errors = {}
sig = logic._doctor_signature
# If a `req_obj_type` was defined for the route, pass all request
# params to that type for validation/coercion
if logic._doctor_req_obj_type:
annotation = logic._doctor_req_obj_type
try:
# NOTE: We calculate the value before applying native type in
# order to support UnionType types which dynamically modifies
# the native_type property based on the initialized value.
value = annotation(params)
params = annotation.native_type(value)
except TypeError:
logging.exception(
'Error casting and validating params with value `%s`.',
params)
raise
except TypeSystemError as e:
errors['__all__'] = e.detail
else:
for name, value in params.items():
annotation = sig.parameters[name].annotation
if annotation.nullable and value is None:
continue
try:
# NOTE: We calculate the value before applying native type
# in order to support UnionType types which dynamically
# modifies the native_type property based on the initialized
# value.
value = annotation(value)
params[name] = annotation.native_type(value)
except TypeSystemError as e:
errors[name] = e.detail
if errors:
raise TypeSystemError(errors, errors=errors)
if logic._doctor_req_obj_type:
# Pass any positional arguments followed by the coerced request
# parameters to the logic function.
response = logic(*args, params)
else:
# Only pass request parameters defined by the logic signature.
logic_params = {k: v for k, v in params.items()
if k in logic._doctor_params.logic}
response = logic(*args, **logic_params)
# response validation
if sig.return_annotation != sig.empty:
return_annotation = sig.return_annotation
_response = response
if isinstance(response, Response):
_response = response.content
# Check if our return annotation is a Response that supplied a
# type to validate against. If so, use that type for validation
# e.g. def logic() -> Response[MyType]
if (issubclass(return_annotation, Response) and
return_annotation.__args__ is not None):
return_annotation = return_annotation.__args__[0]
try:
return_annotation(_response)
except TypeSystemError as e:
response_str = str(_response)
logging.warning('Response to %s %s does not validate: %s.',
request.method, request.path,
response_str, exc_info=e)
if should_raise_response_validation_errors():
error = ('Response to {method} {path} `{response}` does not'
' validate: {error}'.format(
method=request.method, path=request.path,
response=response, error=e.detail))
raise TypeSystemError(error)
if isinstance(response, Response):
status_code = response.status_code
if status_code is None:
status_code = STATUS_CODE_MAP.get(request.method, 200)
return (response.content, status_code, response.headers)
return response, STATUS_CODE_MAP.get(request.method, 200)
except (InvalidValueError, TypeSystemError) as e:
errors = getattr(e, 'errors', None)
raise HTTP400Exception(e, errors=errors)
except UnauthorizedError as e:
raise HTTP401Exception(e)
except ForbiddenError as e:
raise HTTP403Exception(e)
except NotFoundError as e:
raise HTTP404Exception(e)
except ImmutableError as e:
raise HTTP409Exception(e)
except Exception as e:
# Always re-raise exceptions when DEBUG is enabled for development.
if current_app.config.get('DEBUG', False):
raise
allowed_exceptions = logic._doctor_allowed_exceptions
if allowed_exceptions and any(isinstance(e, cls)
for cls in allowed_exceptions):
raise
logging.exception(e)
raise HTTP500Exception('Uncaught error in logic function') | python | def handle_http(handler: Resource, args: Tuple, kwargs: Dict, logic: Callable):
"""Handle a Flask HTTP request
:param handler: flask_restful.Resource: An instance of a Flask Restful
resource class.
:param tuple args: Any positional arguments passed to the wrapper method.
:param dict kwargs: Any keyword arguments passed to the wrapper method.
:param callable logic: The callable to invoke to actually perform the
business logic for this request.
"""
try:
# We are checking mimetype here instead of content_type because
# mimetype is just the content-type, where as content_type can
# contain encoding, charset, and language information. e.g.
# `Content-Type: application/json; charset=UTF8`
if (request.mimetype == 'application/json' and
request.method in HTTP_METHODS_WITH_JSON_BODY):
# This is a proper typed JSON request. The parameters will be
# encoded into the request body as a JSON blob.
if not logic._doctor_req_obj_type:
request_params = map_param_names(
request.json, logic._doctor_signature.parameters)
else:
request_params = request.json
else:
# Try to parse things from normal HTTP parameters
request_params = parse_form_and_query_params(
request.values, logic._doctor_signature.parameters)
params = request_params
# Only filter out additional params if a req_obj_type was not specified.
if not logic._doctor_req_obj_type:
# Filter out any params not part of the logic signature.
all_params = logic._doctor_params.all
params = {k: v for k, v in params.items() if k in all_params}
params.update(**kwargs)
# Check for required params
missing = []
for required in logic._doctor_params.required:
if required not in params:
missing.append(required)
if missing:
verb = 'are'
if len(missing) == 1:
verb = 'is'
missing = missing[0]
error = '{} {} required.'.format(missing, verb)
raise InvalidValueError(error)
# Validate and coerce parameters to the appropriate types.
errors = {}
sig = logic._doctor_signature
# If a `req_obj_type` was defined for the route, pass all request
# params to that type for validation/coercion
if logic._doctor_req_obj_type:
annotation = logic._doctor_req_obj_type
try:
# NOTE: We calculate the value before applying native type in
# order to support UnionType types which dynamically modifies
# the native_type property based on the initialized value.
value = annotation(params)
params = annotation.native_type(value)
except TypeError:
logging.exception(
'Error casting and validating params with value `%s`.',
params)
raise
except TypeSystemError as e:
errors['__all__'] = e.detail
else:
for name, value in params.items():
annotation = sig.parameters[name].annotation
if annotation.nullable and value is None:
continue
try:
# NOTE: We calculate the value before applying native type
# in order to support UnionType types which dynamically
# modifies the native_type property based on the initialized
# value.
value = annotation(value)
params[name] = annotation.native_type(value)
except TypeSystemError as e:
errors[name] = e.detail
if errors:
raise TypeSystemError(errors, errors=errors)
if logic._doctor_req_obj_type:
# Pass any positional arguments followed by the coerced request
# parameters to the logic function.
response = logic(*args, params)
else:
# Only pass request parameters defined by the logic signature.
logic_params = {k: v for k, v in params.items()
if k in logic._doctor_params.logic}
response = logic(*args, **logic_params)
# response validation
if sig.return_annotation != sig.empty:
return_annotation = sig.return_annotation
_response = response
if isinstance(response, Response):
_response = response.content
# Check if our return annotation is a Response that supplied a
# type to validate against. If so, use that type for validation
# e.g. def logic() -> Response[MyType]
if (issubclass(return_annotation, Response) and
return_annotation.__args__ is not None):
return_annotation = return_annotation.__args__[0]
try:
return_annotation(_response)
except TypeSystemError as e:
response_str = str(_response)
logging.warning('Response to %s %s does not validate: %s.',
request.method, request.path,
response_str, exc_info=e)
if should_raise_response_validation_errors():
error = ('Response to {method} {path} `{response}` does not'
' validate: {error}'.format(
method=request.method, path=request.path,
response=response, error=e.detail))
raise TypeSystemError(error)
if isinstance(response, Response):
status_code = response.status_code
if status_code is None:
status_code = STATUS_CODE_MAP.get(request.method, 200)
return (response.content, status_code, response.headers)
return response, STATUS_CODE_MAP.get(request.method, 200)
except (InvalidValueError, TypeSystemError) as e:
errors = getattr(e, 'errors', None)
raise HTTP400Exception(e, errors=errors)
except UnauthorizedError as e:
raise HTTP401Exception(e)
except ForbiddenError as e:
raise HTTP403Exception(e)
except NotFoundError as e:
raise HTTP404Exception(e)
except ImmutableError as e:
raise HTTP409Exception(e)
except Exception as e:
# Always re-raise exceptions when DEBUG is enabled for development.
if current_app.config.get('DEBUG', False):
raise
allowed_exceptions = logic._doctor_allowed_exceptions
if allowed_exceptions and any(isinstance(e, cls)
for cls in allowed_exceptions):
raise
logging.exception(e)
raise HTTP500Exception('Uncaught error in logic function') | [
"def",
"handle_http",
"(",
"handler",
":",
"Resource",
",",
"args",
":",
"Tuple",
",",
"kwargs",
":",
"Dict",
",",
"logic",
":",
"Callable",
")",
":",
"try",
":",
"# We are checking mimetype here instead of content_type because",
"# mimetype is just the content-type, where as content_type can",
"# contain encoding, charset, and language information. e.g.",
"# `Content-Type: application/json; charset=UTF8`",
"if",
"(",
"request",
".",
"mimetype",
"==",
"'application/json'",
"and",
"request",
".",
"method",
"in",
"HTTP_METHODS_WITH_JSON_BODY",
")",
":",
"# This is a proper typed JSON request. The parameters will be",
"# encoded into the request body as a JSON blob.",
"if",
"not",
"logic",
".",
"_doctor_req_obj_type",
":",
"request_params",
"=",
"map_param_names",
"(",
"request",
".",
"json",
",",
"logic",
".",
"_doctor_signature",
".",
"parameters",
")",
"else",
":",
"request_params",
"=",
"request",
".",
"json",
"else",
":",
"# Try to parse things from normal HTTP parameters",
"request_params",
"=",
"parse_form_and_query_params",
"(",
"request",
".",
"values",
",",
"logic",
".",
"_doctor_signature",
".",
"parameters",
")",
"params",
"=",
"request_params",
"# Only filter out additional params if a req_obj_type was not specified.",
"if",
"not",
"logic",
".",
"_doctor_req_obj_type",
":",
"# Filter out any params not part of the logic signature.",
"all_params",
"=",
"logic",
".",
"_doctor_params",
".",
"all",
"params",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
"if",
"k",
"in",
"all_params",
"}",
"params",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"# Check for required params",
"missing",
"=",
"[",
"]",
"for",
"required",
"in",
"logic",
".",
"_doctor_params",
".",
"required",
":",
"if",
"required",
"not",
"in",
"params",
":",
"missing",
".",
"append",
"(",
"required",
")",
"if",
"missing",
":",
"verb",
"=",
"'are'",
"if",
"len",
"(",
"missing",
")",
"==",
"1",
":",
"verb",
"=",
"'is'",
"missing",
"=",
"missing",
"[",
"0",
"]",
"error",
"=",
"'{} {} required.'",
".",
"format",
"(",
"missing",
",",
"verb",
")",
"raise",
"InvalidValueError",
"(",
"error",
")",
"# Validate and coerce parameters to the appropriate types.",
"errors",
"=",
"{",
"}",
"sig",
"=",
"logic",
".",
"_doctor_signature",
"# If a `req_obj_type` was defined for the route, pass all request",
"# params to that type for validation/coercion",
"if",
"logic",
".",
"_doctor_req_obj_type",
":",
"annotation",
"=",
"logic",
".",
"_doctor_req_obj_type",
"try",
":",
"# NOTE: We calculate the value before applying native type in",
"# order to support UnionType types which dynamically modifies",
"# the native_type property based on the initialized value.",
"value",
"=",
"annotation",
"(",
"params",
")",
"params",
"=",
"annotation",
".",
"native_type",
"(",
"value",
")",
"except",
"TypeError",
":",
"logging",
".",
"exception",
"(",
"'Error casting and validating params with value `%s`.'",
",",
"params",
")",
"raise",
"except",
"TypeSystemError",
"as",
"e",
":",
"errors",
"[",
"'__all__'",
"]",
"=",
"e",
".",
"detail",
"else",
":",
"for",
"name",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
":",
"annotation",
"=",
"sig",
".",
"parameters",
"[",
"name",
"]",
".",
"annotation",
"if",
"annotation",
".",
"nullable",
"and",
"value",
"is",
"None",
":",
"continue",
"try",
":",
"# NOTE: We calculate the value before applying native type",
"# in order to support UnionType types which dynamically",
"# modifies the native_type property based on the initialized",
"# value.",
"value",
"=",
"annotation",
"(",
"value",
")",
"params",
"[",
"name",
"]",
"=",
"annotation",
".",
"native_type",
"(",
"value",
")",
"except",
"TypeSystemError",
"as",
"e",
":",
"errors",
"[",
"name",
"]",
"=",
"e",
".",
"detail",
"if",
"errors",
":",
"raise",
"TypeSystemError",
"(",
"errors",
",",
"errors",
"=",
"errors",
")",
"if",
"logic",
".",
"_doctor_req_obj_type",
":",
"# Pass any positional arguments followed by the coerced request",
"# parameters to the logic function.",
"response",
"=",
"logic",
"(",
"*",
"args",
",",
"params",
")",
"else",
":",
"# Only pass request parameters defined by the logic signature.",
"logic_params",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
"if",
"k",
"in",
"logic",
".",
"_doctor_params",
".",
"logic",
"}",
"response",
"=",
"logic",
"(",
"*",
"args",
",",
"*",
"*",
"logic_params",
")",
"# response validation",
"if",
"sig",
".",
"return_annotation",
"!=",
"sig",
".",
"empty",
":",
"return_annotation",
"=",
"sig",
".",
"return_annotation",
"_response",
"=",
"response",
"if",
"isinstance",
"(",
"response",
",",
"Response",
")",
":",
"_response",
"=",
"response",
".",
"content",
"# Check if our return annotation is a Response that supplied a",
"# type to validate against. If so, use that type for validation",
"# e.g. def logic() -> Response[MyType]",
"if",
"(",
"issubclass",
"(",
"return_annotation",
",",
"Response",
")",
"and",
"return_annotation",
".",
"__args__",
"is",
"not",
"None",
")",
":",
"return_annotation",
"=",
"return_annotation",
".",
"__args__",
"[",
"0",
"]",
"try",
":",
"return_annotation",
"(",
"_response",
")",
"except",
"TypeSystemError",
"as",
"e",
":",
"response_str",
"=",
"str",
"(",
"_response",
")",
"logging",
".",
"warning",
"(",
"'Response to %s %s does not validate: %s.'",
",",
"request",
".",
"method",
",",
"request",
".",
"path",
",",
"response_str",
",",
"exc_info",
"=",
"e",
")",
"if",
"should_raise_response_validation_errors",
"(",
")",
":",
"error",
"=",
"(",
"'Response to {method} {path} `{response}` does not'",
"' validate: {error}'",
".",
"format",
"(",
"method",
"=",
"request",
".",
"method",
",",
"path",
"=",
"request",
".",
"path",
",",
"response",
"=",
"response",
",",
"error",
"=",
"e",
".",
"detail",
")",
")",
"raise",
"TypeSystemError",
"(",
"error",
")",
"if",
"isinstance",
"(",
"response",
",",
"Response",
")",
":",
"status_code",
"=",
"response",
".",
"status_code",
"if",
"status_code",
"is",
"None",
":",
"status_code",
"=",
"STATUS_CODE_MAP",
".",
"get",
"(",
"request",
".",
"method",
",",
"200",
")",
"return",
"(",
"response",
".",
"content",
",",
"status_code",
",",
"response",
".",
"headers",
")",
"return",
"response",
",",
"STATUS_CODE_MAP",
".",
"get",
"(",
"request",
".",
"method",
",",
"200",
")",
"except",
"(",
"InvalidValueError",
",",
"TypeSystemError",
")",
"as",
"e",
":",
"errors",
"=",
"getattr",
"(",
"e",
",",
"'errors'",
",",
"None",
")",
"raise",
"HTTP400Exception",
"(",
"e",
",",
"errors",
"=",
"errors",
")",
"except",
"UnauthorizedError",
"as",
"e",
":",
"raise",
"HTTP401Exception",
"(",
"e",
")",
"except",
"ForbiddenError",
"as",
"e",
":",
"raise",
"HTTP403Exception",
"(",
"e",
")",
"except",
"NotFoundError",
"as",
"e",
":",
"raise",
"HTTP404Exception",
"(",
"e",
")",
"except",
"ImmutableError",
"as",
"e",
":",
"raise",
"HTTP409Exception",
"(",
"e",
")",
"except",
"Exception",
"as",
"e",
":",
"# Always re-raise exceptions when DEBUG is enabled for development.",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'DEBUG'",
",",
"False",
")",
":",
"raise",
"allowed_exceptions",
"=",
"logic",
".",
"_doctor_allowed_exceptions",
"if",
"allowed_exceptions",
"and",
"any",
"(",
"isinstance",
"(",
"e",
",",
"cls",
")",
"for",
"cls",
"in",
"allowed_exceptions",
")",
":",
"raise",
"logging",
".",
"exception",
"(",
"e",
")",
"raise",
"HTTP500Exception",
"(",
"'Uncaught error in logic function'",
")"
] | Handle a Flask HTTP request
:param handler: flask_restful.Resource: An instance of a Flask Restful
resource class.
:param tuple args: Any positional arguments passed to the wrapper method.
:param dict kwargs: Any keyword arguments passed to the wrapper method.
:param callable logic: The callable to invoke to actually perform the
business logic for this request. | [
"Handle",
"a",
"Flask",
"HTTP",
"request"
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/flask.py#L97-L246 |
upsight/doctor | doctor/flask.py | create_routes | def create_routes(routes: Tuple[Route]) -> List[Tuple[str, Resource]]:
"""A thin wrapper around create_routes that passes in flask specific values.
:param routes: A tuple containing the route and another tuple with
all http methods allowed for the route.
:returns: A list of tuples containing the route and generated handler.
"""
return doctor_create_routes(
routes, handle_http, default_base_handler_class=Resource) | python | def create_routes(routes: Tuple[Route]) -> List[Tuple[str, Resource]]:
"""A thin wrapper around create_routes that passes in flask specific values.
:param routes: A tuple containing the route and another tuple with
all http methods allowed for the route.
:returns: A list of tuples containing the route and generated handler.
"""
return doctor_create_routes(
routes, handle_http, default_base_handler_class=Resource) | [
"def",
"create_routes",
"(",
"routes",
":",
"Tuple",
"[",
"Route",
"]",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Resource",
"]",
"]",
":",
"return",
"doctor_create_routes",
"(",
"routes",
",",
"handle_http",
",",
"default_base_handler_class",
"=",
"Resource",
")"
] | A thin wrapper around create_routes that passes in flask specific values.
:param routes: A tuple containing the route and another tuple with
all http methods allowed for the route.
:returns: A list of tuples containing the route and generated handler. | [
"A",
"thin",
"wrapper",
"around",
"create_routes",
"that",
"passes",
"in",
"flask",
"specific",
"values",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/flask.py#L249-L257 |
kmedian/korr | korr/mcc.py | confusion_to_mcc | def confusion_to_mcc(*args):
"""Convert the confusion matrix to the Matthews correlation coefficient
Parameters:
-----------
cm : ndarray
2x2 confusion matrix with np.array([[tn, fp], [fn, tp]])
tn, fp, fn, tp : float
four scalar variables
- tn : number of true negatives
- fp : number of false positives
- fn : number of false negatives
- tp : number of true positives
Return:
-------
r : float
Matthews correlation coefficient
"""
if len(args) is 1:
tn, fp, fn, tp = args[0].ravel().astype(float)
elif len(args) is 4:
tn, fp, fn, tp = [float(a) for a in args]
else:
raise Exception((
"Input argument is not an 2x2 matrix, "
"nor 4 elements tn, fp, fn, tp."))
return (tp * tn - fp * fn) / np.sqrt(
(tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) | python | def confusion_to_mcc(*args):
"""Convert the confusion matrix to the Matthews correlation coefficient
Parameters:
-----------
cm : ndarray
2x2 confusion matrix with np.array([[tn, fp], [fn, tp]])
tn, fp, fn, tp : float
four scalar variables
- tn : number of true negatives
- fp : number of false positives
- fn : number of false negatives
- tp : number of true positives
Return:
-------
r : float
Matthews correlation coefficient
"""
if len(args) is 1:
tn, fp, fn, tp = args[0].ravel().astype(float)
elif len(args) is 4:
tn, fp, fn, tp = [float(a) for a in args]
else:
raise Exception((
"Input argument is not an 2x2 matrix, "
"nor 4 elements tn, fp, fn, tp."))
return (tp * tn - fp * fn) / np.sqrt(
(tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) | [
"def",
"confusion_to_mcc",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"is",
"1",
":",
"tn",
",",
"fp",
",",
"fn",
",",
"tp",
"=",
"args",
"[",
"0",
"]",
".",
"ravel",
"(",
")",
".",
"astype",
"(",
"float",
")",
"elif",
"len",
"(",
"args",
")",
"is",
"4",
":",
"tn",
",",
"fp",
",",
"fn",
",",
"tp",
"=",
"[",
"float",
"(",
"a",
")",
"for",
"a",
"in",
"args",
"]",
"else",
":",
"raise",
"Exception",
"(",
"(",
"\"Input argument is not an 2x2 matrix, \"",
"\"nor 4 elements tn, fp, fn, tp.\"",
")",
")",
"return",
"(",
"tp",
"*",
"tn",
"-",
"fp",
"*",
"fn",
")",
"/",
"np",
".",
"sqrt",
"(",
"(",
"tp",
"+",
"fp",
")",
"*",
"(",
"tp",
"+",
"fn",
")",
"*",
"(",
"tn",
"+",
"fp",
")",
"*",
"(",
"tn",
"+",
"fn",
")",
")"
] | Convert the confusion matrix to the Matthews correlation coefficient
Parameters:
-----------
cm : ndarray
2x2 confusion matrix with np.array([[tn, fp], [fn, tp]])
tn, fp, fn, tp : float
four scalar variables
- tn : number of true negatives
- fp : number of false positives
- fn : number of false negatives
- tp : number of true positives
Return:
-------
r : float
Matthews correlation coefficient | [
"Convert",
"the",
"confusion",
"matrix",
"to",
"the",
"Matthews",
"correlation",
"coefficient"
] | train | https://github.com/kmedian/korr/blob/4eb86fc14b1fc1b69204069b7753d115b327c937/korr/mcc.py#L6-L36 |
kmedian/korr | korr/mcc.py | mcc | def mcc(x, axis=0, autocorrect=False):
"""Matthews correlation
Parameters
----------
x : ndarray
dataset of binary [0,1] values
axis : int, optional
Variables as columns is the default (axis=0). If variables
are in the rows use axis=1
autocorrect : bool, optional
If all predictions are True or all are False, then MCC
returns np.NaN
Set autocorrect=True to return a 0.0 correlation instead.
Returns
-------
r : ndarray
Matthews correlation
p : ndarray
p-values of the Chi^2 test statistics
Notes:
------
(1) We cannot directly transform the Chi^2 test statistics to
the Matthews correlation because the relationship is
|r| = sqrt(chi2 / n)
chi2 = r * r * n
(2) The sign would be missing. Therefore, as a rule of thumbs,
If you want to optimize ABS(r_mcc) then just use the Chi2/n
directly (Divide Chi^2 by the number of observations)
Examples:
---------
import korr
r, pval = korr.mcc(X)
Alternatives:
-------------
from sklearn.metrics import matthews_corrcoef
r = matthews_corrcoef(y_true, y_pred)
"""
# transpose if axis<>0
if axis is not 0:
x = x.T
# read dimensions and
n, c = x.shape
# check if enough variables provided
if c < 2:
raise Exception(
"Only " + str(c) + " variables provided. Min. 2 required.")
# allocate variables
r = np.ones((c, c))
p = np.zeros((c, c))
# compute each (i,j)-th correlation
for i in range(0, c):
for j in range(i + 1, c):
cm = confusion(x[:, i], x[:, j])
r[i, j] = confusion_to_mcc(cm)
r[j, i] = r[i, j]
p[i, j] = 1 - scipy.stats.chi2.cdf(r[i, j] * r[i, j] * n, 1)
p[j, i] = p[i, j]
# replace NaN with 0.0
if autocorrect:
r = np.nan_to_num(r)
# done
return r, p | python | def mcc(x, axis=0, autocorrect=False):
"""Matthews correlation
Parameters
----------
x : ndarray
dataset of binary [0,1] values
axis : int, optional
Variables as columns is the default (axis=0). If variables
are in the rows use axis=1
autocorrect : bool, optional
If all predictions are True or all are False, then MCC
returns np.NaN
Set autocorrect=True to return a 0.0 correlation instead.
Returns
-------
r : ndarray
Matthews correlation
p : ndarray
p-values of the Chi^2 test statistics
Notes:
------
(1) We cannot directly transform the Chi^2 test statistics to
the Matthews correlation because the relationship is
|r| = sqrt(chi2 / n)
chi2 = r * r * n
(2) The sign would be missing. Therefore, as a rule of thumbs,
If you want to optimize ABS(r_mcc) then just use the Chi2/n
directly (Divide Chi^2 by the number of observations)
Examples:
---------
import korr
r, pval = korr.mcc(X)
Alternatives:
-------------
from sklearn.metrics import matthews_corrcoef
r = matthews_corrcoef(y_true, y_pred)
"""
# transpose if axis<>0
if axis is not 0:
x = x.T
# read dimensions and
n, c = x.shape
# check if enough variables provided
if c < 2:
raise Exception(
"Only " + str(c) + " variables provided. Min. 2 required.")
# allocate variables
r = np.ones((c, c))
p = np.zeros((c, c))
# compute each (i,j)-th correlation
for i in range(0, c):
for j in range(i + 1, c):
cm = confusion(x[:, i], x[:, j])
r[i, j] = confusion_to_mcc(cm)
r[j, i] = r[i, j]
p[i, j] = 1 - scipy.stats.chi2.cdf(r[i, j] * r[i, j] * n, 1)
p[j, i] = p[i, j]
# replace NaN with 0.0
if autocorrect:
r = np.nan_to_num(r)
# done
return r, p | [
"def",
"mcc",
"(",
"x",
",",
"axis",
"=",
"0",
",",
"autocorrect",
"=",
"False",
")",
":",
"# transpose if axis<>0",
"if",
"axis",
"is",
"not",
"0",
":",
"x",
"=",
"x",
".",
"T",
"# read dimensions and",
"n",
",",
"c",
"=",
"x",
".",
"shape",
"# check if enough variables provided",
"if",
"c",
"<",
"2",
":",
"raise",
"Exception",
"(",
"\"Only \"",
"+",
"str",
"(",
"c",
")",
"+",
"\" variables provided. Min. 2 required.\"",
")",
"# allocate variables",
"r",
"=",
"np",
".",
"ones",
"(",
"(",
"c",
",",
"c",
")",
")",
"p",
"=",
"np",
".",
"zeros",
"(",
"(",
"c",
",",
"c",
")",
")",
"# compute each (i,j)-th correlation",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"c",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"c",
")",
":",
"cm",
"=",
"confusion",
"(",
"x",
"[",
":",
",",
"i",
"]",
",",
"x",
"[",
":",
",",
"j",
"]",
")",
"r",
"[",
"i",
",",
"j",
"]",
"=",
"confusion_to_mcc",
"(",
"cm",
")",
"r",
"[",
"j",
",",
"i",
"]",
"=",
"r",
"[",
"i",
",",
"j",
"]",
"p",
"[",
"i",
",",
"j",
"]",
"=",
"1",
"-",
"scipy",
".",
"stats",
".",
"chi2",
".",
"cdf",
"(",
"r",
"[",
"i",
",",
"j",
"]",
"*",
"r",
"[",
"i",
",",
"j",
"]",
"*",
"n",
",",
"1",
")",
"p",
"[",
"j",
",",
"i",
"]",
"=",
"p",
"[",
"i",
",",
"j",
"]",
"# replace NaN with 0.0",
"if",
"autocorrect",
":",
"r",
"=",
"np",
".",
"nan_to_num",
"(",
"r",
")",
"# done",
"return",
"r",
",",
"p"
] | Matthews correlation
Parameters
----------
x : ndarray
dataset of binary [0,1] values
axis : int, optional
Variables as columns is the default (axis=0). If variables
are in the rows use axis=1
autocorrect : bool, optional
If all predictions are True or all are False, then MCC
returns np.NaN
Set autocorrect=True to return a 0.0 correlation instead.
Returns
-------
r : ndarray
Matthews correlation
p : ndarray
p-values of the Chi^2 test statistics
Notes:
------
(1) We cannot directly transform the Chi^2 test statistics to
the Matthews correlation because the relationship is
|r| = sqrt(chi2 / n)
chi2 = r * r * n
(2) The sign would be missing. Therefore, as a rule of thumbs,
If you want to optimize ABS(r_mcc) then just use the Chi2/n
directly (Divide Chi^2 by the number of observations)
Examples:
---------
import korr
r, pval = korr.mcc(X)
Alternatives:
-------------
from sklearn.metrics import matthews_corrcoef
r = matthews_corrcoef(y_true, y_pred) | [
"Matthews",
"correlation"
] | train | https://github.com/kmedian/korr/blob/4eb86fc14b1fc1b69204069b7753d115b327c937/korr/mcc.py#L39-L116 |
eumis/pyviews | pyviews/rendering/node.py | create_node | def create_node(xml_node: XmlNode, **init_args):
'''Creates node from xml node using namespace as module and tag name as class name'''
inst_type = get_inst_type(xml_node)
init_args['xml_node'] = xml_node
inst = create_inst(inst_type, **init_args)
if not isinstance(inst, Node):
inst = convert_to_node(inst, **init_args)
return inst | python | def create_node(xml_node: XmlNode, **init_args):
'''Creates node from xml node using namespace as module and tag name as class name'''
inst_type = get_inst_type(xml_node)
init_args['xml_node'] = xml_node
inst = create_inst(inst_type, **init_args)
if not isinstance(inst, Node):
inst = convert_to_node(inst, **init_args)
return inst | [
"def",
"create_node",
"(",
"xml_node",
":",
"XmlNode",
",",
"*",
"*",
"init_args",
")",
":",
"inst_type",
"=",
"get_inst_type",
"(",
"xml_node",
")",
"init_args",
"[",
"'xml_node'",
"]",
"=",
"xml_node",
"inst",
"=",
"create_inst",
"(",
"inst_type",
",",
"*",
"*",
"init_args",
")",
"if",
"not",
"isinstance",
"(",
"inst",
",",
"Node",
")",
":",
"inst",
"=",
"convert_to_node",
"(",
"inst",
",",
"*",
"*",
"init_args",
")",
"return",
"inst"
] | Creates node from xml node using namespace as module and tag name as class name | [
"Creates",
"node",
"from",
"xml",
"node",
"using",
"namespace",
"as",
"module",
"and",
"tag",
"name",
"as",
"class",
"name"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/node.py#L11-L18 |
eumis/pyviews | pyviews/rendering/node.py | get_inst_type | def get_inst_type(xml_node: XmlNode):
'''Returns type by xml node'''
(module_path, class_name) = (xml_node.namespace, xml_node.name)
try:
return import_module(module_path).__dict__[class_name]
except (KeyError, ImportError, ModuleNotFoundError):
message = 'Import "{0}.{1}" is failed.'.format(module_path, class_name)
raise RenderingError(message, xml_node.view_info) | python | def get_inst_type(xml_node: XmlNode):
'''Returns type by xml node'''
(module_path, class_name) = (xml_node.namespace, xml_node.name)
try:
return import_module(module_path).__dict__[class_name]
except (KeyError, ImportError, ModuleNotFoundError):
message = 'Import "{0}.{1}" is failed.'.format(module_path, class_name)
raise RenderingError(message, xml_node.view_info) | [
"def",
"get_inst_type",
"(",
"xml_node",
":",
"XmlNode",
")",
":",
"(",
"module_path",
",",
"class_name",
")",
"=",
"(",
"xml_node",
".",
"namespace",
",",
"xml_node",
".",
"name",
")",
"try",
":",
"return",
"import_module",
"(",
"module_path",
")",
".",
"__dict__",
"[",
"class_name",
"]",
"except",
"(",
"KeyError",
",",
"ImportError",
",",
"ModuleNotFoundError",
")",
":",
"message",
"=",
"'Import \"{0}.{1}\" is failed.'",
".",
"format",
"(",
"module_path",
",",
"class_name",
")",
"raise",
"RenderingError",
"(",
"message",
",",
"xml_node",
".",
"view_info",
")"
] | Returns type by xml node | [
"Returns",
"type",
"by",
"xml",
"node"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/node.py#L20-L27 |
eumis/pyviews | pyviews/rendering/node.py | create_inst | def create_inst(inst_type, **init_args):
'''Creates class instance with args'''
args, kwargs = get_init_args(inst_type, init_args)
return inst_type(*args, **kwargs) | python | def create_inst(inst_type, **init_args):
'''Creates class instance with args'''
args, kwargs = get_init_args(inst_type, init_args)
return inst_type(*args, **kwargs) | [
"def",
"create_inst",
"(",
"inst_type",
",",
"*",
"*",
"init_args",
")",
":",
"args",
",",
"kwargs",
"=",
"get_init_args",
"(",
"inst_type",
",",
"init_args",
")",
"return",
"inst_type",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Creates class instance with args | [
"Creates",
"class",
"instance",
"with",
"args"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/node.py#L29-L32 |
eumis/pyviews | pyviews/rendering/node.py | get_init_args | def get_init_args(inst_type, init_args: dict, add_kwargs=False) -> Tuple[List, Dict]:
'''Returns tuple with args and kwargs to pass it to inst_type constructor'''
try:
parameters = signature(inst_type).parameters.values()
args_keys = [p.name for p in parameters \
if p.kind in [Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD] \
and p.default == Parameter.empty]
args = [init_args[key] for key in args_keys]
kwargs = _get_var_kwargs(parameters, args_keys, init_args)\
if add_kwargs else\
_get_kwargs(parameters, init_args)
except KeyError as key_error:
msg_format = 'parameter with key "{0}" is not found in node args'
raise RenderingError(msg_format.format(key_error.args[0]))
return (args, kwargs) | python | def get_init_args(inst_type, init_args: dict, add_kwargs=False) -> Tuple[List, Dict]:
'''Returns tuple with args and kwargs to pass it to inst_type constructor'''
try:
parameters = signature(inst_type).parameters.values()
args_keys = [p.name for p in parameters \
if p.kind in [Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD] \
and p.default == Parameter.empty]
args = [init_args[key] for key in args_keys]
kwargs = _get_var_kwargs(parameters, args_keys, init_args)\
if add_kwargs else\
_get_kwargs(parameters, init_args)
except KeyError as key_error:
msg_format = 'parameter with key "{0}" is not found in node args'
raise RenderingError(msg_format.format(key_error.args[0]))
return (args, kwargs) | [
"def",
"get_init_args",
"(",
"inst_type",
",",
"init_args",
":",
"dict",
",",
"add_kwargs",
"=",
"False",
")",
"->",
"Tuple",
"[",
"List",
",",
"Dict",
"]",
":",
"try",
":",
"parameters",
"=",
"signature",
"(",
"inst_type",
")",
".",
"parameters",
".",
"values",
"(",
")",
"args_keys",
"=",
"[",
"p",
".",
"name",
"for",
"p",
"in",
"parameters",
"if",
"p",
".",
"kind",
"in",
"[",
"Parameter",
".",
"POSITIONAL_ONLY",
",",
"Parameter",
".",
"POSITIONAL_OR_KEYWORD",
"]",
"and",
"p",
".",
"default",
"==",
"Parameter",
".",
"empty",
"]",
"args",
"=",
"[",
"init_args",
"[",
"key",
"]",
"for",
"key",
"in",
"args_keys",
"]",
"kwargs",
"=",
"_get_var_kwargs",
"(",
"parameters",
",",
"args_keys",
",",
"init_args",
")",
"if",
"add_kwargs",
"else",
"_get_kwargs",
"(",
"parameters",
",",
"init_args",
")",
"except",
"KeyError",
"as",
"key_error",
":",
"msg_format",
"=",
"'parameter with key \"{0}\" is not found in node args'",
"raise",
"RenderingError",
"(",
"msg_format",
".",
"format",
"(",
"key_error",
".",
"args",
"[",
"0",
"]",
")",
")",
"return",
"(",
"args",
",",
"kwargs",
")"
] | Returns tuple with args and kwargs to pass it to inst_type constructor | [
"Returns",
"tuple",
"with",
"args",
"and",
"kwargs",
"to",
"pass",
"it",
"to",
"inst_type",
"constructor"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/node.py#L34-L48 |
eumis/pyviews | pyviews/rendering/node.py | convert_to_node | def convert_to_node(instance, xml_node: XmlNode, node_globals: InheritedDict = None)\
-> InstanceNode:
'''Wraps passed instance with InstanceNode'''
return InstanceNode(instance, xml_node, node_globals) | python | def convert_to_node(instance, xml_node: XmlNode, node_globals: InheritedDict = None)\
-> InstanceNode:
'''Wraps passed instance with InstanceNode'''
return InstanceNode(instance, xml_node, node_globals) | [
"def",
"convert_to_node",
"(",
"instance",
",",
"xml_node",
":",
"XmlNode",
",",
"node_globals",
":",
"InheritedDict",
"=",
"None",
")",
"->",
"InstanceNode",
":",
"return",
"InstanceNode",
"(",
"instance",
",",
"xml_node",
",",
"node_globals",
")"
] | Wraps passed instance with InstanceNode | [
"Wraps",
"passed",
"instance",
"with",
"InstanceNode"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/node.py#L67-L70 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/driver_helper.py | get_logger_with_thread_id | def get_logger_with_thread_id(context):
"""
Create QS Logger for command context AutoLoadCommandContext, ResourceCommandContext
or ResourceRemoteCommandContext with thread name
:param context:
:return:
"""
logger = LoggingSessionContext.get_logger_for_context(context)
child = logger.getChild(threading.currentThread().name)
for handler in logger.handlers:
child.addHandler(handler)
child.level = logger.level
for log_filter in logger.filters:
child.addFilter(log_filter)
return child | python | def get_logger_with_thread_id(context):
"""
Create QS Logger for command context AutoLoadCommandContext, ResourceCommandContext
or ResourceRemoteCommandContext with thread name
:param context:
:return:
"""
logger = LoggingSessionContext.get_logger_for_context(context)
child = logger.getChild(threading.currentThread().name)
for handler in logger.handlers:
child.addHandler(handler)
child.level = logger.level
for log_filter in logger.filters:
child.addFilter(log_filter)
return child | [
"def",
"get_logger_with_thread_id",
"(",
"context",
")",
":",
"logger",
"=",
"LoggingSessionContext",
".",
"get_logger_for_context",
"(",
"context",
")",
"child",
"=",
"logger",
".",
"getChild",
"(",
"threading",
".",
"currentThread",
"(",
")",
".",
"name",
")",
"for",
"handler",
"in",
"logger",
".",
"handlers",
":",
"child",
".",
"addHandler",
"(",
"handler",
")",
"child",
".",
"level",
"=",
"logger",
".",
"level",
"for",
"log_filter",
"in",
"logger",
".",
"filters",
":",
"child",
".",
"addFilter",
"(",
"log_filter",
")",
"return",
"child"
] | Create QS Logger for command context AutoLoadCommandContext, ResourceCommandContext
or ResourceRemoteCommandContext with thread name
:param context:
:return: | [
"Create",
"QS",
"Logger",
"for",
"command",
"context",
"AutoLoadCommandContext",
"ResourceCommandContext",
"or",
"ResourceRemoteCommandContext",
"with",
"thread",
"name",
":",
"param",
"context",
":",
":",
"return",
":"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/driver_helper.py#L18-L32 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/driver_helper.py | get_snmp_parameters_from_command_context | def get_snmp_parameters_from_command_context(resource_config, api, force_decrypt=False):
"""
:param ResourceCommandContext resource_config: command context
:return:
"""
if '3' in resource_config.snmp_version:
return SNMPV3Parameters(ip=resource_config.address,
snmp_user=resource_config.snmp_v3_user or '',
snmp_password=api.DecryptPassword(resource_config.snmp_v3_password).Value or '',
snmp_private_key=resource_config.snmp_v3_private_key or '',
auth_protocol=resource_config.snmp_v3_auth_protocol or SNMPV3Parameters.AUTH_NO_AUTH,
private_key_protocol=resource_config.snmp_v3_priv_protocol or SNMPV3Parameters.PRIV_NO_PRIV).get_valid()
else:
if resource_config.shell_name or force_decrypt:
write_community = api.DecryptPassword(resource_config.snmp_write_community).Value or ''
else:
write_community = resource_config.snmp_write_community or ''
if write_community:
return SNMPV2WriteParameters(ip=resource_config.address, snmp_write_community=write_community)
else:
if resource_config.shell_name or force_decrypt:
read_community = api.DecryptPassword(resource_config.snmp_read_community).Value or ''
else:
read_community = resource_config.snmp_read_community or ''
return SNMPV2ReadParameters(ip=resource_config.address, snmp_read_community=read_community) | python | def get_snmp_parameters_from_command_context(resource_config, api, force_decrypt=False):
"""
:param ResourceCommandContext resource_config: command context
:return:
"""
if '3' in resource_config.snmp_version:
return SNMPV3Parameters(ip=resource_config.address,
snmp_user=resource_config.snmp_v3_user or '',
snmp_password=api.DecryptPassword(resource_config.snmp_v3_password).Value or '',
snmp_private_key=resource_config.snmp_v3_private_key or '',
auth_protocol=resource_config.snmp_v3_auth_protocol or SNMPV3Parameters.AUTH_NO_AUTH,
private_key_protocol=resource_config.snmp_v3_priv_protocol or SNMPV3Parameters.PRIV_NO_PRIV).get_valid()
else:
if resource_config.shell_name or force_decrypt:
write_community = api.DecryptPassword(resource_config.snmp_write_community).Value or ''
else:
write_community = resource_config.snmp_write_community or ''
if write_community:
return SNMPV2WriteParameters(ip=resource_config.address, snmp_write_community=write_community)
else:
if resource_config.shell_name or force_decrypt:
read_community = api.DecryptPassword(resource_config.snmp_read_community).Value or ''
else:
read_community = resource_config.snmp_read_community or ''
return SNMPV2ReadParameters(ip=resource_config.address, snmp_read_community=read_community) | [
"def",
"get_snmp_parameters_from_command_context",
"(",
"resource_config",
",",
"api",
",",
"force_decrypt",
"=",
"False",
")",
":",
"if",
"'3'",
"in",
"resource_config",
".",
"snmp_version",
":",
"return",
"SNMPV3Parameters",
"(",
"ip",
"=",
"resource_config",
".",
"address",
",",
"snmp_user",
"=",
"resource_config",
".",
"snmp_v3_user",
"or",
"''",
",",
"snmp_password",
"=",
"api",
".",
"DecryptPassword",
"(",
"resource_config",
".",
"snmp_v3_password",
")",
".",
"Value",
"or",
"''",
",",
"snmp_private_key",
"=",
"resource_config",
".",
"snmp_v3_private_key",
"or",
"''",
",",
"auth_protocol",
"=",
"resource_config",
".",
"snmp_v3_auth_protocol",
"or",
"SNMPV3Parameters",
".",
"AUTH_NO_AUTH",
",",
"private_key_protocol",
"=",
"resource_config",
".",
"snmp_v3_priv_protocol",
"or",
"SNMPV3Parameters",
".",
"PRIV_NO_PRIV",
")",
".",
"get_valid",
"(",
")",
"else",
":",
"if",
"resource_config",
".",
"shell_name",
"or",
"force_decrypt",
":",
"write_community",
"=",
"api",
".",
"DecryptPassword",
"(",
"resource_config",
".",
"snmp_write_community",
")",
".",
"Value",
"or",
"''",
"else",
":",
"write_community",
"=",
"resource_config",
".",
"snmp_write_community",
"or",
"''",
"if",
"write_community",
":",
"return",
"SNMPV2WriteParameters",
"(",
"ip",
"=",
"resource_config",
".",
"address",
",",
"snmp_write_community",
"=",
"write_community",
")",
"else",
":",
"if",
"resource_config",
".",
"shell_name",
"or",
"force_decrypt",
":",
"read_community",
"=",
"api",
".",
"DecryptPassword",
"(",
"resource_config",
".",
"snmp_read_community",
")",
".",
"Value",
"or",
"''",
"else",
":",
"read_community",
"=",
"resource_config",
".",
"snmp_read_community",
"or",
"''",
"return",
"SNMPV2ReadParameters",
"(",
"ip",
"=",
"resource_config",
".",
"address",
",",
"snmp_read_community",
"=",
"read_community",
")"
] | :param ResourceCommandContext resource_config: command context
:return: | [
":",
"param",
"ResourceCommandContext",
"resource_config",
":",
"command",
"context",
":",
"return",
":"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/driver_helper.py#L45-L72 |
Workiva/furious | furious/context/auto_context.py | AutoContext.add | def add(self, target, args=None, kwargs=None, **options):
"""Add an Async job to this context.
Like Context.add(): creates an Async and adds it to our list of tasks.
but also calls _auto_insert_check() to add tasks to queues
automatically.
"""
# In superclass, add new task to our list of tasks
target = super(
AutoContext, self).add(target, args, kwargs, **options)
self._auto_insert_check()
return target | python | def add(self, target, args=None, kwargs=None, **options):
"""Add an Async job to this context.
Like Context.add(): creates an Async and adds it to our list of tasks.
but also calls _auto_insert_check() to add tasks to queues
automatically.
"""
# In superclass, add new task to our list of tasks
target = super(
AutoContext, self).add(target, args, kwargs, **options)
self._auto_insert_check()
return target | [
"def",
"add",
"(",
"self",
",",
"target",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"# In superclass, add new task to our list of tasks",
"target",
"=",
"super",
"(",
"AutoContext",
",",
"self",
")",
".",
"add",
"(",
"target",
",",
"args",
",",
"kwargs",
",",
"*",
"*",
"options",
")",
"self",
".",
"_auto_insert_check",
"(",
")",
"return",
"target"
] | Add an Async job to this context.
Like Context.add(): creates an Async and adds it to our list of tasks.
but also calls _auto_insert_check() to add tasks to queues
automatically. | [
"Add",
"an",
"Async",
"job",
"to",
"this",
"context",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/auto_context.py#L40-L54 |
Workiva/furious | furious/context/auto_context.py | AutoContext._auto_insert_check | def _auto_insert_check(self):
"""Automatically insert tasks asynchronously.
Depending on batch_size, insert or wait until next call.
"""
if not self.batch_size:
return
if len(self._tasks) >= self.batch_size:
self._handle_tasks() | python | def _auto_insert_check(self):
"""Automatically insert tasks asynchronously.
Depending on batch_size, insert or wait until next call.
"""
if not self.batch_size:
return
if len(self._tasks) >= self.batch_size:
self._handle_tasks() | [
"def",
"_auto_insert_check",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"batch_size",
":",
"return",
"if",
"len",
"(",
"self",
".",
"_tasks",
")",
">=",
"self",
".",
"batch_size",
":",
"self",
".",
"_handle_tasks",
"(",
")"
] | Automatically insert tasks asynchronously.
Depending on batch_size, insert or wait until next call. | [
"Automatically",
"insert",
"tasks",
"asynchronously",
".",
"Depending",
"on",
"batch_size",
"insert",
"or",
"wait",
"until",
"next",
"call",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/auto_context.py#L56-L65 |
wallento/riscv-python-model | riscvmodel/insn.py | isa | def isa(mnemonic: str, opcode: int, funct3: int=None, funct7: int=None, *, variant=RV32I, extension=None):
"""
Decorator for the instructions. The decorator contains the static information for the instructions, in particular
the encoding parameters and the assembler mnemonic.
:param mnemonic: Assembler mnemonic
:param opcode: Opcode of this instruction
:param funct3: 3 bit function code on bits 14 to 12 (R-, I-, S- and B-type)
:param funct7: 7 bit function code on bits 31 to 25 (R-type)
:return: Wrapper class that overwrites the actual definition and contains static data
"""
def wrapper(wrapped):
"""Get wrapper"""
class WrappedClass(wrapped):
"""Generic wrapper class"""
_mnemonic = mnemonic
_opcode = opcode
_funct3 = funct3
_funct7 = funct7
_variant = variant
_extension = extension
@staticmethod
def _match(machinecode: int):
"""Try to match a machine code to this instruction"""
f3 = (machinecode >> 12) & 0x7
f7 = (machinecode >> 25) & 0x7f
if funct3 is not None and f3 != funct3:
return False
if funct7 is not None and f7 != funct7:
return False
return True
WrappedClass.__name__ = wrapped.__name__
WrappedClass.__module__ = wrapped.__module__
WrappedClass.__qualname__ = wrapped.__qualname__
return WrappedClass
return wrapper | python | def isa(mnemonic: str, opcode: int, funct3: int=None, funct7: int=None, *, variant=RV32I, extension=None):
"""
Decorator for the instructions. The decorator contains the static information for the instructions, in particular
the encoding parameters and the assembler mnemonic.
:param mnemonic: Assembler mnemonic
:param opcode: Opcode of this instruction
:param funct3: 3 bit function code on bits 14 to 12 (R-, I-, S- and B-type)
:param funct7: 7 bit function code on bits 31 to 25 (R-type)
:return: Wrapper class that overwrites the actual definition and contains static data
"""
def wrapper(wrapped):
"""Get wrapper"""
class WrappedClass(wrapped):
"""Generic wrapper class"""
_mnemonic = mnemonic
_opcode = opcode
_funct3 = funct3
_funct7 = funct7
_variant = variant
_extension = extension
@staticmethod
def _match(machinecode: int):
"""Try to match a machine code to this instruction"""
f3 = (machinecode >> 12) & 0x7
f7 = (machinecode >> 25) & 0x7f
if funct3 is not None and f3 != funct3:
return False
if funct7 is not None and f7 != funct7:
return False
return True
WrappedClass.__name__ = wrapped.__name__
WrappedClass.__module__ = wrapped.__module__
WrappedClass.__qualname__ = wrapped.__qualname__
return WrappedClass
return wrapper | [
"def",
"isa",
"(",
"mnemonic",
":",
"str",
",",
"opcode",
":",
"int",
",",
"funct3",
":",
"int",
"=",
"None",
",",
"funct7",
":",
"int",
"=",
"None",
",",
"*",
",",
"variant",
"=",
"RV32I",
",",
"extension",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"wrapped",
")",
":",
"\"\"\"Get wrapper\"\"\"",
"class",
"WrappedClass",
"(",
"wrapped",
")",
":",
"\"\"\"Generic wrapper class\"\"\"",
"_mnemonic",
"=",
"mnemonic",
"_opcode",
"=",
"opcode",
"_funct3",
"=",
"funct3",
"_funct7",
"=",
"funct7",
"_variant",
"=",
"variant",
"_extension",
"=",
"extension",
"@",
"staticmethod",
"def",
"_match",
"(",
"machinecode",
":",
"int",
")",
":",
"\"\"\"Try to match a machine code to this instruction\"\"\"",
"f3",
"=",
"(",
"machinecode",
">>",
"12",
")",
"&",
"0x7",
"f7",
"=",
"(",
"machinecode",
">>",
"25",
")",
"&",
"0x7f",
"if",
"funct3",
"is",
"not",
"None",
"and",
"f3",
"!=",
"funct3",
":",
"return",
"False",
"if",
"funct7",
"is",
"not",
"None",
"and",
"f7",
"!=",
"funct7",
":",
"return",
"False",
"return",
"True",
"WrappedClass",
".",
"__name__",
"=",
"wrapped",
".",
"__name__",
"WrappedClass",
".",
"__module__",
"=",
"wrapped",
".",
"__module__",
"WrappedClass",
".",
"__qualname__",
"=",
"wrapped",
".",
"__qualname__",
"return",
"WrappedClass",
"return",
"wrapper"
] | Decorator for the instructions. The decorator contains the static information for the instructions, in particular
the encoding parameters and the assembler mnemonic.
:param mnemonic: Assembler mnemonic
:param opcode: Opcode of this instruction
:param funct3: 3 bit function code on bits 14 to 12 (R-, I-, S- and B-type)
:param funct7: 7 bit function code on bits 31 to 25 (R-type)
:return: Wrapper class that overwrites the actual definition and contains static data | [
"Decorator",
"for",
"the",
"instructions",
".",
"The",
"decorator",
"contains",
"the",
"static",
"information",
"for",
"the",
"instructions",
"in",
"particular",
"the",
"encoding",
"parameters",
"and",
"the",
"assembler",
"mnemonic",
"."
] | train | https://github.com/wallento/riscv-python-model/blob/51df07d16b79b143eb3d3c1e95bf26030c64a39b/riscvmodel/insn.py#L394-L431 |
wallento/riscv-python-model | riscvmodel/insn.py | get_insns | def get_insns(cls = None):
"""
Get all Instructions. This is based on all known subclasses of `cls`. If non is given, all Instructions are returned.
Only such instructions are returned that can be generated, i.e., that have a mnemonic, opcode, etc. So other
classes in the hierarchy are not matched.
:param cls: Base class to get list
:type cls: Instruction
:return: List of instructions
"""
insns = []
if cls is None:
cls = Instruction
if "_mnemonic" in cls.__dict__.keys():
insns = [cls]
for subcls in cls.__subclasses__():
insns += get_insns(subcls)
return insns | python | def get_insns(cls = None):
"""
Get all Instructions. This is based on all known subclasses of `cls`. If non is given, all Instructions are returned.
Only such instructions are returned that can be generated, i.e., that have a mnemonic, opcode, etc. So other
classes in the hierarchy are not matched.
:param cls: Base class to get list
:type cls: Instruction
:return: List of instructions
"""
insns = []
if cls is None:
cls = Instruction
if "_mnemonic" in cls.__dict__.keys():
insns = [cls]
for subcls in cls.__subclasses__():
insns += get_insns(subcls)
return insns | [
"def",
"get_insns",
"(",
"cls",
"=",
"None",
")",
":",
"insns",
"=",
"[",
"]",
"if",
"cls",
"is",
"None",
":",
"cls",
"=",
"Instruction",
"if",
"\"_mnemonic\"",
"in",
"cls",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"insns",
"=",
"[",
"cls",
"]",
"for",
"subcls",
"in",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"insns",
"+=",
"get_insns",
"(",
"subcls",
")",
"return",
"insns"
] | Get all Instructions. This is based on all known subclasses of `cls`. If non is given, all Instructions are returned.
Only such instructions are returned that can be generated, i.e., that have a mnemonic, opcode, etc. So other
classes in the hierarchy are not matched.
:param cls: Base class to get list
:type cls: Instruction
:return: List of instructions | [
"Get",
"all",
"Instructions",
".",
"This",
"is",
"based",
"on",
"all",
"known",
"subclasses",
"of",
"cls",
".",
"If",
"non",
"is",
"given",
"all",
"Instructions",
"are",
"returned",
".",
"Only",
"such",
"instructions",
"are",
"returned",
"that",
"can",
"be",
"generated",
"i",
".",
"e",
".",
"that",
"have",
"a",
"mnemonic",
"opcode",
"etc",
".",
"So",
"other",
"classes",
"in",
"the",
"hierarchy",
"are",
"not",
"matched",
"."
] | train | https://github.com/wallento/riscv-python-model/blob/51df07d16b79b143eb3d3c1e95bf26030c64a39b/riscvmodel/insn.py#L446-L467 |
wallento/riscv-python-model | riscvmodel/insn.py | reverse_lookup | def reverse_lookup(mnemonic: str):
"""
Find instruction that matches the mnemonic.
:param mnemonic: Mnemonic to match
:return: :class:`Instruction` that matches or None
"""
for i in get_insns():
if "_mnemonic" in i.__dict__ and i._mnemonic == mnemonic:
return i
return None | python | def reverse_lookup(mnemonic: str):
"""
Find instruction that matches the mnemonic.
:param mnemonic: Mnemonic to match
:return: :class:`Instruction` that matches or None
"""
for i in get_insns():
if "_mnemonic" in i.__dict__ and i._mnemonic == mnemonic:
return i
return None | [
"def",
"reverse_lookup",
"(",
"mnemonic",
":",
"str",
")",
":",
"for",
"i",
"in",
"get_insns",
"(",
")",
":",
"if",
"\"_mnemonic\"",
"in",
"i",
".",
"__dict__",
"and",
"i",
".",
"_mnemonic",
"==",
"mnemonic",
":",
"return",
"i",
"return",
"None"
] | Find instruction that matches the mnemonic.
:param mnemonic: Mnemonic to match
:return: :class:`Instruction` that matches or None | [
"Find",
"instruction",
"that",
"matches",
"the",
"mnemonic",
"."
] | train | https://github.com/wallento/riscv-python-model/blob/51df07d16b79b143eb3d3c1e95bf26030c64a39b/riscvmodel/insn.py#L470-L481 |
upsight/doctor | doctor/types.py | get_value_from_schema | def get_value_from_schema(schema, definition: dict, key: str,
definition_key: str):
"""Gets a value from a schema and definition.
If the value has references it will recursively attempt to resolve them.
:param ResourceSchema schema: The resource schema.
:param dict definition: The definition dict from the schema.
:param str key: The key to use to get the value from the schema.
:param str definition_key: The name of the definition.
:returns: The value.
:raises TypeSystemError: If the key can't be found in the schema/definition
or we can't resolve the definition.
"""
resolved_definition = definition.copy()
if '$ref' in resolved_definition:
try:
# NOTE: The resolve method recursively resolves references, so
# we don't need to worry about that in this function.
resolved_definition = schema.resolve(definition['$ref'])
except SchemaError as e:
raise TypeSystemError(str(e))
try:
value = resolved_definition[key]
except KeyError:
# Before raising an error, the resolved definition may have an array
# or object inside it that needs to be resolved in order to get
# values. Attempt that here and then fail if we still can't find
# the key we are looking for.
# If the key was missing and this is an array, try to resolve it
# from the items key.
if resolved_definition['type'] == 'array':
return [
get_value_from_schema(schema, resolved_definition['items'], key,
definition_key)
]
# If the key was missing and this is an object, resolve it from it's
# properties.
elif resolved_definition['type'] == 'object':
value = {}
for prop, definition in resolved_definition['properties'].items():
value[prop] = get_value_from_schema(
schema, definition, key, definition_key)
return value
raise TypeSystemError(
'Definition `{}` is missing a {}.'.format(
definition_key, key))
return value | python | def get_value_from_schema(schema, definition: dict, key: str,
definition_key: str):
"""Gets a value from a schema and definition.
If the value has references it will recursively attempt to resolve them.
:param ResourceSchema schema: The resource schema.
:param dict definition: The definition dict from the schema.
:param str key: The key to use to get the value from the schema.
:param str definition_key: The name of the definition.
:returns: The value.
:raises TypeSystemError: If the key can't be found in the schema/definition
or we can't resolve the definition.
"""
resolved_definition = definition.copy()
if '$ref' in resolved_definition:
try:
# NOTE: The resolve method recursively resolves references, so
# we don't need to worry about that in this function.
resolved_definition = schema.resolve(definition['$ref'])
except SchemaError as e:
raise TypeSystemError(str(e))
try:
value = resolved_definition[key]
except KeyError:
# Before raising an error, the resolved definition may have an array
# or object inside it that needs to be resolved in order to get
# values. Attempt that here and then fail if we still can't find
# the key we are looking for.
# If the key was missing and this is an array, try to resolve it
# from the items key.
if resolved_definition['type'] == 'array':
return [
get_value_from_schema(schema, resolved_definition['items'], key,
definition_key)
]
# If the key was missing and this is an object, resolve it from it's
# properties.
elif resolved_definition['type'] == 'object':
value = {}
for prop, definition in resolved_definition['properties'].items():
value[prop] = get_value_from_schema(
schema, definition, key, definition_key)
return value
raise TypeSystemError(
'Definition `{}` is missing a {}.'.format(
definition_key, key))
return value | [
"def",
"get_value_from_schema",
"(",
"schema",
",",
"definition",
":",
"dict",
",",
"key",
":",
"str",
",",
"definition_key",
":",
"str",
")",
":",
"resolved_definition",
"=",
"definition",
".",
"copy",
"(",
")",
"if",
"'$ref'",
"in",
"resolved_definition",
":",
"try",
":",
"# NOTE: The resolve method recursively resolves references, so",
"# we don't need to worry about that in this function.",
"resolved_definition",
"=",
"schema",
".",
"resolve",
"(",
"definition",
"[",
"'$ref'",
"]",
")",
"except",
"SchemaError",
"as",
"e",
":",
"raise",
"TypeSystemError",
"(",
"str",
"(",
"e",
")",
")",
"try",
":",
"value",
"=",
"resolved_definition",
"[",
"key",
"]",
"except",
"KeyError",
":",
"# Before raising an error, the resolved definition may have an array",
"# or object inside it that needs to be resolved in order to get",
"# values. Attempt that here and then fail if we still can't find",
"# the key we are looking for.",
"# If the key was missing and this is an array, try to resolve it",
"# from the items key.",
"if",
"resolved_definition",
"[",
"'type'",
"]",
"==",
"'array'",
":",
"return",
"[",
"get_value_from_schema",
"(",
"schema",
",",
"resolved_definition",
"[",
"'items'",
"]",
",",
"key",
",",
"definition_key",
")",
"]",
"# If the key was missing and this is an object, resolve it from it's",
"# properties.",
"elif",
"resolved_definition",
"[",
"'type'",
"]",
"==",
"'object'",
":",
"value",
"=",
"{",
"}",
"for",
"prop",
",",
"definition",
"in",
"resolved_definition",
"[",
"'properties'",
"]",
".",
"items",
"(",
")",
":",
"value",
"[",
"prop",
"]",
"=",
"get_value_from_schema",
"(",
"schema",
",",
"definition",
",",
"key",
",",
"definition_key",
")",
"return",
"value",
"raise",
"TypeSystemError",
"(",
"'Definition `{}` is missing a {}.'",
".",
"format",
"(",
"definition_key",
",",
"key",
")",
")",
"return",
"value"
] | Gets a value from a schema and definition.
If the value has references it will recursively attempt to resolve them.
:param ResourceSchema schema: The resource schema.
:param dict definition: The definition dict from the schema.
:param str key: The key to use to get the value from the schema.
:param str definition_key: The name of the definition.
:returns: The value.
:raises TypeSystemError: If the key can't be found in the schema/definition
or we can't resolve the definition. | [
"Gets",
"a",
"value",
"from",
"a",
"schema",
"and",
"definition",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L726-L774 |
upsight/doctor | doctor/types.py | get_types | def get_types(json_type: StrOrList) -> typing.Tuple[str, str]:
"""Returns the json and native python type based on the json_type input.
If json_type is a list of types it will return the first non 'null' value.
:param json_type: A json type or a list of json types.
:returns: A tuple containing the json type and native python type.
"""
# If the type is a list, use the first non 'null' value as the type.
if isinstance(json_type, list):
for j_type in json_type:
if j_type != 'null':
json_type = j_type
break
return (json_type, JSON_TYPES_TO_NATIVE[json_type]) | python | def get_types(json_type: StrOrList) -> typing.Tuple[str, str]:
"""Returns the json and native python type based on the json_type input.
If json_type is a list of types it will return the first non 'null' value.
:param json_type: A json type or a list of json types.
:returns: A tuple containing the json type and native python type.
"""
# If the type is a list, use the first non 'null' value as the type.
if isinstance(json_type, list):
for j_type in json_type:
if j_type != 'null':
json_type = j_type
break
return (json_type, JSON_TYPES_TO_NATIVE[json_type]) | [
"def",
"get_types",
"(",
"json_type",
":",
"StrOrList",
")",
"->",
"typing",
".",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"# If the type is a list, use the first non 'null' value as the type.",
"if",
"isinstance",
"(",
"json_type",
",",
"list",
")",
":",
"for",
"j_type",
"in",
"json_type",
":",
"if",
"j_type",
"!=",
"'null'",
":",
"json_type",
"=",
"j_type",
"break",
"return",
"(",
"json_type",
",",
"JSON_TYPES_TO_NATIVE",
"[",
"json_type",
"]",
")"
] | Returns the json and native python type based on the json_type input.
If json_type is a list of types it will return the first non 'null' value.
:param json_type: A json type or a list of json types.
:returns: A tuple containing the json type and native python type. | [
"Returns",
"the",
"json",
"and",
"native",
"python",
"type",
"based",
"on",
"the",
"json_type",
"input",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L777-L791 |
upsight/doctor | doctor/types.py | json_schema_type | def json_schema_type(schema_file: str, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.JsonSchema` type.
This function will automatically load the schema and set it as an attribute
of the class along with the description and example.
:param schema_file: The full path to the json schema file to load.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.JsonSchema`
"""
# Importing here to avoid circular dependencies
from doctor.resource import ResourceSchema
schema = ResourceSchema.from_file(schema_file)
kwargs['schema'] = schema
# Look up the description, example and type in the schema.
definition_key = kwargs.get('definition_key')
if definition_key:
params = [definition_key]
request_schema = schema._create_request_schema(params, params)
try:
definition = request_schema['definitions'][definition_key]
except KeyError:
raise TypeSystemError(
'Definition `{}` is not defined in the schema.'.format(
definition_key))
description = get_value_from_schema(
schema, definition, 'description', definition_key)
example = get_value_from_schema(
schema, definition, 'example', definition_key)
json_type = get_value_from_schema(
schema, definition, 'type', definition_key)
json_type, native_type = get_types(json_type)
kwargs['description'] = description
kwargs['example'] = example
kwargs['json_type'] = json_type
kwargs['native_type'] = native_type
else:
try:
kwargs['description'] = schema.schema['description']
except KeyError:
raise TypeSystemError('Schema is missing a description.')
try:
json_type = schema.schema['type']
except KeyError:
raise TypeSystemError('Schema is missing a type.')
json_type, native_type = get_types(json_type)
kwargs['json_type'] = json_type
kwargs['native_type'] = native_type
try:
kwargs['example'] = schema.schema['example']
except KeyError:
# Attempt to load from properties, if defined.
if schema.schema.get('properties'):
example = {}
for prop, definition in schema.schema['properties'].items():
example[prop] = get_value_from_schema(
schema, definition, 'example', 'root')
kwargs['example'] = example
else:
raise TypeSystemError('Schema is missing an example.')
return type('JsonSchema', (JsonSchema,), kwargs) | python | def json_schema_type(schema_file: str, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.JsonSchema` type.
This function will automatically load the schema and set it as an attribute
of the class along with the description and example.
:param schema_file: The full path to the json schema file to load.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.JsonSchema`
"""
# Importing here to avoid circular dependencies
from doctor.resource import ResourceSchema
schema = ResourceSchema.from_file(schema_file)
kwargs['schema'] = schema
# Look up the description, example and type in the schema.
definition_key = kwargs.get('definition_key')
if definition_key:
params = [definition_key]
request_schema = schema._create_request_schema(params, params)
try:
definition = request_schema['definitions'][definition_key]
except KeyError:
raise TypeSystemError(
'Definition `{}` is not defined in the schema.'.format(
definition_key))
description = get_value_from_schema(
schema, definition, 'description', definition_key)
example = get_value_from_schema(
schema, definition, 'example', definition_key)
json_type = get_value_from_schema(
schema, definition, 'type', definition_key)
json_type, native_type = get_types(json_type)
kwargs['description'] = description
kwargs['example'] = example
kwargs['json_type'] = json_type
kwargs['native_type'] = native_type
else:
try:
kwargs['description'] = schema.schema['description']
except KeyError:
raise TypeSystemError('Schema is missing a description.')
try:
json_type = schema.schema['type']
except KeyError:
raise TypeSystemError('Schema is missing a type.')
json_type, native_type = get_types(json_type)
kwargs['json_type'] = json_type
kwargs['native_type'] = native_type
try:
kwargs['example'] = schema.schema['example']
except KeyError:
# Attempt to load from properties, if defined.
if schema.schema.get('properties'):
example = {}
for prop, definition in schema.schema['properties'].items():
example[prop] = get_value_from_schema(
schema, definition, 'example', 'root')
kwargs['example'] = example
else:
raise TypeSystemError('Schema is missing an example.')
return type('JsonSchema', (JsonSchema,), kwargs) | [
"def",
"json_schema_type",
"(",
"schema_file",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Type",
":",
"# Importing here to avoid circular dependencies",
"from",
"doctor",
".",
"resource",
"import",
"ResourceSchema",
"schema",
"=",
"ResourceSchema",
".",
"from_file",
"(",
"schema_file",
")",
"kwargs",
"[",
"'schema'",
"]",
"=",
"schema",
"# Look up the description, example and type in the schema.",
"definition_key",
"=",
"kwargs",
".",
"get",
"(",
"'definition_key'",
")",
"if",
"definition_key",
":",
"params",
"=",
"[",
"definition_key",
"]",
"request_schema",
"=",
"schema",
".",
"_create_request_schema",
"(",
"params",
",",
"params",
")",
"try",
":",
"definition",
"=",
"request_schema",
"[",
"'definitions'",
"]",
"[",
"definition_key",
"]",
"except",
"KeyError",
":",
"raise",
"TypeSystemError",
"(",
"'Definition `{}` is not defined in the schema.'",
".",
"format",
"(",
"definition_key",
")",
")",
"description",
"=",
"get_value_from_schema",
"(",
"schema",
",",
"definition",
",",
"'description'",
",",
"definition_key",
")",
"example",
"=",
"get_value_from_schema",
"(",
"schema",
",",
"definition",
",",
"'example'",
",",
"definition_key",
")",
"json_type",
"=",
"get_value_from_schema",
"(",
"schema",
",",
"definition",
",",
"'type'",
",",
"definition_key",
")",
"json_type",
",",
"native_type",
"=",
"get_types",
"(",
"json_type",
")",
"kwargs",
"[",
"'description'",
"]",
"=",
"description",
"kwargs",
"[",
"'example'",
"]",
"=",
"example",
"kwargs",
"[",
"'json_type'",
"]",
"=",
"json_type",
"kwargs",
"[",
"'native_type'",
"]",
"=",
"native_type",
"else",
":",
"try",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"schema",
".",
"schema",
"[",
"'description'",
"]",
"except",
"KeyError",
":",
"raise",
"TypeSystemError",
"(",
"'Schema is missing a description.'",
")",
"try",
":",
"json_type",
"=",
"schema",
".",
"schema",
"[",
"'type'",
"]",
"except",
"KeyError",
":",
"raise",
"TypeSystemError",
"(",
"'Schema is missing a type.'",
")",
"json_type",
",",
"native_type",
"=",
"get_types",
"(",
"json_type",
")",
"kwargs",
"[",
"'json_type'",
"]",
"=",
"json_type",
"kwargs",
"[",
"'native_type'",
"]",
"=",
"native_type",
"try",
":",
"kwargs",
"[",
"'example'",
"]",
"=",
"schema",
".",
"schema",
"[",
"'example'",
"]",
"except",
"KeyError",
":",
"# Attempt to load from properties, if defined.",
"if",
"schema",
".",
"schema",
".",
"get",
"(",
"'properties'",
")",
":",
"example",
"=",
"{",
"}",
"for",
"prop",
",",
"definition",
"in",
"schema",
".",
"schema",
"[",
"'properties'",
"]",
".",
"items",
"(",
")",
":",
"example",
"[",
"prop",
"]",
"=",
"get_value_from_schema",
"(",
"schema",
",",
"definition",
",",
"'example'",
",",
"'root'",
")",
"kwargs",
"[",
"'example'",
"]",
"=",
"example",
"else",
":",
"raise",
"TypeSystemError",
"(",
"'Schema is missing an example.'",
")",
"return",
"type",
"(",
"'JsonSchema'",
",",
"(",
"JsonSchema",
",",
")",
",",
"kwargs",
")"
] | Create a :class:`~doctor.types.JsonSchema` type.
This function will automatically load the schema and set it as an attribute
of the class along with the description and example.
:param schema_file: The full path to the json schema file to load.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.JsonSchema` | [
"Create",
"a",
":",
"class",
":",
"~doctor",
".",
"types",
".",
"JsonSchema",
"type",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L794-L856 |
upsight/doctor | doctor/types.py | string | def string(description: str, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.String` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.String`
"""
kwargs['description'] = description
return type('String', (String,), kwargs) | python | def string(description: str, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.String` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.String`
"""
kwargs['description'] = description
return type('String', (String,), kwargs) | [
"def",
"string",
"(",
"description",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Type",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"description",
"return",
"type",
"(",
"'String'",
",",
"(",
"String",
",",
")",
",",
"kwargs",
")"
] | Create a :class:`~doctor.types.String` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.String` | [
"Create",
"a",
":",
"class",
":",
"~doctor",
".",
"types",
".",
"String",
"type",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L859-L867 |
upsight/doctor | doctor/types.py | integer | def integer(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Integer` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Integer`
"""
kwargs['description'] = description
return type('Integer', (Integer,), kwargs) | python | def integer(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Integer` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Integer`
"""
kwargs['description'] = description
return type('Integer', (Integer,), kwargs) | [
"def",
"integer",
"(",
"description",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Type",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"description",
"return",
"type",
"(",
"'Integer'",
",",
"(",
"Integer",
",",
")",
",",
"kwargs",
")"
] | Create a :class:`~doctor.types.Integer` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Integer` | [
"Create",
"a",
":",
"class",
":",
"~doctor",
".",
"types",
".",
"Integer",
"type",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L870-L878 |
upsight/doctor | doctor/types.py | number | def number(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Number` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Number`
"""
kwargs['description'] = description
return type('Number', (Number,), kwargs) | python | def number(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Number` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Number`
"""
kwargs['description'] = description
return type('Number', (Number,), kwargs) | [
"def",
"number",
"(",
"description",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Type",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"description",
"return",
"type",
"(",
"'Number'",
",",
"(",
"Number",
",",
")",
",",
"kwargs",
")"
] | Create a :class:`~doctor.types.Number` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Number` | [
"Create",
"a",
":",
"class",
":",
"~doctor",
".",
"types",
".",
"Number",
"type",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L881-L889 |
upsight/doctor | doctor/types.py | boolean | def boolean(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Boolean` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Boolean`
"""
kwargs['description'] = description
return type('Boolean', (Boolean,), kwargs) | python | def boolean(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Boolean` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Boolean`
"""
kwargs['description'] = description
return type('Boolean', (Boolean,), kwargs) | [
"def",
"boolean",
"(",
"description",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Type",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"description",
"return",
"type",
"(",
"'Boolean'",
",",
"(",
"Boolean",
",",
")",
",",
"kwargs",
")"
] | Create a :class:`~doctor.types.Boolean` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Boolean` | [
"Create",
"a",
":",
"class",
":",
"~doctor",
".",
"types",
".",
"Boolean",
"type",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L892-L900 |
upsight/doctor | doctor/types.py | enum | def enum(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Enum` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Enum`
"""
kwargs['description'] = description
return type('Enum', (Enum,), kwargs) | python | def enum(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Enum` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Enum`
"""
kwargs['description'] = description
return type('Enum', (Enum,), kwargs) | [
"def",
"enum",
"(",
"description",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Type",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"description",
"return",
"type",
"(",
"'Enum'",
",",
"(",
"Enum",
",",
")",
",",
"kwargs",
")"
] | Create a :class:`~doctor.types.Enum` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Enum` | [
"Create",
"a",
":",
"class",
":",
"~doctor",
".",
"types",
".",
"Enum",
"type",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L903-L911 |
upsight/doctor | doctor/types.py | array | def array(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Array` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Array`
"""
kwargs['description'] = description
return type('Array', (Array,), kwargs) | python | def array(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Array` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Array`
"""
kwargs['description'] = description
return type('Array', (Array,), kwargs) | [
"def",
"array",
"(",
"description",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Type",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"description",
"return",
"type",
"(",
"'Array'",
",",
"(",
"Array",
",",
")",
",",
"kwargs",
")"
] | Create a :class:`~doctor.types.Array` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Array` | [
"Create",
"a",
":",
"class",
":",
"~doctor",
".",
"types",
".",
"Array",
"type",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L914-L922 |
upsight/doctor | doctor/types.py | new_type | def new_type(cls, **kwargs) -> typing.Type:
"""Create a user defined type.
The new type will contain all attributes of the `cls` type passed in.
Any attribute's value can be overwritten using kwargs.
:param kwargs: Can include any attribute defined in
the provided user defined type.
"""
props = dict(cls.__dict__)
props.update(kwargs)
return type(cls.__name__, (cls,), props) | python | def new_type(cls, **kwargs) -> typing.Type:
"""Create a user defined type.
The new type will contain all attributes of the `cls` type passed in.
Any attribute's value can be overwritten using kwargs.
:param kwargs: Can include any attribute defined in
the provided user defined type.
"""
props = dict(cls.__dict__)
props.update(kwargs)
return type(cls.__name__, (cls,), props) | [
"def",
"new_type",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Type",
":",
"props",
"=",
"dict",
"(",
"cls",
".",
"__dict__",
")",
"props",
".",
"update",
"(",
"kwargs",
")",
"return",
"type",
"(",
"cls",
".",
"__name__",
",",
"(",
"cls",
",",
")",
",",
"props",
")"
] | Create a user defined type.
The new type will contain all attributes of the `cls` type passed in.
Any attribute's value can be overwritten using kwargs.
:param kwargs: Can include any attribute defined in
the provided user defined type. | [
"Create",
"a",
"user",
"defined",
"type",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L925-L936 |
upsight/doctor | doctor/types.py | Object.get_example | def get_example(cls) -> dict:
"""Returns an example value for the Dict type.
If an example isn't a defined attribute on the class we return
a dict of example values based on each property's annotation.
"""
if cls.example is not None:
return cls.example
return {k: v.get_example() for k, v in cls.properties.items()} | python | def get_example(cls) -> dict:
"""Returns an example value for the Dict type.
If an example isn't a defined attribute on the class we return
a dict of example values based on each property's annotation.
"""
if cls.example is not None:
return cls.example
return {k: v.get_example() for k, v in cls.properties.items()} | [
"def",
"get_example",
"(",
"cls",
")",
"->",
"dict",
":",
"if",
"cls",
".",
"example",
"is",
"not",
"None",
":",
"return",
"cls",
".",
"example",
"return",
"{",
"k",
":",
"v",
".",
"get_example",
"(",
")",
"for",
"k",
",",
"v",
"in",
"cls",
".",
"properties",
".",
"items",
"(",
")",
"}"
] | Returns an example value for the Dict type.
If an example isn't a defined attribute on the class we return
a dict of example values based on each property's annotation. | [
"Returns",
"an",
"example",
"value",
"for",
"the",
"Dict",
"type",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L563-L571 |
upsight/doctor | doctor/types.py | Array.get_example | def get_example(cls) -> list:
"""Returns an example value for the Array type.
If an example isn't a defined attribute on the class we return
a list of 1 item containing the example value of the `items` attribute.
If `items` is None we simply return a `[1]`.
"""
if cls.example is not None:
return cls.example
if cls.items is not None:
if isinstance(cls.items, list):
return [item.get_example() for item in cls.items]
else:
return [cls.items.get_example()]
return [1] | python | def get_example(cls) -> list:
"""Returns an example value for the Array type.
If an example isn't a defined attribute on the class we return
a list of 1 item containing the example value of the `items` attribute.
If `items` is None we simply return a `[1]`.
"""
if cls.example is not None:
return cls.example
if cls.items is not None:
if isinstance(cls.items, list):
return [item.get_example() for item in cls.items]
else:
return [cls.items.get_example()]
return [1] | [
"def",
"get_example",
"(",
"cls",
")",
"->",
"list",
":",
"if",
"cls",
".",
"example",
"is",
"not",
"None",
":",
"return",
"cls",
".",
"example",
"if",
"cls",
".",
"items",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"cls",
".",
"items",
",",
"list",
")",
":",
"return",
"[",
"item",
".",
"get_example",
"(",
")",
"for",
"item",
"in",
"cls",
".",
"items",
"]",
"else",
":",
"return",
"[",
"cls",
".",
"items",
".",
"get_example",
"(",
")",
"]",
"return",
"[",
"1",
"]"
] | Returns an example value for the Array type.
If an example isn't a defined attribute on the class we return
a list of 1 item containing the example value of the `items` attribute.
If `items` is None we simply return a `[1]`. | [
"Returns",
"an",
"example",
"value",
"for",
"the",
"Array",
"type",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L650-L664 |
eumis/pyviews | pyviews/rendering/pipeline.py | render_node | def render_node(xml_node: XmlNode, **args) -> Node:
"""Renders node from xml node"""
try:
node = create_node(xml_node, **args)
pipeline = get_pipeline(node)
run_steps(node, pipeline, **args)
return node
except CoreError as error:
error.add_view_info(xml_node.view_info)
raise
except:
info = exc_info()
msg = 'Unknown error occurred during rendering'
error = RenderingError(msg, xml_node.view_info)
error.add_cause(info[1])
raise error from info[1] | python | def render_node(xml_node: XmlNode, **args) -> Node:
"""Renders node from xml node"""
try:
node = create_node(xml_node, **args)
pipeline = get_pipeline(node)
run_steps(node, pipeline, **args)
return node
except CoreError as error:
error.add_view_info(xml_node.view_info)
raise
except:
info = exc_info()
msg = 'Unknown error occurred during rendering'
error = RenderingError(msg, xml_node.view_info)
error.add_cause(info[1])
raise error from info[1] | [
"def",
"render_node",
"(",
"xml_node",
":",
"XmlNode",
",",
"*",
"*",
"args",
")",
"->",
"Node",
":",
"try",
":",
"node",
"=",
"create_node",
"(",
"xml_node",
",",
"*",
"*",
"args",
")",
"pipeline",
"=",
"get_pipeline",
"(",
"node",
")",
"run_steps",
"(",
"node",
",",
"pipeline",
",",
"*",
"*",
"args",
")",
"return",
"node",
"except",
"CoreError",
"as",
"error",
":",
"error",
".",
"add_view_info",
"(",
"xml_node",
".",
"view_info",
")",
"raise",
"except",
":",
"info",
"=",
"exc_info",
"(",
")",
"msg",
"=",
"'Unknown error occurred during rendering'",
"error",
"=",
"RenderingError",
"(",
"msg",
",",
"xml_node",
".",
"view_info",
")",
"error",
".",
"add_cause",
"(",
"info",
"[",
"1",
"]",
")",
"raise",
"error",
"from",
"info",
"[",
"1",
"]"
] | Renders node from xml node | [
"Renders",
"node",
"from",
"xml",
"node"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/pipeline.py#L19-L34 |
eumis/pyviews | pyviews/rendering/pipeline.py | get_pipeline | def get_pipeline(node: Node) -> RenderingPipeline:
"""Gets rendering pipeline for passed node"""
pipeline = _get_registered_pipeline(node)
if pipeline is None:
msg = _get_pipeline_registration_error_message(node)
raise RenderingError(msg)
return pipeline | python | def get_pipeline(node: Node) -> RenderingPipeline:
"""Gets rendering pipeline for passed node"""
pipeline = _get_registered_pipeline(node)
if pipeline is None:
msg = _get_pipeline_registration_error_message(node)
raise RenderingError(msg)
return pipeline | [
"def",
"get_pipeline",
"(",
"node",
":",
"Node",
")",
"->",
"RenderingPipeline",
":",
"pipeline",
"=",
"_get_registered_pipeline",
"(",
"node",
")",
"if",
"pipeline",
"is",
"None",
":",
"msg",
"=",
"_get_pipeline_registration_error_message",
"(",
"node",
")",
"raise",
"RenderingError",
"(",
"msg",
")",
"return",
"pipeline"
] | Gets rendering pipeline for passed node | [
"Gets",
"rendering",
"pipeline",
"for",
"passed",
"node"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/pipeline.py#L37-L43 |
eumis/pyviews | pyviews/rendering/pipeline.py | run_steps | def run_steps(node: Node, pipeline: RenderingPipeline, **args):
"""Runs instance node rendering steps"""
for step in pipeline.steps:
result = step(node, pipeline=pipeline, **args)
if isinstance(result, dict):
args = {**args, **result} | python | def run_steps(node: Node, pipeline: RenderingPipeline, **args):
"""Runs instance node rendering steps"""
for step in pipeline.steps:
result = step(node, pipeline=pipeline, **args)
if isinstance(result, dict):
args = {**args, **result} | [
"def",
"run_steps",
"(",
"node",
":",
"Node",
",",
"pipeline",
":",
"RenderingPipeline",
",",
"*",
"*",
"args",
")",
":",
"for",
"step",
"in",
"pipeline",
".",
"steps",
":",
"result",
"=",
"step",
"(",
"node",
",",
"pipeline",
"=",
"pipeline",
",",
"*",
"*",
"args",
")",
"if",
"isinstance",
"(",
"result",
",",
"dict",
")",
":",
"args",
"=",
"{",
"*",
"*",
"args",
",",
"*",
"*",
"result",
"}"
] | Runs instance node rendering steps | [
"Runs",
"instance",
"node",
"rendering",
"steps"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/pipeline.py#L66-L71 |
eumis/pyviews | pyviews/rendering/pipeline.py | apply_attributes | def apply_attributes(node: Node, **_):
"""Applies xml attributes to instance node and setups bindings"""
for attr in node.xml_node.attrs:
apply_attribute(node, attr) | python | def apply_attributes(node: Node, **_):
"""Applies xml attributes to instance node and setups bindings"""
for attr in node.xml_node.attrs:
apply_attribute(node, attr) | [
"def",
"apply_attributes",
"(",
"node",
":",
"Node",
",",
"*",
"*",
"_",
")",
":",
"for",
"attr",
"in",
"node",
".",
"xml_node",
".",
"attrs",
":",
"apply_attribute",
"(",
"node",
",",
"attr",
")"
] | Applies xml attributes to instance node and setups bindings | [
"Applies",
"xml",
"attributes",
"to",
"instance",
"node",
"and",
"setups",
"bindings"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/pipeline.py#L74-L77 |
eumis/pyviews | pyviews/rendering/pipeline.py | apply_attribute | def apply_attribute(node: Node, attr: XmlAttr):
"""Maps xml attribute to instance node property and setups bindings"""
setter = get_setter(attr)
stripped_value = attr.value.strip() if attr.value else ''
if is_expression(stripped_value):
(binding_type, expr_body) = parse_expression(stripped_value)
binder().apply(binding_type, node=node, attr=attr, modifier=setter, expr_body=expr_body)
else:
setter(node, attr.name, attr.value) | python | def apply_attribute(node: Node, attr: XmlAttr):
"""Maps xml attribute to instance node property and setups bindings"""
setter = get_setter(attr)
stripped_value = attr.value.strip() if attr.value else ''
if is_expression(stripped_value):
(binding_type, expr_body) = parse_expression(stripped_value)
binder().apply(binding_type, node=node, attr=attr, modifier=setter, expr_body=expr_body)
else:
setter(node, attr.name, attr.value) | [
"def",
"apply_attribute",
"(",
"node",
":",
"Node",
",",
"attr",
":",
"XmlAttr",
")",
":",
"setter",
"=",
"get_setter",
"(",
"attr",
")",
"stripped_value",
"=",
"attr",
".",
"value",
".",
"strip",
"(",
")",
"if",
"attr",
".",
"value",
"else",
"''",
"if",
"is_expression",
"(",
"stripped_value",
")",
":",
"(",
"binding_type",
",",
"expr_body",
")",
"=",
"parse_expression",
"(",
"stripped_value",
")",
"binder",
"(",
")",
".",
"apply",
"(",
"binding_type",
",",
"node",
"=",
"node",
",",
"attr",
"=",
"attr",
",",
"modifier",
"=",
"setter",
",",
"expr_body",
"=",
"expr_body",
")",
"else",
":",
"setter",
"(",
"node",
",",
"attr",
".",
"name",
",",
"attr",
".",
"value",
")"
] | Maps xml attribute to instance node property and setups bindings | [
"Maps",
"xml",
"attribute",
"to",
"instance",
"node",
"property",
"and",
"setups",
"bindings"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/pipeline.py#L80-L88 |
eumis/pyviews | pyviews/rendering/pipeline.py | call_set_attr | def call_set_attr(node: Node, key: str, value):
"""Calls node setter"""
node.set_attr(key, value) | python | def call_set_attr(node: Node, key: str, value):
"""Calls node setter"""
node.set_attr(key, value) | [
"def",
"call_set_attr",
"(",
"node",
":",
"Node",
",",
"key",
":",
"str",
",",
"value",
")",
":",
"node",
".",
"set_attr",
"(",
"key",
",",
"value",
")"
] | Calls node setter | [
"Calls",
"node",
"setter"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/pipeline.py#L98-L100 |
eumis/pyviews | pyviews/rendering/pipeline.py | render_children | def render_children(node: Node, **child_args):
"""Render node children"""
for xml_node in node.xml_node.children:
child = render(xml_node, **child_args)
node.add_child(child) | python | def render_children(node: Node, **child_args):
"""Render node children"""
for xml_node in node.xml_node.children:
child = render(xml_node, **child_args)
node.add_child(child) | [
"def",
"render_children",
"(",
"node",
":",
"Node",
",",
"*",
"*",
"child_args",
")",
":",
"for",
"xml_node",
"in",
"node",
".",
"xml_node",
".",
"children",
":",
"child",
"=",
"render",
"(",
"xml_node",
",",
"*",
"*",
"child_args",
")",
"node",
".",
"add_child",
"(",
"child",
")"
] | Render node children | [
"Render",
"node",
"children"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/pipeline.py#L103-L107 |
horejsek/python-sqlpuzzle | sqlpuzzle/_queryparts/values.py | MultipleValues.all_columns | def all_columns(self):
"""Return list of all columns."""
columns = set()
for values in self._parts:
for value in values._parts:
columns.add(value.column_name)
return sorted(columns) | python | def all_columns(self):
"""Return list of all columns."""
columns = set()
for values in self._parts:
for value in values._parts:
columns.add(value.column_name)
return sorted(columns) | [
"def",
"all_columns",
"(",
"self",
")",
":",
"columns",
"=",
"set",
"(",
")",
"for",
"values",
"in",
"self",
".",
"_parts",
":",
"for",
"value",
"in",
"values",
".",
"_parts",
":",
"columns",
".",
"add",
"(",
"value",
".",
"column_name",
")",
"return",
"sorted",
"(",
"columns",
")"
] | Return list of all columns. | [
"Return",
"list",
"of",
"all",
"columns",
"."
] | train | https://github.com/horejsek/python-sqlpuzzle/blob/d3a42ed1b339b8eafddb8d2c28a3a5832b3998dd/sqlpuzzle/_queryparts/values.py#L79-L85 |
upsight/doctor | doctor/resource.py | ResourceSchemaAnnotation.get_annotation | def get_annotation(cls, fn):
"""Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the attribute on this function.
:returns: an instance of
:class:`~doctor.resource.ResourceSchemaAnnotation` or
None.
"""
while fn is not None:
if hasattr(fn, '_schema_annotation'):
return fn._schema_annotation
fn = getattr(fn, 'im_func', fn)
closure = getattr(fn, '__closure__', None)
fn = closure[0].cell_contents if closure is not None else None
return None | python | def get_annotation(cls, fn):
"""Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the attribute on this function.
:returns: an instance of
:class:`~doctor.resource.ResourceSchemaAnnotation` or
None.
"""
while fn is not None:
if hasattr(fn, '_schema_annotation'):
return fn._schema_annotation
fn = getattr(fn, 'im_func', fn)
closure = getattr(fn, '__closure__', None)
fn = closure[0].cell_contents if closure is not None else None
return None | [
"def",
"get_annotation",
"(",
"cls",
",",
"fn",
")",
":",
"while",
"fn",
"is",
"not",
"None",
":",
"if",
"hasattr",
"(",
"fn",
",",
"'_schema_annotation'",
")",
":",
"return",
"fn",
".",
"_schema_annotation",
"fn",
"=",
"getattr",
"(",
"fn",
",",
"'im_func'",
",",
"fn",
")",
"closure",
"=",
"getattr",
"(",
"fn",
",",
"'__closure__'",
",",
"None",
")",
"fn",
"=",
"closure",
"[",
"0",
"]",
".",
"cell_contents",
"if",
"closure",
"is",
"not",
"None",
"else",
"None",
"return",
"None"
] | Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the attribute on this function.
:returns: an instance of
:class:`~doctor.resource.ResourceSchemaAnnotation` or
None. | [
"Find",
"the",
"_schema_annotation",
"attribute",
"for",
"the",
"given",
"function",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/resource.py#L48-L65 |
upsight/doctor | doctor/resource.py | ResourceSchema._create_request_schema | def _create_request_schema(self, params, required):
"""Create a JSON schema for a request.
:param list params: A list of keys specifying which definitions from
the base schema should be allowed in the request.
:param list required: A subset of the params that the requester must
specify in the request.
:returns: a JSON schema dict
"""
# We allow additional properties because the data this will validate
# may also include kwargs passed by decorators on the handler method.
schema = {'additionalProperties': True,
'definitions': self.resolve('#/definitions'),
'properties': {},
'required': required or (),
'type': 'object'}
for param in params:
schema['properties'][param] = {
'$ref': '#/definitions/{}'.format(param)}
return schema | python | def _create_request_schema(self, params, required):
"""Create a JSON schema for a request.
:param list params: A list of keys specifying which definitions from
the base schema should be allowed in the request.
:param list required: A subset of the params that the requester must
specify in the request.
:returns: a JSON schema dict
"""
# We allow additional properties because the data this will validate
# may also include kwargs passed by decorators on the handler method.
schema = {'additionalProperties': True,
'definitions': self.resolve('#/definitions'),
'properties': {},
'required': required or (),
'type': 'object'}
for param in params:
schema['properties'][param] = {
'$ref': '#/definitions/{}'.format(param)}
return schema | [
"def",
"_create_request_schema",
"(",
"self",
",",
"params",
",",
"required",
")",
":",
"# We allow additional properties because the data this will validate",
"# may also include kwargs passed by decorators on the handler method.",
"schema",
"=",
"{",
"'additionalProperties'",
":",
"True",
",",
"'definitions'",
":",
"self",
".",
"resolve",
"(",
"'#/definitions'",
")",
",",
"'properties'",
":",
"{",
"}",
",",
"'required'",
":",
"required",
"or",
"(",
")",
",",
"'type'",
":",
"'object'",
"}",
"for",
"param",
"in",
"params",
":",
"schema",
"[",
"'properties'",
"]",
"[",
"param",
"]",
"=",
"{",
"'$ref'",
":",
"'#/definitions/{}'",
".",
"format",
"(",
"param",
")",
"}",
"return",
"schema"
] | Create a JSON schema for a request.
:param list params: A list of keys specifying which definitions from
the base schema should be allowed in the request.
:param list required: A subset of the params that the requester must
specify in the request.
:returns: a JSON schema dict | [
"Create",
"a",
"JSON",
"schema",
"for",
"a",
"request",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/resource.py#L116-L135 |
upsight/doctor | examples/flask/app.py | update_note | def update_note(note_id: NoteId, body: Body=None, done: Done=None) -> Note:
"""Update an existing note."""
if note_id != 1:
raise NotFoundError('Note does not exist')
new_note = note.copy()
if body is not None:
new_note['body'] = body
if done is not None:
new_note['done'] = done
return new_note | python | def update_note(note_id: NoteId, body: Body=None, done: Done=None) -> Note:
"""Update an existing note."""
if note_id != 1:
raise NotFoundError('Note does not exist')
new_note = note.copy()
if body is not None:
new_note['body'] = body
if done is not None:
new_note['done'] = done
return new_note | [
"def",
"update_note",
"(",
"note_id",
":",
"NoteId",
",",
"body",
":",
"Body",
"=",
"None",
",",
"done",
":",
"Done",
"=",
"None",
")",
"->",
"Note",
":",
"if",
"note_id",
"!=",
"1",
":",
"raise",
"NotFoundError",
"(",
"'Note does not exist'",
")",
"new_note",
"=",
"note",
".",
"copy",
"(",
")",
"if",
"body",
"is",
"not",
"None",
":",
"new_note",
"[",
"'body'",
"]",
"=",
"body",
"if",
"done",
"is",
"not",
"None",
":",
"new_note",
"[",
"'done'",
"]",
"=",
"done",
"return",
"new_note"
] | Update an existing note. | [
"Update",
"an",
"existing",
"note",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/examples/flask/app.py#L71-L80 |
Workiva/furious | furious/batcher.py | Message.to_task | def to_task(self):
"""Return a task object representing this message."""
from google.appengine.api.taskqueue import Task
task_args = self.get_task_args().copy()
payload = None
if 'payload' in task_args:
payload = task_args.pop('payload')
kwargs = {
'method': METHOD_TYPE,
'payload': json.dumps(payload)
}
kwargs.update(task_args)
return Task(**kwargs) | python | def to_task(self):
"""Return a task object representing this message."""
from google.appengine.api.taskqueue import Task
task_args = self.get_task_args().copy()
payload = None
if 'payload' in task_args:
payload = task_args.pop('payload')
kwargs = {
'method': METHOD_TYPE,
'payload': json.dumps(payload)
}
kwargs.update(task_args)
return Task(**kwargs) | [
"def",
"to_task",
"(",
"self",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"taskqueue",
"import",
"Task",
"task_args",
"=",
"self",
".",
"get_task_args",
"(",
")",
".",
"copy",
"(",
")",
"payload",
"=",
"None",
"if",
"'payload'",
"in",
"task_args",
":",
"payload",
"=",
"task_args",
".",
"pop",
"(",
"'payload'",
")",
"kwargs",
"=",
"{",
"'method'",
":",
"METHOD_TYPE",
",",
"'payload'",
":",
"json",
".",
"dumps",
"(",
"payload",
")",
"}",
"kwargs",
".",
"update",
"(",
"task_args",
")",
"return",
"Task",
"(",
"*",
"*",
"kwargs",
")"
] | Return a task object representing this message. | [
"Return",
"a",
"task",
"object",
"representing",
"this",
"message",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L58-L75 |
Workiva/furious | furious/batcher.py | Message.insert | def insert(self):
"""Insert the pull task into the requested queue, 'default' if non
given.
"""
from google.appengine.api.taskqueue import Queue
task = self.to_task()
Queue(name=self.get_queue()).add(task) | python | def insert(self):
"""Insert the pull task into the requested queue, 'default' if non
given.
"""
from google.appengine.api.taskqueue import Queue
task = self.to_task()
Queue(name=self.get_queue()).add(task) | [
"def",
"insert",
"(",
"self",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"taskqueue",
"import",
"Queue",
"task",
"=",
"self",
".",
"to_task",
"(",
")",
"Queue",
"(",
"name",
"=",
"self",
".",
"get_queue",
"(",
")",
")",
".",
"add",
"(",
"task",
")"
] | Insert the pull task into the requested queue, 'default' if non
given. | [
"Insert",
"the",
"pull",
"task",
"into",
"the",
"requested",
"queue",
"default",
"if",
"non",
"given",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L77-L85 |
Workiva/furious | furious/batcher.py | Message.to_dict | def to_dict(self):
"""Return this message as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime(eta.timetuple())
return options | python | def to_dict(self):
"""Return this message as a dict suitable for json encoding."""
import copy
options = copy.deepcopy(self._options)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime(eta.timetuple())
return options | [
"def",
"to_dict",
"(",
"self",
")",
":",
"import",
"copy",
"options",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_options",
")",
"# JSON don't like datetimes.",
"eta",
"=",
"options",
".",
"get",
"(",
"'task_args'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'eta'",
")",
"if",
"eta",
":",
"options",
"[",
"'task_args'",
"]",
"[",
"'eta'",
"]",
"=",
"time",
".",
"mktime",
"(",
"eta",
".",
"timetuple",
"(",
")",
")",
"return",
"options"
] | Return this message as a dict suitable for json encoding. | [
"Return",
"this",
"message",
"as",
"a",
"dict",
"suitable",
"for",
"json",
"encoding",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L87-L98 |
Workiva/furious | furious/batcher.py | Message._get_id | def _get_id(self):
"""If this message has no id, generate one."""
id = self._options.get('id')
if id:
return id
id = uuid.uuid4().hex
self.update_options(id=id)
return id | python | def _get_id(self):
"""If this message has no id, generate one."""
id = self._options.get('id')
if id:
return id
id = uuid.uuid4().hex
self.update_options(id=id)
return id | [
"def",
"_get_id",
"(",
"self",
")",
":",
"id",
"=",
"self",
".",
"_options",
".",
"get",
"(",
"'id'",
")",
"if",
"id",
":",
"return",
"id",
"id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"self",
".",
"update_options",
"(",
"id",
"=",
"id",
")",
"return",
"id"
] | If this message has no id, generate one. | [
"If",
"this",
"message",
"has",
"no",
"id",
"generate",
"one",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L100-L108 |
Workiva/furious | furious/batcher.py | Message.from_dict | def from_dict(cls, message):
"""Return an message from a dict output by Async.to_dict."""
message_options = message.copy()
# JSON don't like datetimes.
eta = message_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
message_options['task_args']['eta'] = datetime.fromtimestamp(eta)
return Message(**message_options) | python | def from_dict(cls, message):
"""Return an message from a dict output by Async.to_dict."""
message_options = message.copy()
# JSON don't like datetimes.
eta = message_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
message_options['task_args']['eta'] = datetime.fromtimestamp(eta)
return Message(**message_options) | [
"def",
"from_dict",
"(",
"cls",
",",
"message",
")",
":",
"message_options",
"=",
"message",
".",
"copy",
"(",
")",
"# JSON don't like datetimes.",
"eta",
"=",
"message_options",
".",
"get",
"(",
"'task_args'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'eta'",
")",
"if",
"eta",
":",
"from",
"datetime",
"import",
"datetime",
"message_options",
"[",
"'task_args'",
"]",
"[",
"'eta'",
"]",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"eta",
")",
"return",
"Message",
"(",
"*",
"*",
"message_options",
")"
] | Return an message from a dict output by Async.to_dict. | [
"Return",
"an",
"message",
"from",
"a",
"dict",
"output",
"by",
"Async",
".",
"to_dict",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L116-L128 |
Workiva/furious | furious/batcher.py | MessageProcessor.to_task | def to_task(self):
"""Return a task object representing this MessageProcessor job."""
task_args = self.get_task_args()
# check for name in task args
name = task_args.get('name', MESSAGE_PROCESSOR_NAME)
# if the countdown isn't in the task_args set it to the frequency
if not 'countdown' in task_args:
task_args['countdown'] = self.frequency
task_args['name'] = "%s-%s-%s-%s" % (
name, self.tag, self.current_batch, self.time_throttle)
self.update_options(task_args=task_args)
return super(MessageProcessor, self).to_task() | python | def to_task(self):
"""Return a task object representing this MessageProcessor job."""
task_args = self.get_task_args()
# check for name in task args
name = task_args.get('name', MESSAGE_PROCESSOR_NAME)
# if the countdown isn't in the task_args set it to the frequency
if not 'countdown' in task_args:
task_args['countdown'] = self.frequency
task_args['name'] = "%s-%s-%s-%s" % (
name, self.tag, self.current_batch, self.time_throttle)
self.update_options(task_args=task_args)
return super(MessageProcessor, self).to_task() | [
"def",
"to_task",
"(",
"self",
")",
":",
"task_args",
"=",
"self",
".",
"get_task_args",
"(",
")",
"# check for name in task args",
"name",
"=",
"task_args",
".",
"get",
"(",
"'name'",
",",
"MESSAGE_PROCESSOR_NAME",
")",
"# if the countdown isn't in the task_args set it to the frequency",
"if",
"not",
"'countdown'",
"in",
"task_args",
":",
"task_args",
"[",
"'countdown'",
"]",
"=",
"self",
".",
"frequency",
"task_args",
"[",
"'name'",
"]",
"=",
"\"%s-%s-%s-%s\"",
"%",
"(",
"name",
",",
"self",
".",
"tag",
",",
"self",
".",
"current_batch",
",",
"self",
".",
"time_throttle",
")",
"self",
".",
"update_options",
"(",
"task_args",
"=",
"task_args",
")",
"return",
"super",
"(",
"MessageProcessor",
",",
"self",
")",
".",
"to_task",
"(",
")"
] | Return a task object representing this MessageProcessor job. | [
"Return",
"a",
"task",
"object",
"representing",
"this",
"MessageProcessor",
"job",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L141-L157 |
Workiva/furious | furious/batcher.py | MessageProcessor.current_batch | def current_batch(self):
"""Return the batch id for the tag.
:return: :class: `int` current batch id
"""
current_batch = memcache.get(self.group_key)
if not current_batch:
memcache.add(self.group_key, 1)
current_batch = 1
return current_batch | python | def current_batch(self):
"""Return the batch id for the tag.
:return: :class: `int` current batch id
"""
current_batch = memcache.get(self.group_key)
if not current_batch:
memcache.add(self.group_key, 1)
current_batch = 1
return current_batch | [
"def",
"current_batch",
"(",
"self",
")",
":",
"current_batch",
"=",
"memcache",
".",
"get",
"(",
"self",
".",
"group_key",
")",
"if",
"not",
"current_batch",
":",
"memcache",
".",
"add",
"(",
"self",
".",
"group_key",
",",
"1",
")",
"current_batch",
"=",
"1",
"return",
"current_batch"
] | Return the batch id for the tag.
:return: :class: `int` current batch id | [
"Return",
"the",
"batch",
"id",
"for",
"the",
"tag",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L165-L176 |
Workiva/furious | furious/batcher.py | MessageIterator.fetch_messages | def fetch_messages(self):
"""Fetch messages from the specified pull-queue.
This should only be called a single time by a given MessageIterator
object. If the MessageIterator is iterated over again, it should
return the originally leased messages.
"""
if self._fetched:
return
start = time.time()
loaded_messages = self.queue.lease_tasks_by_tag(
self.duration, self.size, tag=self.tag, deadline=self.deadline)
# If we are within 0.1 sec of our deadline and no messages were
# returned, then we are hitting queue contention issues and this
# should be a DeadlineExceederError.
# TODO: investigate other ways around this, perhaps async leases, etc.
if (not loaded_messages and
round(time.time() - start, 1) >= self.deadline - 0.1):
raise DeadlineExceededError()
self._messages.extend(loaded_messages)
self._fetched = True
logging.debug("Calling fetch messages with %s:%s:%s:%s:%s:%s" % (
len(self._messages), len(loaded_messages),
len(self._processed_messages), self.duration, self.size, self.tag)) | python | def fetch_messages(self):
"""Fetch messages from the specified pull-queue.
This should only be called a single time by a given MessageIterator
object. If the MessageIterator is iterated over again, it should
return the originally leased messages.
"""
if self._fetched:
return
start = time.time()
loaded_messages = self.queue.lease_tasks_by_tag(
self.duration, self.size, tag=self.tag, deadline=self.deadline)
# If we are within 0.1 sec of our deadline and no messages were
# returned, then we are hitting queue contention issues and this
# should be a DeadlineExceederError.
# TODO: investigate other ways around this, perhaps async leases, etc.
if (not loaded_messages and
round(time.time() - start, 1) >= self.deadline - 0.1):
raise DeadlineExceededError()
self._messages.extend(loaded_messages)
self._fetched = True
logging.debug("Calling fetch messages with %s:%s:%s:%s:%s:%s" % (
len(self._messages), len(loaded_messages),
len(self._processed_messages), self.duration, self.size, self.tag)) | [
"def",
"fetch_messages",
"(",
"self",
")",
":",
"if",
"self",
".",
"_fetched",
":",
"return",
"start",
"=",
"time",
".",
"time",
"(",
")",
"loaded_messages",
"=",
"self",
".",
"queue",
".",
"lease_tasks_by_tag",
"(",
"self",
".",
"duration",
",",
"self",
".",
"size",
",",
"tag",
"=",
"self",
".",
"tag",
",",
"deadline",
"=",
"self",
".",
"deadline",
")",
"# If we are within 0.1 sec of our deadline and no messages were",
"# returned, then we are hitting queue contention issues and this",
"# should be a DeadlineExceederError.",
"# TODO: investigate other ways around this, perhaps async leases, etc.",
"if",
"(",
"not",
"loaded_messages",
"and",
"round",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start",
",",
"1",
")",
">=",
"self",
".",
"deadline",
"-",
"0.1",
")",
":",
"raise",
"DeadlineExceededError",
"(",
")",
"self",
".",
"_messages",
".",
"extend",
"(",
"loaded_messages",
")",
"self",
".",
"_fetched",
"=",
"True",
"logging",
".",
"debug",
"(",
"\"Calling fetch messages with %s:%s:%s:%s:%s:%s\"",
"%",
"(",
"len",
"(",
"self",
".",
"_messages",
")",
",",
"len",
"(",
"loaded_messages",
")",
",",
"len",
"(",
"self",
".",
"_processed_messages",
")",
",",
"self",
".",
"duration",
",",
"self",
".",
"size",
",",
"self",
".",
"tag",
")",
")"
] | Fetch messages from the specified pull-queue.
This should only be called a single time by a given MessageIterator
object. If the MessageIterator is iterated over again, it should
return the originally leased messages. | [
"Fetch",
"messages",
"from",
"the",
"specified",
"pull",
"-",
"queue",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L228-L257 |
Workiva/furious | furious/batcher.py | MessageIterator.next | def next(self):
"""Get the next batch of messages from the previously fetched messages.
If there's no more messages, check if we should auto-delete the
messages and raise StopIteration.
"""
if not self._messages:
if self.auto_delete:
self.delete_messages()
raise StopIteration
message = self._messages.pop(0)
self._processed_messages.append(message)
return json.loads(message.payload) | python | def next(self):
"""Get the next batch of messages from the previously fetched messages.
If there's no more messages, check if we should auto-delete the
messages and raise StopIteration.
"""
if not self._messages:
if self.auto_delete:
self.delete_messages()
raise StopIteration
message = self._messages.pop(0)
self._processed_messages.append(message)
return json.loads(message.payload) | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_messages",
":",
"if",
"self",
".",
"auto_delete",
":",
"self",
".",
"delete_messages",
"(",
")",
"raise",
"StopIteration",
"message",
"=",
"self",
".",
"_messages",
".",
"pop",
"(",
"0",
")",
"self",
".",
"_processed_messages",
".",
"append",
"(",
"message",
")",
"return",
"json",
".",
"loads",
"(",
"message",
".",
"payload",
")"
] | Get the next batch of messages from the previously fetched messages.
If there's no more messages, check if we should auto-delete the
messages and raise StopIteration. | [
"Get",
"the",
"next",
"batch",
"of",
"messages",
"from",
"the",
"previously",
"fetched",
"messages",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L280-L293 |
Workiva/furious | furious/batcher.py | MessageIterator.delete_messages | def delete_messages(self, only_processed=True):
"""Delete the messages previously leased.
Unless otherwise directed, only the messages iterated over will be
deleted.
"""
messages = self._processed_messages
if not only_processed:
messages += self._messages
if messages:
try:
self.queue.delete_tasks(messages)
except Exception:
logging.exception("Error deleting messages")
raise | python | def delete_messages(self, only_processed=True):
"""Delete the messages previously leased.
Unless otherwise directed, only the messages iterated over will be
deleted.
"""
messages = self._processed_messages
if not only_processed:
messages += self._messages
if messages:
try:
self.queue.delete_tasks(messages)
except Exception:
logging.exception("Error deleting messages")
raise | [
"def",
"delete_messages",
"(",
"self",
",",
"only_processed",
"=",
"True",
")",
":",
"messages",
"=",
"self",
".",
"_processed_messages",
"if",
"not",
"only_processed",
":",
"messages",
"+=",
"self",
".",
"_messages",
"if",
"messages",
":",
"try",
":",
"self",
".",
"queue",
".",
"delete_tasks",
"(",
"messages",
")",
"except",
"Exception",
":",
"logging",
".",
"exception",
"(",
"\"Error deleting messages\"",
")",
"raise"
] | Delete the messages previously leased.
Unless otherwise directed, only the messages iterated over will be
deleted. | [
"Delete",
"the",
"messages",
"previously",
"leased",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/batcher.py#L295-L310 |
upsight/doctor | doctor/utils/__init__.py | copy_func | def copy_func(func: Callable) -> Callable:
"""Returns a copy of a function.
:param func: The function to copy.
:returns: The copied function.
"""
copied = types.FunctionType(
func.__code__, func.__globals__, name=func.__name__,
argdefs=func.__defaults__, closure=func.__closure__)
copied = functools.update_wrapper(copied, func)
copied.__kwdefaults__ = func.__kwdefaults__
return copied | python | def copy_func(func: Callable) -> Callable:
"""Returns a copy of a function.
:param func: The function to copy.
:returns: The copied function.
"""
copied = types.FunctionType(
func.__code__, func.__globals__, name=func.__name__,
argdefs=func.__defaults__, closure=func.__closure__)
copied = functools.update_wrapper(copied, func)
copied.__kwdefaults__ = func.__kwdefaults__
return copied | [
"def",
"copy_func",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"copied",
"=",
"types",
".",
"FunctionType",
"(",
"func",
".",
"__code__",
",",
"func",
".",
"__globals__",
",",
"name",
"=",
"func",
".",
"__name__",
",",
"argdefs",
"=",
"func",
".",
"__defaults__",
",",
"closure",
"=",
"func",
".",
"__closure__",
")",
"copied",
"=",
"functools",
".",
"update_wrapper",
"(",
"copied",
",",
"func",
")",
"copied",
".",
"__kwdefaults__",
"=",
"func",
".",
"__kwdefaults__",
"return",
"copied"
] | Returns a copy of a function.
:param func: The function to copy.
:returns: The copied function. | [
"Returns",
"a",
"copy",
"of",
"a",
"function",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L25-L36 |
upsight/doctor | doctor/utils/__init__.py | get_params_from_func | def get_params_from_func(func: Callable, signature: Signature=None) -> Params:
"""Gets all parameters from a function signature.
:param func: The function to inspect.
:param signature: An inspect.Signature instance.
:returns: A named tuple containing information about all, optional,
required and logic function parameters.
"""
if signature is None:
# Check if the function already parsed the signature
signature = getattr(func, '_doctor_signature', None)
# Otherwise parse the signature
if signature is None:
signature = inspect.signature(func)
# Check if a `req_obj_type` was provided for the function. If so we should
# derrive the parameters from that defined type instead of the signature.
if getattr(func, '_doctor_req_obj_type', None):
annotation = func._doctor_req_obj_type
all_params = list(annotation.properties.keys())
required = annotation.required
optional = list(set(all_params) - set(required))
else:
# Required is a positional argument with no defualt value and it's
# annotation must sub class SuperType. This is so we don't try to
# require parameters passed to a logic function by a decorator that are
# not part of a request.
required = [key for key, p in signature.parameters.items()
if p.default == p.empty and
issubclass(p.annotation, SuperType)]
optional = [key for key, p in signature.parameters.items()
if p.default != p.empty]
all_params = [key for key in signature.parameters.keys()]
# Logic params are all parameters that are part of the logic signature.
logic_params = copy(all_params)
return Params(all_params, required, optional, logic_params) | python | def get_params_from_func(func: Callable, signature: Signature=None) -> Params:
"""Gets all parameters from a function signature.
:param func: The function to inspect.
:param signature: An inspect.Signature instance.
:returns: A named tuple containing information about all, optional,
required and logic function parameters.
"""
if signature is None:
# Check if the function already parsed the signature
signature = getattr(func, '_doctor_signature', None)
# Otherwise parse the signature
if signature is None:
signature = inspect.signature(func)
# Check if a `req_obj_type` was provided for the function. If so we should
# derrive the parameters from that defined type instead of the signature.
if getattr(func, '_doctor_req_obj_type', None):
annotation = func._doctor_req_obj_type
all_params = list(annotation.properties.keys())
required = annotation.required
optional = list(set(all_params) - set(required))
else:
# Required is a positional argument with no defualt value and it's
# annotation must sub class SuperType. This is so we don't try to
# require parameters passed to a logic function by a decorator that are
# not part of a request.
required = [key for key, p in signature.parameters.items()
if p.default == p.empty and
issubclass(p.annotation, SuperType)]
optional = [key for key, p in signature.parameters.items()
if p.default != p.empty]
all_params = [key for key in signature.parameters.keys()]
# Logic params are all parameters that are part of the logic signature.
logic_params = copy(all_params)
return Params(all_params, required, optional, logic_params) | [
"def",
"get_params_from_func",
"(",
"func",
":",
"Callable",
",",
"signature",
":",
"Signature",
"=",
"None",
")",
"->",
"Params",
":",
"if",
"signature",
"is",
"None",
":",
"# Check if the function already parsed the signature",
"signature",
"=",
"getattr",
"(",
"func",
",",
"'_doctor_signature'",
",",
"None",
")",
"# Otherwise parse the signature",
"if",
"signature",
"is",
"None",
":",
"signature",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"# Check if a `req_obj_type` was provided for the function. If so we should",
"# derrive the parameters from that defined type instead of the signature.",
"if",
"getattr",
"(",
"func",
",",
"'_doctor_req_obj_type'",
",",
"None",
")",
":",
"annotation",
"=",
"func",
".",
"_doctor_req_obj_type",
"all_params",
"=",
"list",
"(",
"annotation",
".",
"properties",
".",
"keys",
"(",
")",
")",
"required",
"=",
"annotation",
".",
"required",
"optional",
"=",
"list",
"(",
"set",
"(",
"all_params",
")",
"-",
"set",
"(",
"required",
")",
")",
"else",
":",
"# Required is a positional argument with no defualt value and it's",
"# annotation must sub class SuperType. This is so we don't try to",
"# require parameters passed to a logic function by a decorator that are",
"# not part of a request.",
"required",
"=",
"[",
"key",
"for",
"key",
",",
"p",
"in",
"signature",
".",
"parameters",
".",
"items",
"(",
")",
"if",
"p",
".",
"default",
"==",
"p",
".",
"empty",
"and",
"issubclass",
"(",
"p",
".",
"annotation",
",",
"SuperType",
")",
"]",
"optional",
"=",
"[",
"key",
"for",
"key",
",",
"p",
"in",
"signature",
".",
"parameters",
".",
"items",
"(",
")",
"if",
"p",
".",
"default",
"!=",
"p",
".",
"empty",
"]",
"all_params",
"=",
"[",
"key",
"for",
"key",
"in",
"signature",
".",
"parameters",
".",
"keys",
"(",
")",
"]",
"# Logic params are all parameters that are part of the logic signature.",
"logic_params",
"=",
"copy",
"(",
"all_params",
")",
"return",
"Params",
"(",
"all_params",
",",
"required",
",",
"optional",
",",
"logic_params",
")"
] | Gets all parameters from a function signature.
:param func: The function to inspect.
:param signature: An inspect.Signature instance.
:returns: A named tuple containing information about all, optional,
required and logic function parameters. | [
"Gets",
"all",
"parameters",
"from",
"a",
"function",
"signature",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L88-L124 |
upsight/doctor | doctor/utils/__init__.py | add_param_annotations | def add_param_annotations(
logic: Callable, params: List[RequestParamAnnotation]) -> Callable:
"""Adds parameter annotations to a logic function.
This adds additional required and/or optional parameters to the logic
function that are not part of it's signature. It's intended to be used
by decorators decorating logic functions or middleware.
:param logic: The logic function to add the parameter annotations to.
:param params: The list of RequestParamAnnotations to add to the logic func.
:returns: The logic func with updated parameter annotations.
"""
# If we've already added param annotations to this function get the
# values from the logic, otherwise we need to inspect it.
if hasattr(logic, '_doctor_signature'):
sig = logic._doctor_signature
doctor_params = logic._doctor_params
else:
sig = inspect.signature(logic)
doctor_params = get_params_from_func(logic, sig)
prev_parameters = {name: param for name, param in sig.parameters.items()}
new_params = []
for param in params:
# If the parameter already exists in the function signature, log
# a warning and skip it.
if param.name in prev_parameters:
logging.warning('Not adding %s to signature of %s, function '
'already has that parameter in its signature.',
param.name, logic.__name__)
continue
doctor_params.all.append(param.name)
default = None
if param.required:
default = Parameter.empty
doctor_params.required.append(param.name)
else:
doctor_params.optional.append(param.name)
new_params.append(
Parameter(param.name, Parameter.KEYWORD_ONLY, default=default,
annotation=param.annotation))
new_sig = sig.replace(
parameters=list(prev_parameters.values()) + new_params)
logic._doctor_signature = new_sig
logic._doctor_params = doctor_params
return logic | python | def add_param_annotations(
logic: Callable, params: List[RequestParamAnnotation]) -> Callable:
"""Adds parameter annotations to a logic function.
This adds additional required and/or optional parameters to the logic
function that are not part of it's signature. It's intended to be used
by decorators decorating logic functions or middleware.
:param logic: The logic function to add the parameter annotations to.
:param params: The list of RequestParamAnnotations to add to the logic func.
:returns: The logic func with updated parameter annotations.
"""
# If we've already added param annotations to this function get the
# values from the logic, otherwise we need to inspect it.
if hasattr(logic, '_doctor_signature'):
sig = logic._doctor_signature
doctor_params = logic._doctor_params
else:
sig = inspect.signature(logic)
doctor_params = get_params_from_func(logic, sig)
prev_parameters = {name: param for name, param in sig.parameters.items()}
new_params = []
for param in params:
# If the parameter already exists in the function signature, log
# a warning and skip it.
if param.name in prev_parameters:
logging.warning('Not adding %s to signature of %s, function '
'already has that parameter in its signature.',
param.name, logic.__name__)
continue
doctor_params.all.append(param.name)
default = None
if param.required:
default = Parameter.empty
doctor_params.required.append(param.name)
else:
doctor_params.optional.append(param.name)
new_params.append(
Parameter(param.name, Parameter.KEYWORD_ONLY, default=default,
annotation=param.annotation))
new_sig = sig.replace(
parameters=list(prev_parameters.values()) + new_params)
logic._doctor_signature = new_sig
logic._doctor_params = doctor_params
return logic | [
"def",
"add_param_annotations",
"(",
"logic",
":",
"Callable",
",",
"params",
":",
"List",
"[",
"RequestParamAnnotation",
"]",
")",
"->",
"Callable",
":",
"# If we've already added param annotations to this function get the",
"# values from the logic, otherwise we need to inspect it.",
"if",
"hasattr",
"(",
"logic",
",",
"'_doctor_signature'",
")",
":",
"sig",
"=",
"logic",
".",
"_doctor_signature",
"doctor_params",
"=",
"logic",
".",
"_doctor_params",
"else",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"logic",
")",
"doctor_params",
"=",
"get_params_from_func",
"(",
"logic",
",",
"sig",
")",
"prev_parameters",
"=",
"{",
"name",
":",
"param",
"for",
"name",
",",
"param",
"in",
"sig",
".",
"parameters",
".",
"items",
"(",
")",
"}",
"new_params",
"=",
"[",
"]",
"for",
"param",
"in",
"params",
":",
"# If the parameter already exists in the function signature, log",
"# a warning and skip it.",
"if",
"param",
".",
"name",
"in",
"prev_parameters",
":",
"logging",
".",
"warning",
"(",
"'Not adding %s to signature of %s, function '",
"'already has that parameter in its signature.'",
",",
"param",
".",
"name",
",",
"logic",
".",
"__name__",
")",
"continue",
"doctor_params",
".",
"all",
".",
"append",
"(",
"param",
".",
"name",
")",
"default",
"=",
"None",
"if",
"param",
".",
"required",
":",
"default",
"=",
"Parameter",
".",
"empty",
"doctor_params",
".",
"required",
".",
"append",
"(",
"param",
".",
"name",
")",
"else",
":",
"doctor_params",
".",
"optional",
".",
"append",
"(",
"param",
".",
"name",
")",
"new_params",
".",
"append",
"(",
"Parameter",
"(",
"param",
".",
"name",
",",
"Parameter",
".",
"KEYWORD_ONLY",
",",
"default",
"=",
"default",
",",
"annotation",
"=",
"param",
".",
"annotation",
")",
")",
"new_sig",
"=",
"sig",
".",
"replace",
"(",
"parameters",
"=",
"list",
"(",
"prev_parameters",
".",
"values",
"(",
")",
")",
"+",
"new_params",
")",
"logic",
".",
"_doctor_signature",
"=",
"new_sig",
"logic",
".",
"_doctor_params",
"=",
"doctor_params",
"return",
"logic"
] | Adds parameter annotations to a logic function.
This adds additional required and/or optional parameters to the logic
function that are not part of it's signature. It's intended to be used
by decorators decorating logic functions or middleware.
:param logic: The logic function to add the parameter annotations to.
:param params: The list of RequestParamAnnotations to add to the logic func.
:returns: The logic func with updated parameter annotations. | [
"Adds",
"parameter",
"annotations",
"to",
"a",
"logic",
"function",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L127-L173 |
upsight/doctor | doctor/utils/__init__.py | get_module_attr | def get_module_attr(module_filename, module_attr, namespace=None):
"""Get an attribute from a module.
This uses exec to load the module with a private namespace, and then
plucks and returns the given attribute from that module's namespace.
Note that, while this method doesn't have any explicit unit tests, it is
tested implicitly by the doctor's own documentation. The Sphinx
build process will fail to generate docs if this does not work.
:param str module_filename: Path to the module to execute (e.g.
"../src/app.py").
:param str module_attr: Attribute to pluck from the module's namespace.
(e.g. "app").
:param dict namespace: Optional namespace. If one is not passed, an empty
dict will be used instead. Note that this function mutates the passed
namespace, so you can inspect a passed dict after calling this method
to see how the module changed it.
:returns: The attribute from the module.
:raises KeyError: if the module doesn't have the given attribute.
"""
if namespace is None:
namespace = {}
module_filename = os.path.abspath(module_filename)
namespace['__file__'] = module_filename
module_dir = os.path.dirname(module_filename)
old_cwd = os.getcwd()
old_sys_path = sys.path[:]
try:
os.chdir(module_dir)
sys.path.append(module_dir)
with open(module_filename, 'r') as mf:
exec(compile(mf.read(), module_filename, 'exec'), namespace)
return namespace[module_attr]
finally:
os.chdir(old_cwd)
sys.path = old_sys_path | python | def get_module_attr(module_filename, module_attr, namespace=None):
"""Get an attribute from a module.
This uses exec to load the module with a private namespace, and then
plucks and returns the given attribute from that module's namespace.
Note that, while this method doesn't have any explicit unit tests, it is
tested implicitly by the doctor's own documentation. The Sphinx
build process will fail to generate docs if this does not work.
:param str module_filename: Path to the module to execute (e.g.
"../src/app.py").
:param str module_attr: Attribute to pluck from the module's namespace.
(e.g. "app").
:param dict namespace: Optional namespace. If one is not passed, an empty
dict will be used instead. Note that this function mutates the passed
namespace, so you can inspect a passed dict after calling this method
to see how the module changed it.
:returns: The attribute from the module.
:raises KeyError: if the module doesn't have the given attribute.
"""
if namespace is None:
namespace = {}
module_filename = os.path.abspath(module_filename)
namespace['__file__'] = module_filename
module_dir = os.path.dirname(module_filename)
old_cwd = os.getcwd()
old_sys_path = sys.path[:]
try:
os.chdir(module_dir)
sys.path.append(module_dir)
with open(module_filename, 'r') as mf:
exec(compile(mf.read(), module_filename, 'exec'), namespace)
return namespace[module_attr]
finally:
os.chdir(old_cwd)
sys.path = old_sys_path | [
"def",
"get_module_attr",
"(",
"module_filename",
",",
"module_attr",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"{",
"}",
"module_filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"module_filename",
")",
"namespace",
"[",
"'__file__'",
"]",
"=",
"module_filename",
"module_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"module_filename",
")",
"old_cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"old_sys_path",
"=",
"sys",
".",
"path",
"[",
":",
"]",
"try",
":",
"os",
".",
"chdir",
"(",
"module_dir",
")",
"sys",
".",
"path",
".",
"append",
"(",
"module_dir",
")",
"with",
"open",
"(",
"module_filename",
",",
"'r'",
")",
"as",
"mf",
":",
"exec",
"(",
"compile",
"(",
"mf",
".",
"read",
"(",
")",
",",
"module_filename",
",",
"'exec'",
")",
",",
"namespace",
")",
"return",
"namespace",
"[",
"module_attr",
"]",
"finally",
":",
"os",
".",
"chdir",
"(",
"old_cwd",
")",
"sys",
".",
"path",
"=",
"old_sys_path"
] | Get an attribute from a module.
This uses exec to load the module with a private namespace, and then
plucks and returns the given attribute from that module's namespace.
Note that, while this method doesn't have any explicit unit tests, it is
tested implicitly by the doctor's own documentation. The Sphinx
build process will fail to generate docs if this does not work.
:param str module_filename: Path to the module to execute (e.g.
"../src/app.py").
:param str module_attr: Attribute to pluck from the module's namespace.
(e.g. "app").
:param dict namespace: Optional namespace. If one is not passed, an empty
dict will be used instead. Note that this function mutates the passed
namespace, so you can inspect a passed dict after calling this method
to see how the module changed it.
:returns: The attribute from the module.
:raises KeyError: if the module doesn't have the given attribute. | [
"Get",
"an",
"attribute",
"from",
"a",
"module",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L176-L212 |
upsight/doctor | doctor/utils/__init__.py | get_description_lines | def get_description_lines(docstring):
"""Extract the description from the given docstring.
This grabs everything up to the first occurrence of something that looks
like a parameter description. The docstring will be dedented and cleaned
up using the standard Sphinx methods.
:param str docstring: The source docstring.
:returns: list
"""
if prepare_docstring is None:
raise ImportError('sphinx must be installed to use this function.')
if not isinstance(docstring, str):
return []
lines = []
for line in prepare_docstring(docstring):
if DESCRIPTION_END_RE.match(line):
break
lines.append(line)
if lines and lines[-1] != '':
lines.append('')
return lines | python | def get_description_lines(docstring):
"""Extract the description from the given docstring.
This grabs everything up to the first occurrence of something that looks
like a parameter description. The docstring will be dedented and cleaned
up using the standard Sphinx methods.
:param str docstring: The source docstring.
:returns: list
"""
if prepare_docstring is None:
raise ImportError('sphinx must be installed to use this function.')
if not isinstance(docstring, str):
return []
lines = []
for line in prepare_docstring(docstring):
if DESCRIPTION_END_RE.match(line):
break
lines.append(line)
if lines and lines[-1] != '':
lines.append('')
return lines | [
"def",
"get_description_lines",
"(",
"docstring",
")",
":",
"if",
"prepare_docstring",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"'sphinx must be installed to use this function.'",
")",
"if",
"not",
"isinstance",
"(",
"docstring",
",",
"str",
")",
":",
"return",
"[",
"]",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"prepare_docstring",
"(",
"docstring",
")",
":",
"if",
"DESCRIPTION_END_RE",
".",
"match",
"(",
"line",
")",
":",
"break",
"lines",
".",
"append",
"(",
"line",
")",
"if",
"lines",
"and",
"lines",
"[",
"-",
"1",
"]",
"!=",
"''",
":",
"lines",
".",
"append",
"(",
"''",
")",
"return",
"lines"
] | Extract the description from the given docstring.
This grabs everything up to the first occurrence of something that looks
like a parameter description. The docstring will be dedented and cleaned
up using the standard Sphinx methods.
:param str docstring: The source docstring.
:returns: list | [
"Extract",
"the",
"description",
"from",
"the",
"given",
"docstring",
"."
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L215-L237 |
upsight/doctor | doctor/utils/__init__.py | get_valid_class_name | def get_valid_class_name(s: str) -> str:
"""Return the given string converted so that it can be used for a class name
Remove leading and trailing spaces; removes spaces and capitalizes each
word; and remove anything that is not alphanumeric. Returns a pep8
compatible class name.
:param s: The string to convert.
:returns: The updated string.
"""
s = str(s).strip()
s = ''.join([w.title() for w in re.split(r'\W+|_', s)])
return re.sub(r'[^\w|_]', '', s) | python | def get_valid_class_name(s: str) -> str:
"""Return the given string converted so that it can be used for a class name
Remove leading and trailing spaces; removes spaces and capitalizes each
word; and remove anything that is not alphanumeric. Returns a pep8
compatible class name.
:param s: The string to convert.
:returns: The updated string.
"""
s = str(s).strip()
s = ''.join([w.title() for w in re.split(r'\W+|_', s)])
return re.sub(r'[^\w|_]', '', s) | [
"def",
"get_valid_class_name",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"s",
"=",
"str",
"(",
"s",
")",
".",
"strip",
"(",
")",
"s",
"=",
"''",
".",
"join",
"(",
"[",
"w",
".",
"title",
"(",
")",
"for",
"w",
"in",
"re",
".",
"split",
"(",
"r'\\W+|_'",
",",
"s",
")",
"]",
")",
"return",
"re",
".",
"sub",
"(",
"r'[^\\w|_]'",
",",
"''",
",",
"s",
")"
] | Return the given string converted so that it can be used for a class name
Remove leading and trailing spaces; removes spaces and capitalizes each
word; and remove anything that is not alphanumeric. Returns a pep8
compatible class name.
:param s: The string to convert.
:returns: The updated string. | [
"Return",
"the",
"given",
"string",
"converted",
"so",
"that",
"it",
"can",
"be",
"used",
"for",
"a",
"class",
"name"
] | train | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/utils/__init__.py#L240-L252 |
Workiva/furious | furious/context/_execution.py | execution_context_from_async | def execution_context_from_async(async):
"""Instantiate a new _ExecutionContext and store a reference to it in the
global async context to make later retrieval easier.
"""
local_context = _local.get_local_context()
if local_context._executing_async_context:
raise errors.ContextExistsError
execution_context = _ExecutionContext(async)
local_context._executing_async_context = execution_context
return execution_context | python | def execution_context_from_async(async):
"""Instantiate a new _ExecutionContext and store a reference to it in the
global async context to make later retrieval easier.
"""
local_context = _local.get_local_context()
if local_context._executing_async_context:
raise errors.ContextExistsError
execution_context = _ExecutionContext(async)
local_context._executing_async_context = execution_context
return execution_context | [
"def",
"execution_context_from_async",
"(",
"async",
")",
":",
"local_context",
"=",
"_local",
".",
"get_local_context",
"(",
")",
"if",
"local_context",
".",
"_executing_async_context",
":",
"raise",
"errors",
".",
"ContextExistsError",
"execution_context",
"=",
"_ExecutionContext",
"(",
"async",
")",
"local_context",
".",
"_executing_async_context",
"=",
"execution_context",
"return",
"execution_context"
] | Instantiate a new _ExecutionContext and store a reference to it in the
global async context to make later retrieval easier. | [
"Instantiate",
"a",
"new",
"_ExecutionContext",
"and",
"store",
"a",
"reference",
"to",
"it",
"in",
"the",
"global",
"async",
"context",
"to",
"make",
"later",
"retrieval",
"easier",
"."
] | train | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/_execution.py#L40-L51 |
QualiSystems/cloudshell-networking-devices | cloudshell/devices/cli_handler_impl.py | CliHandlerImpl.get_cli_service | def get_cli_service(self, command_mode):
"""Use cli.get_session to open CLI connection and switch into required mode
:param CommandMode command_mode: operation mode, can be default_mode/enable_mode/config_mode/etc.
:return: created session in provided mode
:rtype: CommandModeContextManager
"""
return self._cli.get_session(self._new_sessions(), command_mode, self._logger) | python | def get_cli_service(self, command_mode):
"""Use cli.get_session to open CLI connection and switch into required mode
:param CommandMode command_mode: operation mode, can be default_mode/enable_mode/config_mode/etc.
:return: created session in provided mode
:rtype: CommandModeContextManager
"""
return self._cli.get_session(self._new_sessions(), command_mode, self._logger) | [
"def",
"get_cli_service",
"(",
"self",
",",
"command_mode",
")",
":",
"return",
"self",
".",
"_cli",
".",
"get_session",
"(",
"self",
".",
"_new_sessions",
"(",
")",
",",
"command_mode",
",",
"self",
".",
"_logger",
")"
] | Use cli.get_session to open CLI connection and switch into required mode
:param CommandMode command_mode: operation mode, can be default_mode/enable_mode/config_mode/etc.
:return: created session in provided mode
:rtype: CommandModeContextManager | [
"Use",
"cli",
".",
"get_session",
"to",
"open",
"CLI",
"connection",
"and",
"switch",
"into",
"required",
"mode"
] | train | https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/cli_handler_impl.py#L111-L118 |
aiidalab/aiidalab-widgets-base | aiidalab_widgets_base/crystal_sim_crystal.py | check_crystal_equivalence | def check_crystal_equivalence(crystal_a, crystal_b):
"""Function that identifies whether two crystals are equivalent"""
# getting symmetry datasets for both crystals
cryst_a = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_a), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
cryst_b = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_b), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
samecell = np.allclose(cryst_a['std_lattice'], cryst_b['std_lattice'], atol=1e-5)
samenatoms = len(cryst_a['std_positions']) == len(cryst_b['std_positions'])
samespg = cryst_a['number'] == cryst_b['number']
def test_rotations_translations(cryst_a, cryst_b, repeat):
cell = cryst_a['std_lattice']
pristine = crystal('Mg', [(0, 0., 0.)],
spacegroup=int(cryst_a['number']),
cellpar=[cell[0]/repeat[0], cell[1]/repeat[1], cell[2]/repeat[2]]).repeat(repeat)
sym_set_p = spglib.get_symmetry_dataset(ase_to_spgcell(pristine), symprec=1e-5,
angle_tolerance=-1.0, hall_number=0)
for _,trans in enumerate(zip(sym_set_p['rotations'], sym_set_p['translations'])):
pnew=(np.matmul(trans[0],cryst_a['std_positions'].T).T + trans[1]) % 1.0
fulln = np.concatenate([cryst_a['std_types'][:, None], pnew], axis=1)
fullb = np.concatenate([cryst_b['std_types'][:, None], cryst_b['std_positions']], axis=1)
sorted_n = np.array(sorted([ list(row) for row in list(fulln) ]))
sorted_b = np.array(sorted([ list(row) for row in list(fullb) ]))
if np.allclose(sorted_n, sorted_b, atol=1e-5):
return True
return False
if samecell and samenatoms and samespg:
cell = cryst_a['std_lattice']
# we assume there are no crystals with a lattice parameter smaller than 2 A
rng1 = range(1, int(norm(cell[0])/2.))
rng2 = range(1, int(norm(cell[1])/2.))
rng3 = range(1, int(norm(cell[2])/2.))
for repeat in itertools.product(rng1, rng2, rng3):
if test_rotations_translations(cryst_a, cryst_b, repeat):
return True
return False | python | def check_crystal_equivalence(crystal_a, crystal_b):
"""Function that identifies whether two crystals are equivalent"""
# getting symmetry datasets for both crystals
cryst_a = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_a), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
cryst_b = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_b), symprec=1e-5, angle_tolerance=-1.0, hall_number=0)
samecell = np.allclose(cryst_a['std_lattice'], cryst_b['std_lattice'], atol=1e-5)
samenatoms = len(cryst_a['std_positions']) == len(cryst_b['std_positions'])
samespg = cryst_a['number'] == cryst_b['number']
def test_rotations_translations(cryst_a, cryst_b, repeat):
cell = cryst_a['std_lattice']
pristine = crystal('Mg', [(0, 0., 0.)],
spacegroup=int(cryst_a['number']),
cellpar=[cell[0]/repeat[0], cell[1]/repeat[1], cell[2]/repeat[2]]).repeat(repeat)
sym_set_p = spglib.get_symmetry_dataset(ase_to_spgcell(pristine), symprec=1e-5,
angle_tolerance=-1.0, hall_number=0)
for _,trans in enumerate(zip(sym_set_p['rotations'], sym_set_p['translations'])):
pnew=(np.matmul(trans[0],cryst_a['std_positions'].T).T + trans[1]) % 1.0
fulln = np.concatenate([cryst_a['std_types'][:, None], pnew], axis=1)
fullb = np.concatenate([cryst_b['std_types'][:, None], cryst_b['std_positions']], axis=1)
sorted_n = np.array(sorted([ list(row) for row in list(fulln) ]))
sorted_b = np.array(sorted([ list(row) for row in list(fullb) ]))
if np.allclose(sorted_n, sorted_b, atol=1e-5):
return True
return False
if samecell and samenatoms and samespg:
cell = cryst_a['std_lattice']
# we assume there are no crystals with a lattice parameter smaller than 2 A
rng1 = range(1, int(norm(cell[0])/2.))
rng2 = range(1, int(norm(cell[1])/2.))
rng3 = range(1, int(norm(cell[2])/2.))
for repeat in itertools.product(rng1, rng2, rng3):
if test_rotations_translations(cryst_a, cryst_b, repeat):
return True
return False | [
"def",
"check_crystal_equivalence",
"(",
"crystal_a",
",",
"crystal_b",
")",
":",
"# getting symmetry datasets for both crystals",
"cryst_a",
"=",
"spglib",
".",
"get_symmetry_dataset",
"(",
"ase_to_spgcell",
"(",
"crystal_a",
")",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
",",
"hall_number",
"=",
"0",
")",
"cryst_b",
"=",
"spglib",
".",
"get_symmetry_dataset",
"(",
"ase_to_spgcell",
"(",
"crystal_b",
")",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
",",
"hall_number",
"=",
"0",
")",
"samecell",
"=",
"np",
".",
"allclose",
"(",
"cryst_a",
"[",
"'std_lattice'",
"]",
",",
"cryst_b",
"[",
"'std_lattice'",
"]",
",",
"atol",
"=",
"1e-5",
")",
"samenatoms",
"=",
"len",
"(",
"cryst_a",
"[",
"'std_positions'",
"]",
")",
"==",
"len",
"(",
"cryst_b",
"[",
"'std_positions'",
"]",
")",
"samespg",
"=",
"cryst_a",
"[",
"'number'",
"]",
"==",
"cryst_b",
"[",
"'number'",
"]",
"def",
"test_rotations_translations",
"(",
"cryst_a",
",",
"cryst_b",
",",
"repeat",
")",
":",
"cell",
"=",
"cryst_a",
"[",
"'std_lattice'",
"]",
"pristine",
"=",
"crystal",
"(",
"'Mg'",
",",
"[",
"(",
"0",
",",
"0.",
",",
"0.",
")",
"]",
",",
"spacegroup",
"=",
"int",
"(",
"cryst_a",
"[",
"'number'",
"]",
")",
",",
"cellpar",
"=",
"[",
"cell",
"[",
"0",
"]",
"/",
"repeat",
"[",
"0",
"]",
",",
"cell",
"[",
"1",
"]",
"/",
"repeat",
"[",
"1",
"]",
",",
"cell",
"[",
"2",
"]",
"/",
"repeat",
"[",
"2",
"]",
"]",
")",
".",
"repeat",
"(",
"repeat",
")",
"sym_set_p",
"=",
"spglib",
".",
"get_symmetry_dataset",
"(",
"ase_to_spgcell",
"(",
"pristine",
")",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
",",
"hall_number",
"=",
"0",
")",
"for",
"_",
",",
"trans",
"in",
"enumerate",
"(",
"zip",
"(",
"sym_set_p",
"[",
"'rotations'",
"]",
",",
"sym_set_p",
"[",
"'translations'",
"]",
")",
")",
":",
"pnew",
"=",
"(",
"np",
".",
"matmul",
"(",
"trans",
"[",
"0",
"]",
",",
"cryst_a",
"[",
"'std_positions'",
"]",
".",
"T",
")",
".",
"T",
"+",
"trans",
"[",
"1",
"]",
")",
"%",
"1.0",
"fulln",
"=",
"np",
".",
"concatenate",
"(",
"[",
"cryst_a",
"[",
"'std_types'",
"]",
"[",
":",
",",
"None",
"]",
",",
"pnew",
"]",
",",
"axis",
"=",
"1",
")",
"fullb",
"=",
"np",
".",
"concatenate",
"(",
"[",
"cryst_b",
"[",
"'std_types'",
"]",
"[",
":",
",",
"None",
"]",
",",
"cryst_b",
"[",
"'std_positions'",
"]",
"]",
",",
"axis",
"=",
"1",
")",
"sorted_n",
"=",
"np",
".",
"array",
"(",
"sorted",
"(",
"[",
"list",
"(",
"row",
")",
"for",
"row",
"in",
"list",
"(",
"fulln",
")",
"]",
")",
")",
"sorted_b",
"=",
"np",
".",
"array",
"(",
"sorted",
"(",
"[",
"list",
"(",
"row",
")",
"for",
"row",
"in",
"list",
"(",
"fullb",
")",
"]",
")",
")",
"if",
"np",
".",
"allclose",
"(",
"sorted_n",
",",
"sorted_b",
",",
"atol",
"=",
"1e-5",
")",
":",
"return",
"True",
"return",
"False",
"if",
"samecell",
"and",
"samenatoms",
"and",
"samespg",
":",
"cell",
"=",
"cryst_a",
"[",
"'std_lattice'",
"]",
"# we assume there are no crystals with a lattice parameter smaller than 2 A",
"rng1",
"=",
"range",
"(",
"1",
",",
"int",
"(",
"norm",
"(",
"cell",
"[",
"0",
"]",
")",
"/",
"2.",
")",
")",
"rng2",
"=",
"range",
"(",
"1",
",",
"int",
"(",
"norm",
"(",
"cell",
"[",
"1",
"]",
")",
"/",
"2.",
")",
")",
"rng3",
"=",
"range",
"(",
"1",
",",
"int",
"(",
"norm",
"(",
"cell",
"[",
"2",
"]",
")",
"/",
"2.",
")",
")",
"for",
"repeat",
"in",
"itertools",
".",
"product",
"(",
"rng1",
",",
"rng2",
",",
"rng3",
")",
":",
"if",
"test_rotations_translations",
"(",
"cryst_a",
",",
"cryst_b",
",",
"repeat",
")",
":",
"return",
"True",
"return",
"False"
] | Function that identifies whether two crystals are equivalent | [
"Function",
"that",
"identifies",
"whether",
"two",
"crystals",
"are",
"equivalent"
] | train | https://github.com/aiidalab/aiidalab-widgets-base/blob/291a9b159eac902aee655862322670ec1b0cd5b1/aiidalab_widgets_base/crystal_sim_crystal.py#L15-L56 |
eumis/pyviews | pyviews/core/common.py | CoreError.add_view_info | def add_view_info(self, view_info: ViewInfo):
'''Adds view information to error message'''
try:
next(info for info in self._view_infos if info.view == view_info.view)
except StopIteration:
indent = len(self._view_infos) * '\t'
self._view_infos.append(view_info)
info = 'Line {0} in "{1}"'.format(view_info.line, view_info.view)
self.add_info(indent + 'View info', info) | python | def add_view_info(self, view_info: ViewInfo):
'''Adds view information to error message'''
try:
next(info for info in self._view_infos if info.view == view_info.view)
except StopIteration:
indent = len(self._view_infos) * '\t'
self._view_infos.append(view_info)
info = 'Line {0} in "{1}"'.format(view_info.line, view_info.view)
self.add_info(indent + 'View info', info) | [
"def",
"add_view_info",
"(",
"self",
",",
"view_info",
":",
"ViewInfo",
")",
":",
"try",
":",
"next",
"(",
"info",
"for",
"info",
"in",
"self",
".",
"_view_infos",
"if",
"info",
".",
"view",
"==",
"view_info",
".",
"view",
")",
"except",
"StopIteration",
":",
"indent",
"=",
"len",
"(",
"self",
".",
"_view_infos",
")",
"*",
"'\\t'",
"self",
".",
"_view_infos",
".",
"append",
"(",
"view_info",
")",
"info",
"=",
"'Line {0} in \"{1}\"'",
".",
"format",
"(",
"view_info",
".",
"line",
",",
"view_info",
".",
"view",
")",
"self",
".",
"add_info",
"(",
"indent",
"+",
"'View info'",
",",
"info",
")"
] | Adds view information to error message | [
"Adds",
"view",
"information",
"to",
"error",
"message"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/common.py#L18-L26 |
eumis/pyviews | pyviews/core/common.py | CoreError.add_info | def add_info(self, header, message):
'''Adds "header: message" line to error message'''
current_message = self.args[0]
message = current_message + self._format_info(header, message)
self.args = (message,) + self.args[1:] | python | def add_info(self, header, message):
'''Adds "header: message" line to error message'''
current_message = self.args[0]
message = current_message + self._format_info(header, message)
self.args = (message,) + self.args[1:] | [
"def",
"add_info",
"(",
"self",
",",
"header",
",",
"message",
")",
":",
"current_message",
"=",
"self",
".",
"args",
"[",
"0",
"]",
"message",
"=",
"current_message",
"+",
"self",
".",
"_format_info",
"(",
"header",
",",
"message",
")",
"self",
".",
"args",
"=",
"(",
"message",
",",
")",
"+",
"self",
".",
"args",
"[",
"1",
":",
"]"
] | Adds "header: message" line to error message | [
"Adds",
"header",
":",
"message",
"line",
"to",
"error",
"message"
] | train | https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/core/common.py#L28-L32 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.