repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
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 annotat...
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 annotat...
[ "def", "get_json_object_lines", "(", "annotation", ":", "ResourceAnnotation", ",", "properties", ":", "Dict", "[", "str", ",", "Any", "]", ",", "field", ":", "str", ",", "url_params", ":", "Dict", ",", "request", ":", "bool", "=", "False", ",", "object_pro...
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 requ...
[ "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...
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...
[ "def", "get_json_lines", "(", "annotation", ":", "ResourceAnnotation", ",", "field", ":", "str", ",", "route", ":", "str", ",", "request", ":", "bool", "=", "False", ")", "->", "List", ":", "url_params", "=", "URL_PARAMS_RE", ".", "findall", "(", "route", ...
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 ...
[ "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 in...
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 in...
[ "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...
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. :return...
[ "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((val...
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((val...
[ "def", "get_name", "(", "value", ")", "->", "str", ":", "if", "value", ".", "__module__", "==", "'__builtin__'", ":", "return", "value", ".", "__name__", "else", ":", "return", "'.'", ".", "join", "(", "(", "value", ".", "__module__", ",", "value", "."...
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('<...
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('<...
[ "def", "normalize_route", "(", "route", ":", "str", ")", "->", "str", ":", "normalized_route", "=", "str", "(", "route", ")", ".", "lstrip", "(", "'^'", ")", ".", "rstrip", "(", "'$'", ")", ".", "rstrip", "(", "'?'", ")", "normalized_route", "=", "no...
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 ...
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 ...
[ "def", "prefix_lines", "(", "lines", ",", "prefix", ")", ":", "if", "isinstance", "(", "lines", ",", "bytes", ")", ":", "lines", "=", "lines", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "lines", ",", "str", ")", ":", "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 prefi...
[ "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]+...
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]+...
[ "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 ...
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 f...
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 f...
[ "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...
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 mult...
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 mult...
[ "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 assoc...
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 =...
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 =...
[ "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", ...
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 implement...
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 implement...
[ "def", "get_outdated_docs", "(", "cls", ",", "app", ",", "env", ",", "added", ",", "changed", ",", "removed", ")", ":", "# pragma: no cover", "state", "=", "getattr", "(", "env", ",", "cls", ".", "directive_name", ",", "None", ")", "if", "state", "and", ...
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...
[ "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 exte...
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 exte...
[ "def", "purge_docs", "(", "cls", ",", "app", ",", "env", ",", "docname", ")", ":", "# pragma: no cover", "state", "=", "getattr", "(", "env", ",", "cls", ".", "directive_name", ",", "None", ")", "if", "state", "and", "docname", "in", "state", ".", "doc...
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 environm...
[ "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')...
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')...
[ "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", ".", "...
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 ...
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 ...
[ "def", "define_header_values", "(", "self", ",", "http_method", ",", "route", ",", "values", ",", "update", "=", "False", ")", ":", "self", ".", "defined_header_values", "[", "(", "http_method", ".", "lower", "(", ")", ",", "route", ")", "]", "=", "{", ...
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"....
[ "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 ro...
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 ro...
[ "def", "define_example_values", "(", "self", ",", "http_method", ",", "route", ",", "values", ",", "update", "=", "False", ")", ":", "self", ".", "defined_example_values", "[", "(", "http_method", ".", "lower", "(", ")", ",", "route", ")", "]", "=", "{",...
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...
[ "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 ...
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 ...
[ "def", "_get_annotation_heading", "(", "self", ",", "handler", ",", "route", ",", "heading", "=", "None", ")", ":", "if", "hasattr", "(", "handler", ",", "'_doctor_heading'", ")", ":", "return", "handler", ".", "_doctor_heading", "heading", "=", "''", "handl...
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.FooL...
[ "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....
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....
[ "def", "_get_headers", "(", "self", ",", "route", ":", "str", ",", "annotation", ":", "ResourceAnnotation", ")", "->", "Dict", ":", "headers", "=", "self", ".", "headers", ".", "copy", "(", ")", "defined_header_values", "=", "self", ".", "defined_header_valu...
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 ...
[ "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. ...
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. ...
[ "def", "_get_example_values", "(", "self", ",", "route", ":", "str", ",", "annotation", ":", "ResourceAnnotation", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "defined_values", "=", "self", ".", "defined_example_values", ".", "get", "(", "(", "ann...
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.ResourceAnnota...
[ "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 = ...
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 = ...
[ "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", ",...
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,...
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,...
[ "def", "has", "(", "self", ",", "querypart_name", ",", "value", "=", "None", ")", ":", "if", "super", "(", ")", ".", "has", "(", "querypart_name", ",", "value", ")", ":", "return", "True", "if", "not", "value", ":", "return", "super", "(", ")", "."...
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'...
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'...
[ "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 "...
[ "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')) ...
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')) ...
[ "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 co...
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 co...
[ "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_...
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 pr...
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 pr...
[ "def", "process_messages", "(", "tag", ",", "retries", "=", "0", ")", ":", "from", "furious", ".", "batcher", "import", "bump_batch", "from", "furious", ".", "batcher", "import", "MESSAGE_DEFAULT_QUEUE", "from", "furious", ".", "batcher", "import", "MessageItera...
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 t...
[ "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...
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...
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...
[ "def", "set_stats", "(", "stats", ",", "value", ")", ":", "stats", "[", "\"total_count\"", "]", "+=", "1", "stats", "[", "\"value\"", "]", "+=", "value", "stats", "[", "\"average\"", "]", "=", "stats", "[", "\"value\"", "]", "/", "stats", "[", "\"total...
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": {...
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": {...
[ "def", "get_default_stats", "(", ")", ":", "default_stats", "=", "{", "\"total_count\"", ":", "0", ",", "\"max\"", ":", "0", ",", "\"min\"", ":", "0", ",", "\"value\"", ":", "0", ",", "\"average\"", ":", "0", ",", "\"last_update\"", ":", "None", ",", "...
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 deserial...
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 deserial...
[ "def", "serialize_to_json", "(", "result", ",", "unpicklable", "=", "False", ")", ":", "json", "=", "jsonpickle", ".", "encode", "(", "result", ",", "unpicklable", "=", "unpicklable", ")", "result_for_output", "=", "str", "(", "json", ")", "return", "result_...
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...
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...
[ "def", "save", "(", "self", ",", "folder_path", "=", "''", ",", "configuration_type", "=", "'running'", ",", "vrf_management_name", "=", "None", ",", "return_artifact", "=", "False", ")", ":", "if", "hasattr", "(", "self", ".", "resource_config", ",", "\"vrf...
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 ...
[ "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"...
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: ...
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: ...
[ "def", "restore", "(", "self", ",", "path", ",", "configuration_type", "=", "\"running\"", ",", "restore_method", "=", "\"override\"", ",", "vrf_management_name", "=", "None", ")", ":", "if", "hasattr", "(", "self", ".", "resource_config", ",", "\"vrf_management...
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 configurat...
[ "Restore", "configuration", "on", "device", "from", "provided", "configuration", "file", "Restore", "configuration", "from", "local", "file", "system", "or", "ftp", "/", "tftp", "server", "into", "running", "-", "config", "or", "startup", "-", "config", ".", "...
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 ...
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 ...
[ "def", "orchestration_save", "(", "self", ",", "mode", "=", "\"shallow\"", ",", "custom_params", "=", "None", ")", ":", "save_params", "=", "{", "'folder_path'", ":", "''", ",", "'configuration_type'", ":", "'running'", ",", "'return_artifact'", ":", "True", "...
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_...
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_...
[ "def", "orchestration_restore", "(", "self", ",", "saved_artifact_info", ",", "custom_params", "=", "None", ")", ":", "if", "saved_artifact_info", "is", "None", "or", "saved_artifact_info", "==", "''", ":", "raise", "Exception", "(", "'ConfigurationOperations'", ","...
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...
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...
[ "def", "get_path", "(", "self", ",", "path", "=", "''", ")", ":", "if", "not", "path", ":", "host", "=", "self", ".", "resource_config", ".", "backup_location", "if", "':'", "not", "in", "host", ":", "scheme", "=", "self", ".", "resource_config", ".", ...
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': ...
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': ...
[ "def", "_validate_configuration_type", "(", "self", ",", "configuration_type", ")", ":", "if", "configuration_type", ".", "lower", "(", ")", "!=", "'running'", "and", "configuration_type", ".", "lower", "(", ")", "!=", "'startup'", ":", "raise", "Exception", "("...
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_...
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_...
[ "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", ...
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", ",", ...
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 k...
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 k...
[ "def", "inject", "(", "*", "injections", ")", ":", "def", "_decorate", "(", "func", ")", ":", "def", "_decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "keys_to_inject", "=", "[", "name", "for"...
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] = {} se...
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] = {} se...
[ "def", "register", "(", "self", ",", "key", ",", "initializer", ":", "callable", ",", "param", "=", "None", ")", ":", "if", "not", "callable", "(", "initializer", ")", ":", "raise", "DependencyError", "(", "'Initializer {0} is not callable'", ".", "format", ...
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", ...
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...
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...
[ "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, wh...
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 callabl...
[ "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 ro...
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 ro...
[ "def", "create_routes", "(", "routes", ":", "Tuple", "[", "Route", "]", ")", "->", "List", "[", "Tuple", "[", "str", ",", "Resource", "]", "]", ":", "return", "doctor_create_routes", "(", "routes", ",", "handle_http", ",", "default_base_handler_class", "=", ...
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 ...
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 ...
[ "def", "confusion_to_mcc", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "is", "1", ":", "tn", ",", "fp", ",", "fn", ",", "tp", "=", "args", "[", "0", "]", ".", "ravel", "(", ")", ".", "astype", "(", "float", ")", "elif", "len", ...
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 positiv...
[ "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 ...
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 ...
[ "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", "# ch...
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 Fals...
[ "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...
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...
[ "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", ",", "...
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.'.fo...
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.'.fo...
[ "def", "get_inst_type", "(", "xml_node", ":", "XmlNode", ")", ":", "(", "module_path", ",", "class_name", ")", "=", "(", "xml_node", ".", "namespace", ",", "xml_node", ".", "name", ")", "try", ":", "return", "import_module", "(", "module_path", ")", ".", ...
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 [Pa...
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 [Pa...
[ "def", "get_init_args", "(", "inst_type", ",", "init_args", ":", "dict", ",", "add_kwargs", "=", "False", ")", "->", "Tuple", "[", "List", ",", "Dict", "]", ":", "try", ":", "parameters", "=", "signature", "(", "inst_type", ")", ".", "parameters", ".", ...
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.getC...
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.getC...
[ "def", "get_logger_with_thread_id", "(", "context", ")", ":", "logger", "=", "LoggingSessionContext", ".", "get_logger_for_context", "(", "context", ")", "child", "=", "logger", ".", "getChild", "(", "threading", ".", "currentThread", "(", ")", ".", "name", ")",...
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, ...
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, ...
[ "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", ".",...
: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 t...
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 t...
[ "def", "add", "(", "self", ",", "target", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "*", "*", "options", ")", ":", "# In superclass, add new task to our list of tasks", "target", "=", "super", "(", "AutoContext", ",", "self", ")", ".", "ad...
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...
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...
[ "def", "isa", "(", "mnemonic", ":", "str", ",", "opcode", ":", "int", ",", "funct3", ":", "int", "=", "None", ",", "funct7", ":", "int", "=", "None", ",", "*", ",", "variant", "=", "RV32I", ",", "extension", "=", "None", ")", ":", "def", "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-...
[ "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. ...
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. ...
[ "def", "get_insns", "(", "cls", "=", "None", ")", ":", "insns", "=", "[", "]", "if", "cls", "is", "None", ":", "cls", "=", "Instruction", "if", "\"_mnemonic\"", "in", "cls", ".", "__dict__", ".", "keys", "(", ")", ":", "insns", "=", "[", "cls", "...
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 ...
[ "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...
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 N...
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 N...
[ "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...
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...
[ "def", "get_value_from_schema", "(", "schema", ",", "definition", ":", "dict", ",", "key", ":", "str", ",", "definition_key", ":", "str", ")", ":", "resolved_definition", "=", "definition", ".", "copy", "(", ")", "if", "'$ref'", "in", "resolved_definition", ...
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. :para...
[ "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 jso...
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 jso...
[ "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",...
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 fil...
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 fil...
[ "def", "json_schema_type", "(", "schema_file", ":", "str", ",", "*", "*", "kwargs", ")", "->", "typing", ".", "Type", ":", "# Importing here to avoid circular dependencies", "from", "doctor", ".", "resource", "import", "ResourceSchema", "schema", "=", "ResourceSchem...
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 ...
[ "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('St...
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('St...
[ "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('Inte...
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('Inte...
[ "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'...
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'...
[ "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('Bool...
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('Bool...
[ "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,...
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,...
[ "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', (A...
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', (A...
[ "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. """ ...
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. """ ...
[ "def", "new_type", "(", "cls", ",", "*", "*", "kwargs", ")", "->", "typing", ".", "Type", ":", "props", "=", "dict", "(", "cls", ".", "__dict__", ")", "props", ".", "update", "(", "kwargs", ")", "return", "type", "(", "cls", ".", "__name__", ",", ...
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...
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...
[ "def", "get_example", "(", "cls", ")", "->", "dict", ":", "if", "cls", ".", "example", "is", "not", "None", ":", "return", "cls", ".", "example", "return", "{", "k", ":", "v", ".", "get_example", "(", ")", "for", "k", ",", "v", "in", "cls", ".", ...
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.ex...
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.ex...
[ "def", "get_example", "(", "cls", ")", "->", "list", ":", "if", "cls", ".", "example", "is", "not", "None", ":", "return", "cls", ".", "example", "if", "cls", ".", "items", "is", "not", "None", ":", "if", "isinstance", "(", "cls", ".", "items", ","...
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...
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...
[ "def", "render_node", "(", "xml_node", ":", "XmlNode", ",", "*", "*", "args", ")", "->", "Node", ":", "try", ":", "node", "=", "create_node", "(", "xml_node", ",", "*", "*", "args", ")", "pipeline", "=", "get_pipeline", "(", "node", ")", "run_steps", ...
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", ")", "r...
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", ",", "...
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...
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...
[ "def", "apply_attribute", "(", "node", ":", "Node", ",", "attr", ":", "XmlAttr", ")", ":", "setter", "=", "get_setter", "(", "attr", ")", "stripped_value", "=", "attr", ".", "value", ".", "strip", "(", ")", "if", "attr", ".", "value", "else", "''", "...
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", ".", ...
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...
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. ...
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. ...
[ "def", "get_annotation", "(", "cls", ",", "fn", ")", ":", "while", "fn", "is", "not", "None", ":", "if", "hasattr", "(", "fn", ",", "'_schema_annotation'", ")", ":", "return", "fn", ".", "_schema_annotation", "fn", "=", "getattr", "(", "fn", ",", "'im_...
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 ...
[ "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 ...
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 ...
[ "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'", ":", ...
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...
[ "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'] = d...
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'] = d...
[ "def", "update_note", "(", "note_id", ":", "NoteId", ",", "body", ":", "Body", "=", "None", ",", "done", ":", "Done", "=", "None", ")", "->", "Note", ":", "if", "note_id", "!=", "1", ":", "raise", "NotFoundError", "(", "'Note does not exist'", ")", "ne...
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 = { ...
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 = { ...
[ "def", "to_task", "(", "self", ")", ":", "from", "google", ".", "appengine", ".", "api", ".", "taskqueue", "import", "Task", "task_args", "=", "self", ".", "get_task_args", "(", ")", ".", "copy", "(", ")", "payload", "=", "None", "if", "'payload'", "in...
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", "(", ")", ")", ".", "ad...
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...
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...
[ "def", "to_dict", "(", "self", ")", ":", "import", "copy", "options", "=", "copy", ".", "deepcopy", "(", "self", ".", "_options", ")", "# JSON don't like datetimes.", "eta", "=", "options", ".", "get", "(", "'task_args'", ",", "{", "}", ")", ".", "get", ...
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", "=", "i...
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_o...
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_o...
[ "def", "from_dict", "(", "cls", ",", "message", ")", ":", "message_options", "=", "message", ".", "copy", "(", ")", "# JSON don't like datetimes.", "eta", "=", "message_options", ".", "get", "(", "'task_args'", ",", "{", "}", ")", ".", "get", "(", "'eta'",...
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...
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...
[ "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 ...
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", "="...
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: ...
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: ...
[ "def", "fetch_messages", "(", "self", ")", ":", "if", "self", ".", "_fetched", ":", "return", "start", "=", "time", ".", "time", "(", ")", "loaded_messages", "=", "self", ".", "queue", ".", "lease_tasks_by_tag", "(", "self", ".", "duration", ",", "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.
[ "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_messa...
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_messa...
[ "def", "next", "(", "self", ")", ":", "if", "not", "self", ".", "_messages", ":", "if", "self", ".", "auto_delete", ":", "self", ".", "delete_messages", "(", ")", "raise", "StopIteration", "message", "=", "self", ".", "_messages", ".", "pop", "(", "0",...
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 ...
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 ...
[ "def", "delete_messages", "(", "self", ",", "only_processed", "=", "True", ")", ":", "messages", "=", "self", ".", "_processed_messages", "if", "not", "only_processed", ":", "messages", "+=", "self", ".", "_messages", "if", "messages", ":", "try", ":", "self...
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__) ...
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__) ...
[ "def", "copy_func", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "copied", "=", "types", ".", "FunctionType", "(", "func", ".", "__code__", ",", "func", ".", "__globals__", ",", "name", "=", "func", ".", "__name__", ",", "argdefs", "=", "f...
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 an...
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 an...
[ "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", "(", ...
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 deco...
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 deco...
[ "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...
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 an...
[ "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 te...
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 te...
[ "def", "get_module_attr", "(", "module_filename", ",", "module_attr", ",", "namespace", "=", "None", ")", ":", "if", "namespace", "is", "None", ":", "namespace", "=", "{", "}", "module_filename", "=", "os", ".", "path", ".", "abspath", "(", "module_filename"...
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 Sp...
[ "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: T...
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: T...
[ "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...
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 str...
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 str...
[ "def", "get_valid_class_name", "(", "s", ":", "str", ")", "->", "str", ":", "s", "=", "str", "(", "s", ")", ".", "strip", "(", ")", "s", "=", "''", ".", "join", "(", "[", "w", ".", "title", "(", ")", "for", "w", "in", "re", ".", "split", "(...
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 ...
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 ...
[ "def", "execution_context_from_async", "(", "async", ")", ":", "local_context", "=", "_local", ".", "get_local_context", "(", ")", "if", "local_context", ".", "_executing_async_context", ":", "raise", "errors", ".", "ContextExistsError", "execution_context", "=", "_Ex...
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: CommandModeContextMana...
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: CommandModeContextMana...
[ "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_...
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_...
[ "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", ",", "a...
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...
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...
[ "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",...
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", ".", "...
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