repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
jacebrowning/comparable | comparable/tools.py | duplicates | def duplicates(base, items):
"""Get an iterator of items similar but not equal to the base.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: generator of items sorted by similarity to the base
"""
for item in items:
if item.similarity(base) and not item.equality(base):
yield item | python | def duplicates(base, items):
"""Get an iterator of items similar but not equal to the base.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: generator of items sorted by similarity to the base
"""
for item in items:
if item.similarity(base) and not item.equality(base):
yield item | [
"def",
"duplicates",
"(",
"base",
",",
"items",
")",
":",
"for",
"item",
"in",
"items",
":",
"if",
"item",
".",
"similarity",
"(",
"base",
")",
"and",
"not",
"item",
".",
"equality",
"(",
"base",
")",
":",
"yield",
"item"
] | Get an iterator of items similar but not equal to the base.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: generator of items sorted by similarity to the base | [
"Get",
"an",
"iterator",
"of",
"items",
"similar",
"but",
"not",
"equal",
"to",
"the",
"base",
"."
] | train | https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/tools.py#L55-L65 |
jacebrowning/comparable | comparable/tools.py | sort | def sort(base, items):
"""Get a sorted list of items ranked in descending similarity.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: list of items sorted by similarity to the base
"""
return sorted(items, key=base.similarity, reverse=True) | python | def sort(base, items):
"""Get a sorted list of items ranked in descending similarity.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: list of items sorted by similarity to the base
"""
return sorted(items, key=base.similarity, reverse=True) | [
"def",
"sort",
"(",
"base",
",",
"items",
")",
":",
"return",
"sorted",
"(",
"items",
",",
"key",
"=",
"base",
".",
"similarity",
",",
"reverse",
"=",
"True",
")"
] | Get a sorted list of items ranked in descending similarity.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: list of items sorted by similarity to the base | [
"Get",
"a",
"sorted",
"list",
"of",
"items",
"ranked",
"in",
"descending",
"similarity",
"."
] | train | https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/tools.py#L68-L76 |
clusterpoint/python-client-api | pycps/query.py | term | def term(term, xpath=None, escape=True):
""" Escapes <, > and & characters in the given term for inclusion into XML (like the search query).
Also wrap the term in XML tags if xpath is specified.
Note that this function doesn't escape the @, $, " and other symbols that are meaningful in a search query.
Args:
term -- The term text to be escaped (e.g. a search query term).
Keyword args:
xpath -- An optional xpath, to be specified if the term is to wraped in tags.
escape -- An optional parameter - whether to escape the term's XML characters. Default is True.
Returns:
Properly escaped xml string for queries.
>>> term('lorem<4')
'lorem<4'
>>> term('3 < bar < 5 $$ True', 'document/foo', False)
'<document><foo>3 < bar < 5 $$ True</foo></document>'
>>> term('3 < bar < 5 $$ True', 'document/foo')
'<document><foo>3 < bar < 5 $$ True</foo></document>'
"""
prefix = []
postfix = []
if xpath:
tags = xpath.split('/')
for tag in tags:
if tag:
prefix.append('<{0}>'.format(tag))
postfix.insert(0, '</{0}>'.format(tag))
if escape:
term = cgi.escape(term)
return ''.join(prefix + [term] + postfix) | python | def term(term, xpath=None, escape=True):
""" Escapes <, > and & characters in the given term for inclusion into XML (like the search query).
Also wrap the term in XML tags if xpath is specified.
Note that this function doesn't escape the @, $, " and other symbols that are meaningful in a search query.
Args:
term -- The term text to be escaped (e.g. a search query term).
Keyword args:
xpath -- An optional xpath, to be specified if the term is to wraped in tags.
escape -- An optional parameter - whether to escape the term's XML characters. Default is True.
Returns:
Properly escaped xml string for queries.
>>> term('lorem<4')
'lorem<4'
>>> term('3 < bar < 5 $$ True', 'document/foo', False)
'<document><foo>3 < bar < 5 $$ True</foo></document>'
>>> term('3 < bar < 5 $$ True', 'document/foo')
'<document><foo>3 < bar < 5 $$ True</foo></document>'
"""
prefix = []
postfix = []
if xpath:
tags = xpath.split('/')
for tag in tags:
if tag:
prefix.append('<{0}>'.format(tag))
postfix.insert(0, '</{0}>'.format(tag))
if escape:
term = cgi.escape(term)
return ''.join(prefix + [term] + postfix) | [
"def",
"term",
"(",
"term",
",",
"xpath",
"=",
"None",
",",
"escape",
"=",
"True",
")",
":",
"prefix",
"=",
"[",
"]",
"postfix",
"=",
"[",
"]",
"if",
"xpath",
":",
"tags",
"=",
"xpath",
".",
"split",
"(",
"'/'",
")",
"for",
"tag",
"in",
"tags",... | Escapes <, > and & characters in the given term for inclusion into XML (like the search query).
Also wrap the term in XML tags if xpath is specified.
Note that this function doesn't escape the @, $, " and other symbols that are meaningful in a search query.
Args:
term -- The term text to be escaped (e.g. a search query term).
Keyword args:
xpath -- An optional xpath, to be specified if the term is to wraped in tags.
escape -- An optional parameter - whether to escape the term's XML characters. Default is True.
Returns:
Properly escaped xml string for queries.
>>> term('lorem<4')
'lorem<4'
>>> term('3 < bar < 5 $$ True', 'document/foo', False)
'<document><foo>3 < bar < 5 $$ True</foo></document>'
>>> term('3 < bar < 5 $$ True', 'document/foo')
'<document><foo>3 < bar < 5 $$ True</foo></document>' | [
"Escapes",
"<",
">",
"and",
"&",
"characters",
"in",
"the",
"given",
"term",
"for",
"inclusion",
"into",
"XML",
"(",
"like",
"the",
"search",
"query",
")",
".",
"Also",
"wrap",
"the",
"term",
"in",
"XML",
"tags",
"if",
"xpath",
"is",
"specified",
".",
... | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/query.py#L20-L54 |
clusterpoint/python-client-api | pycps/query.py | terms_from_dict | def terms_from_dict(source):
""" Convert a dict representing a query to a string.
Args:
source -- A dict with query xpaths as keys and text or nested query dicts as values.
Returns:
A string composed from the nested query terms given.
>>> terms_from_dict({'document': {'title': "Title this is", 'text': "A long text."}})
'<document><text>A long text.</text><title>Title this is</title></document>'
>>> terms_from_dict({'document/title': "Title this is", 'document/text': "A long text."})
'<document><title>Title this is</title></document><document><text>A long text.</text></document>'
"""
parsed = ''
for xpath, text in source.items():
if hasattr(text, 'keys'):
parsed += term(terms_from_dict(text), xpath, escape=False)
else:
parsed += term(text, xpath)
return parsed | python | def terms_from_dict(source):
""" Convert a dict representing a query to a string.
Args:
source -- A dict with query xpaths as keys and text or nested query dicts as values.
Returns:
A string composed from the nested query terms given.
>>> terms_from_dict({'document': {'title': "Title this is", 'text': "A long text."}})
'<document><text>A long text.</text><title>Title this is</title></document>'
>>> terms_from_dict({'document/title': "Title this is", 'document/text': "A long text."})
'<document><title>Title this is</title></document><document><text>A long text.</text></document>'
"""
parsed = ''
for xpath, text in source.items():
if hasattr(text, 'keys'):
parsed += term(terms_from_dict(text), xpath, escape=False)
else:
parsed += term(text, xpath)
return parsed | [
"def",
"terms_from_dict",
"(",
"source",
")",
":",
"parsed",
"=",
"''",
"for",
"xpath",
",",
"text",
"in",
"source",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"text",
",",
"'keys'",
")",
":",
"parsed",
"+=",
"term",
"(",
"terms_from_dict",
"... | Convert a dict representing a query to a string.
Args:
source -- A dict with query xpaths as keys and text or nested query dicts as values.
Returns:
A string composed from the nested query terms given.
>>> terms_from_dict({'document': {'title': "Title this is", 'text': "A long text."}})
'<document><text>A long text.</text><title>Title this is</title></document>'
>>> terms_from_dict({'document/title': "Title this is", 'document/text': "A long text."})
'<document><title>Title this is</title></document><document><text>A long text.</text></document>' | [
"Convert",
"a",
"dict",
"representing",
"a",
"query",
"to",
"a",
"string",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/query.py#L57-L78 |
clusterpoint/python-client-api | pycps/query.py | and_terms | def and_terms(*args):
""" Connect given term strings or list(s) of term strings with an AND operator for querying.
Args:
An arbitrary number of either strings or lists of strings representing query terms.
Returns
A query string consisting of argument terms and'ed together.
"""
args = [arg if not isinstance(arg, list) else ' '.join(arg) for arg in args]
return '({0})'.format(' '.join(args)) | python | def and_terms(*args):
""" Connect given term strings or list(s) of term strings with an AND operator for querying.
Args:
An arbitrary number of either strings or lists of strings representing query terms.
Returns
A query string consisting of argument terms and'ed together.
"""
args = [arg if not isinstance(arg, list) else ' '.join(arg) for arg in args]
return '({0})'.format(' '.join(args)) | [
"def",
"and_terms",
"(",
"*",
"args",
")",
":",
"args",
"=",
"[",
"arg",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"list",
")",
"else",
"' '",
".",
"join",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
"return",
"'({0})'",
".",
"format",
"(... | Connect given term strings or list(s) of term strings with an AND operator for querying.
Args:
An arbitrary number of either strings or lists of strings representing query terms.
Returns
A query string consisting of argument terms and'ed together. | [
"Connect",
"given",
"term",
"strings",
"or",
"list",
"(",
"s",
")",
"of",
"term",
"strings",
"with",
"an",
"AND",
"operator",
"for",
"querying",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/query.py#L81-L91 |
clusterpoint/python-client-api | pycps/query.py | or_terms | def or_terms(*args):
""" Connect given term strings or list(s) of term strings with a OR operator for querying.
Args:
An arbitrary number of either strings or lists of strings representing query terms.
Returns
A query string consisting of argument terms or'ed together.
"""
args = [arg if not isinstance(arg, list) else ' '.join(arg) for arg in args]
return '{{{0}}}'.format(' '.join(args)) | python | def or_terms(*args):
""" Connect given term strings or list(s) of term strings with a OR operator for querying.
Args:
An arbitrary number of either strings or lists of strings representing query terms.
Returns
A query string consisting of argument terms or'ed together.
"""
args = [arg if not isinstance(arg, list) else ' '.join(arg) for arg in args]
return '{{{0}}}'.format(' '.join(args)) | [
"def",
"or_terms",
"(",
"*",
"args",
")",
":",
"args",
"=",
"[",
"arg",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"list",
")",
"else",
"' '",
".",
"join",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
"return",
"'{{{0}}}'",
".",
"format",
"... | Connect given term strings or list(s) of term strings with a OR operator for querying.
Args:
An arbitrary number of either strings or lists of strings representing query terms.
Returns
A query string consisting of argument terms or'ed together. | [
"Connect",
"given",
"term",
"strings",
"or",
"list",
"(",
"s",
")",
"of",
"term",
"strings",
"with",
"a",
"OR",
"operator",
"for",
"querying",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/query.py#L93-L103 |
salesking/salesking_python_sdk | salesking/utils/validators.py | validate_format_iso8601 | def validate_format_iso8601(validator, fieldname, value, format_option):
"""
validates the iso8601 format
raises value error if the value for fieldname does not match the format
is iso8601 eg #"2007-06-20T12:34:40+03:00"
"""
try:
iso8601.parse_date(value)
except ValueError:
raise ValidationError(
"Value %(value)r of field '%(fieldname)s' is not in "
"'iso8601 YYYY-MM-DDThh:mm:ss(+/-)hh:mm' format" % locals()) | python | def validate_format_iso8601(validator, fieldname, value, format_option):
"""
validates the iso8601 format
raises value error if the value for fieldname does not match the format
is iso8601 eg #"2007-06-20T12:34:40+03:00"
"""
try:
iso8601.parse_date(value)
except ValueError:
raise ValidationError(
"Value %(value)r of field '%(fieldname)s' is not in "
"'iso8601 YYYY-MM-DDThh:mm:ss(+/-)hh:mm' format" % locals()) | [
"def",
"validate_format_iso8601",
"(",
"validator",
",",
"fieldname",
",",
"value",
",",
"format_option",
")",
":",
"try",
":",
"iso8601",
".",
"parse_date",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValidationError",
"(",
"\"Value %(value)r of fie... | validates the iso8601 format
raises value error if the value for fieldname does not match the format
is iso8601 eg #"2007-06-20T12:34:40+03:00" | [
"validates",
"the",
"iso8601",
"format",
"raises",
"value",
"error",
"if",
"the",
"value",
"for",
"fieldname",
"does",
"not",
"match",
"the",
"format",
"is",
"iso8601",
"eg",
"#",
"2007",
"-",
"06",
"-",
"20T12",
":",
"34",
":",
"40",
"+",
"03",
":",
... | train | https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/utils/validators.py#L10-L21 |
salesking/salesking_python_sdk | salesking/utils/validators.py | json_schema_validation_format | def json_schema_validation_format(value, schema_validation_type):
"""
adds iso8601 to the datetimevalidator
raises SchemaError if validation fails
"""
DEFAULT_FORMAT_VALIDATORS['date-time'] = validate_format_iso8601
DEFAULT_FORMAT_VALIDATORS['text'] = validate_format_text
validictory.validate(value, schema_validation_type, format_validators=DEFAULT_FORMAT_VALIDATORS) | python | def json_schema_validation_format(value, schema_validation_type):
"""
adds iso8601 to the datetimevalidator
raises SchemaError if validation fails
"""
DEFAULT_FORMAT_VALIDATORS['date-time'] = validate_format_iso8601
DEFAULT_FORMAT_VALIDATORS['text'] = validate_format_text
validictory.validate(value, schema_validation_type, format_validators=DEFAULT_FORMAT_VALIDATORS) | [
"def",
"json_schema_validation_format",
"(",
"value",
",",
"schema_validation_type",
")",
":",
"DEFAULT_FORMAT_VALIDATORS",
"[",
"'date-time'",
"]",
"=",
"validate_format_iso8601",
"DEFAULT_FORMAT_VALIDATORS",
"[",
"'text'",
"]",
"=",
"validate_format_text",
"validictory",
... | adds iso8601 to the datetimevalidator
raises SchemaError if validation fails | [
"adds",
"iso8601",
"to",
"the",
"datetimevalidator",
"raises",
"SchemaError",
"if",
"validation",
"fails"
] | train | https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/utils/validators.py#L29-L36 |
henzk/ape | ape/__init__.py | get_signature | def get_signature(name, func):
"""
Helper to generate a readable signature for a function
:param name:
:param func:
:return:
"""
args, varargs, keywords, defaults = inspect.getargspec(func)
defaults = defaults or []
posargslen = len(args) - len(defaults)
if varargs is None and keywords is None:
sig = name + '('
sigargs = []
for idx, arg in enumerate(args):
if idx < posargslen:
sigargs.append(arg)
else:
default = repr(defaults[idx - posargslen])
sigargs.append(arg + '=' + default)
sig += ', '.join(sigargs) + ')'
return sig
elif not args and varargs and not keywords and not defaults:
return name + '(*' + varargs + ')'
else:
raise InvalidTask('ape tasks may not use **kwargs') | python | def get_signature(name, func):
"""
Helper to generate a readable signature for a function
:param name:
:param func:
:return:
"""
args, varargs, keywords, defaults = inspect.getargspec(func)
defaults = defaults or []
posargslen = len(args) - len(defaults)
if varargs is None and keywords is None:
sig = name + '('
sigargs = []
for idx, arg in enumerate(args):
if idx < posargslen:
sigargs.append(arg)
else:
default = repr(defaults[idx - posargslen])
sigargs.append(arg + '=' + default)
sig += ', '.join(sigargs) + ')'
return sig
elif not args and varargs and not keywords and not defaults:
return name + '(*' + varargs + ')'
else:
raise InvalidTask('ape tasks may not use **kwargs') | [
"def",
"get_signature",
"(",
"name",
",",
"func",
")",
":",
"args",
",",
"varargs",
",",
"keywords",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"defaults",
"=",
"defaults",
"or",
"[",
"]",
"posargslen",
"=",
"len",
"(",
"args... | Helper to generate a readable signature for a function
:param name:
:param func:
:return: | [
"Helper",
"to",
"generate",
"a",
"readable",
"signature",
"for",
"a",
"function",
":",
"param",
"name",
":",
":",
"param",
"func",
":",
":",
"return",
":"
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/__init__.py#L26-L50 |
henzk/ape | ape/__init__.py | TerminalColor.set | def set(cls, color):
"""
Sets the terminal to the passed color.
:param color: one of the availabe colors.
"""
sys.stdout.write(cls.colors.get(color, cls.colors['RESET'])) | python | def set(cls, color):
"""
Sets the terminal to the passed color.
:param color: one of the availabe colors.
"""
sys.stdout.write(cls.colors.get(color, cls.colors['RESET'])) | [
"def",
"set",
"(",
"cls",
",",
"color",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"cls",
".",
"colors",
".",
"get",
"(",
"color",
",",
"cls",
".",
"colors",
"[",
"'RESET'",
"]",
")",
")"
] | Sets the terminal to the passed color.
:param color: one of the availabe colors. | [
"Sets",
"the",
"terminal",
"to",
"the",
"passed",
"color",
".",
":",
"param",
"color",
":",
"one",
"of",
"the",
"availabe",
"colors",
"."
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/__init__.py#L66-L71 |
henzk/ape | ape/__init__.py | Tasks.register | def register(self, func):
"""
Register a task. Typically used as a decorator to the task function.
If a task by that name already exists,
a TaskAlreadyRegistered exception is raised.
:param func: func to register as an ape task
:return: invalid accessor
"""
if hasattr(self._tasks, func.__name__):
raise TaskAlreadyRegistered(func.__name__)
setattr(self._tasks, func.__name__, func)
return _get_invalid_accessor(func.__name__) | python | def register(self, func):
"""
Register a task. Typically used as a decorator to the task function.
If a task by that name already exists,
a TaskAlreadyRegistered exception is raised.
:param func: func to register as an ape task
:return: invalid accessor
"""
if hasattr(self._tasks, func.__name__):
raise TaskAlreadyRegistered(func.__name__)
setattr(self._tasks, func.__name__, func)
return _get_invalid_accessor(func.__name__) | [
"def",
"register",
"(",
"self",
",",
"func",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_tasks",
",",
"func",
".",
"__name__",
")",
":",
"raise",
"TaskAlreadyRegistered",
"(",
"func",
".",
"__name__",
")",
"setattr",
"(",
"self",
".",
"_tasks",
",",... | Register a task. Typically used as a decorator to the task function.
If a task by that name already exists,
a TaskAlreadyRegistered exception is raised.
:param func: func to register as an ape task
:return: invalid accessor | [
"Register",
"a",
"task",
".",
"Typically",
"used",
"as",
"a",
"decorator",
"to",
"the",
"task",
"function",
"."
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/__init__.py#L93-L106 |
henzk/ape | ape/__init__.py | Tasks.register_helper | def register_helper(self, func):
"""
A helper is a task that is not directly exposed to
the command line
:param func: registers func as a helper
:return: invalid accessor
"""
self._helper_names.add(func.__name__)
return self.register(func) | python | def register_helper(self, func):
"""
A helper is a task that is not directly exposed to
the command line
:param func: registers func as a helper
:return: invalid accessor
"""
self._helper_names.add(func.__name__)
return self.register(func) | [
"def",
"register_helper",
"(",
"self",
",",
"func",
")",
":",
"self",
".",
"_helper_names",
".",
"add",
"(",
"func",
".",
"__name__",
")",
"return",
"self",
".",
"register",
"(",
"func",
")"
] | A helper is a task that is not directly exposed to
the command line
:param func: registers func as a helper
:return: invalid accessor | [
"A",
"helper",
"is",
"a",
"task",
"that",
"is",
"not",
"directly",
"exposed",
"to",
"the",
"command",
"line",
":",
"param",
"func",
":",
"registers",
"func",
"as",
"a",
"helper",
":",
"return",
":",
"invalid",
"accessor"
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/__init__.py#L108-L117 |
henzk/ape | ape/__init__.py | Tasks.get_tasks | def get_tasks(self):
"""
Return tasks as list of (name, function) tuples.
"""
def predicate(item):
return (inspect.isfunction(item) and
item.__name__ not in self._helper_names)
return inspect.getmembers(self._tasks, predicate) | python | def get_tasks(self):
"""
Return tasks as list of (name, function) tuples.
"""
def predicate(item):
return (inspect.isfunction(item) and
item.__name__ not in self._helper_names)
return inspect.getmembers(self._tasks, predicate) | [
"def",
"get_tasks",
"(",
"self",
")",
":",
"def",
"predicate",
"(",
"item",
")",
":",
"return",
"(",
"inspect",
".",
"isfunction",
"(",
"item",
")",
"and",
"item",
".",
"__name__",
"not",
"in",
"self",
".",
"_helper_names",
")",
"return",
"inspect",
".... | Return tasks as list of (name, function) tuples. | [
"Return",
"tasks",
"as",
"list",
"of",
"(",
"name",
"function",
")",
"tuples",
"."
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/__init__.py#L119-L127 |
henzk/ape | ape/__init__.py | Tasks.get_task | def get_task(self, name, include_helpers=True):
"""
Get task identified by name or raise TaskNotFound if there
is no such task
:param name: name of helper/task to get
:param include_helpers: if True, also look for helpers
:return: task or helper identified by name
"""
if not include_helpers and name in self._helper_names:
raise TaskNotFound(name)
try:
return getattr(self._tasks, name)
except AttributeError:
raise TaskNotFound(name) | python | def get_task(self, name, include_helpers=True):
"""
Get task identified by name or raise TaskNotFound if there
is no such task
:param name: name of helper/task to get
:param include_helpers: if True, also look for helpers
:return: task or helper identified by name
"""
if not include_helpers and name in self._helper_names:
raise TaskNotFound(name)
try:
return getattr(self._tasks, name)
except AttributeError:
raise TaskNotFound(name) | [
"def",
"get_task",
"(",
"self",
",",
"name",
",",
"include_helpers",
"=",
"True",
")",
":",
"if",
"not",
"include_helpers",
"and",
"name",
"in",
"self",
".",
"_helper_names",
":",
"raise",
"TaskNotFound",
"(",
"name",
")",
"try",
":",
"return",
"getattr",
... | Get task identified by name or raise TaskNotFound if there
is no such task
:param name: name of helper/task to get
:param include_helpers: if True, also look for helpers
:return: task or helper identified by name | [
"Get",
"task",
"identified",
"by",
"name",
"or",
"raise",
"TaskNotFound",
"if",
"there",
"is",
"no",
"such",
"task",
":",
"param",
"name",
":",
"name",
"of",
"helper",
"/",
"task",
"to",
"get",
":",
"param",
"include_helpers",
":",
"if",
"True",
"also",
... | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/__init__.py#L129-L143 |
henzk/ape | ape/__init__.py | Tasks.print_task_help | def print_task_help(self, task, name):
"""
Prints the help for the passed task with the passed name.
:param task: the task function object
:param name: the name of the module.
:return: None
"""
TerminalColor.set('GREEN')
print(get_signature(name, task))
# TODO: print the location does not work properly and sometimes returns None
# print(' => defined in: {}'.format(inspect.getsourcefile(task)))
help_msg = inspect.getdoc(task) or ''
TerminalColor.reset()
print(' ' + help_msg.replace('\n', '\n '))
TerminalColor.reset()
print() | python | def print_task_help(self, task, name):
"""
Prints the help for the passed task with the passed name.
:param task: the task function object
:param name: the name of the module.
:return: None
"""
TerminalColor.set('GREEN')
print(get_signature(name, task))
# TODO: print the location does not work properly and sometimes returns None
# print(' => defined in: {}'.format(inspect.getsourcefile(task)))
help_msg = inspect.getdoc(task) or ''
TerminalColor.reset()
print(' ' + help_msg.replace('\n', '\n '))
TerminalColor.reset()
print() | [
"def",
"print_task_help",
"(",
"self",
",",
"task",
",",
"name",
")",
":",
"TerminalColor",
".",
"set",
"(",
"'GREEN'",
")",
"print",
"(",
"get_signature",
"(",
"name",
",",
"task",
")",
")",
"# TODO: print the location does not work properly and sometimes returns N... | Prints the help for the passed task with the passed name.
:param task: the task function object
:param name: the name of the module.
:return: None | [
"Prints",
"the",
"help",
"for",
"the",
"passed",
"task",
"with",
"the",
"passed",
"name",
".",
":",
"param",
"task",
":",
"the",
"task",
"function",
"object",
":",
"param",
"name",
":",
"the",
"name",
"of",
"the",
"module",
".",
":",
"return",
":",
"... | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/__init__.py#L145-L161 |
henzk/ape | ape/__init__.py | Tasks.help | def help(self, taskname=None):
"""
List tasks or provide help for specific task
:param taskname: if supplied, help for this specific task is displayed.
Otherwise, displays overview of available tasks.
:return: None
"""
if not taskname:
print(inspect.getdoc(self._tasks))
print()
print('Available tasks:')
print()
for task in self.get_tasks():
self.print_task_help(task[1], task[0])
else:
try:
task = self.get_task(taskname)
self.print_task_help(task, task.__name__)
except TaskNotFound:
print('Task "%s" not found! Use "ape help" to get usage information.' % taskname) | python | def help(self, taskname=None):
"""
List tasks or provide help for specific task
:param taskname: if supplied, help for this specific task is displayed.
Otherwise, displays overview of available tasks.
:return: None
"""
if not taskname:
print(inspect.getdoc(self._tasks))
print()
print('Available tasks:')
print()
for task in self.get_tasks():
self.print_task_help(task[1], task[0])
else:
try:
task = self.get_task(taskname)
self.print_task_help(task, task.__name__)
except TaskNotFound:
print('Task "%s" not found! Use "ape help" to get usage information.' % taskname) | [
"def",
"help",
"(",
"self",
",",
"taskname",
"=",
"None",
")",
":",
"if",
"not",
"taskname",
":",
"print",
"(",
"inspect",
".",
"getdoc",
"(",
"self",
".",
"_tasks",
")",
")",
"print",
"(",
")",
"print",
"(",
"'Available tasks:'",
")",
"print",
"(",
... | List tasks or provide help for specific task
:param taskname: if supplied, help for this specific task is displayed.
Otherwise, displays overview of available tasks.
:return: None | [
"List",
"tasks",
"or",
"provide",
"help",
"for",
"specific",
"task",
":",
"param",
"taskname",
":",
"if",
"supplied",
"help",
"for",
"this",
"specific",
"task",
"is",
"displayed",
".",
"Otherwise",
"displays",
"overview",
"of",
"available",
"tasks",
".",
":"... | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/__init__.py#L163-L185 |
henzk/ape | ape/__init__.py | Tasks.superimpose | def superimpose(self, module):
"""
superimpose a task module on registered tasks'''
:param module: ape tasks module that is superimposed on available ape tasks
:return: None
"""
featuremonkey.compose(module, self._tasks)
self._tasks.FEATURE_SELECTION.append(module.__name__) | python | def superimpose(self, module):
"""
superimpose a task module on registered tasks'''
:param module: ape tasks module that is superimposed on available ape tasks
:return: None
"""
featuremonkey.compose(module, self._tasks)
self._tasks.FEATURE_SELECTION.append(module.__name__) | [
"def",
"superimpose",
"(",
"self",
",",
"module",
")",
":",
"featuremonkey",
".",
"compose",
"(",
"module",
",",
"self",
".",
"_tasks",
")",
"self",
".",
"_tasks",
".",
"FEATURE_SELECTION",
".",
"append",
"(",
"module",
".",
"__name__",
")"
] | superimpose a task module on registered tasks'''
:param module: ape tasks module that is superimposed on available ape tasks
:return: None | [
"superimpose",
"a",
"task",
"module",
"on",
"registered",
"tasks",
":",
"param",
"module",
":",
"ape",
"tasks",
"module",
"that",
"is",
"superimposed",
"on",
"available",
"ape",
"tasks",
":",
"return",
":",
"None"
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/__init__.py#L198-L205 |
aerogear/digger-build-cli | digger/base/action.py | BaseAction.props | def props(cls):
"""
Class method that returns all defined arguments within the class.
Returns:
A dictionary containing all action defined arguments (if any).
"""
return {k:v for (k, v) in inspect.getmembers(cls) if type(v) is Argument} | python | def props(cls):
"""
Class method that returns all defined arguments within the class.
Returns:
A dictionary containing all action defined arguments (if any).
"""
return {k:v for (k, v) in inspect.getmembers(cls) if type(v) is Argument} | [
"def",
"props",
"(",
"cls",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"inspect",
".",
"getmembers",
"(",
"cls",
")",
"if",
"type",
"(",
"v",
")",
"is",
"Argument",
"}"
] | Class method that returns all defined arguments within the class.
Returns:
A dictionary containing all action defined arguments (if any). | [
"Class",
"method",
"that",
"returns",
"all",
"defined",
"arguments",
"within",
"the",
"class",
".",
"Returns",
":",
"A",
"dictionary",
"containing",
"all",
"action",
"defined",
"arguments",
"(",
"if",
"any",
")",
"."
] | train | https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/base/action.py#L82-L89 |
eshandas/simple_django_logger | django_project/simple_django_logger/tasks/__init__.py | purge_old_logs | def purge_old_logs(delete_before_days=7):
"""
Purges old logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = Log.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | python | def purge_old_logs(delete_before_days=7):
"""
Purges old logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = Log.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | [
"def",
"purge_old_logs",
"(",
"delete_before_days",
"=",
"7",
")",
":",
"delete_before_date",
"=",
"timezone",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"days",
"=",
"delete_before_days",
")",
"logs_deleted",
"=",
"Log",
".",
"objects",
".",
"filter",
"("... | Purges old logs from the database table | [
"Purges",
"old",
"logs",
"from",
"the",
"database",
"table"
] | train | https://github.com/eshandas/simple_django_logger/blob/a6d15ca1c1ded414ed8fe5cc0c4ca0c20a846582/django_project/simple_django_logger/tasks/__init__.py#L16-L23 |
eshandas/simple_django_logger | django_project/simple_django_logger/tasks/__init__.py | purge_old_event_logs | def purge_old_event_logs(delete_before_days=7):
"""
Purges old event logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = EventLog.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | python | def purge_old_event_logs(delete_before_days=7):
"""
Purges old event logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = EventLog.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | [
"def",
"purge_old_event_logs",
"(",
"delete_before_days",
"=",
"7",
")",
":",
"delete_before_date",
"=",
"timezone",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"days",
"=",
"delete_before_days",
")",
"logs_deleted",
"=",
"EventLog",
".",
"objects",
".",
"fil... | Purges old event logs from the database table | [
"Purges",
"old",
"event",
"logs",
"from",
"the",
"database",
"table"
] | train | https://github.com/eshandas/simple_django_logger/blob/a6d15ca1c1ded414ed8fe5cc0c4ca0c20a846582/django_project/simple_django_logger/tasks/__init__.py#L27-L34 |
eshandas/simple_django_logger | django_project/simple_django_logger/tasks/__init__.py | purge_old_request_logs | def purge_old_request_logs(delete_before_days=7):
"""
Purges old request logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = RequestLog.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | python | def purge_old_request_logs(delete_before_days=7):
"""
Purges old request logs from the database table
"""
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = RequestLog.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | [
"def",
"purge_old_request_logs",
"(",
"delete_before_days",
"=",
"7",
")",
":",
"delete_before_date",
"=",
"timezone",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"days",
"=",
"delete_before_days",
")",
"logs_deleted",
"=",
"RequestLog",
".",
"objects",
".",
... | Purges old request logs from the database table | [
"Purges",
"old",
"request",
"logs",
"from",
"the",
"database",
"table"
] | train | https://github.com/eshandas/simple_django_logger/blob/a6d15ca1c1ded414ed8fe5cc0c4ca0c20a846582/django_project/simple_django_logger/tasks/__init__.py#L38-L45 |
petebachant/PXL | pxl/timeseries.py | sigmafilter | def sigmafilter(data, sigmas, passes):
"""Remove datapoints outside of a specified standard deviation range."""
for n in range(passes):
meandata = np.mean(data[~np.isnan(data)])
sigma = np.std(data[~np.isnan(data)])
data[data > meandata+sigmas*sigma] = np.nan
data[data < meandata-sigmas*sigma] = np.nan
return data | python | def sigmafilter(data, sigmas, passes):
"""Remove datapoints outside of a specified standard deviation range."""
for n in range(passes):
meandata = np.mean(data[~np.isnan(data)])
sigma = np.std(data[~np.isnan(data)])
data[data > meandata+sigmas*sigma] = np.nan
data[data < meandata-sigmas*sigma] = np.nan
return data | [
"def",
"sigmafilter",
"(",
"data",
",",
"sigmas",
",",
"passes",
")",
":",
"for",
"n",
"in",
"range",
"(",
"passes",
")",
":",
"meandata",
"=",
"np",
".",
"mean",
"(",
"data",
"[",
"~",
"np",
".",
"isnan",
"(",
"data",
")",
"]",
")",
"sigma",
"... | Remove datapoints outside of a specified standard deviation range. | [
"Remove",
"datapoints",
"outside",
"of",
"a",
"specified",
"standard",
"deviation",
"range",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L13-L20 |
petebachant/PXL | pxl/timeseries.py | psd | def psd(t, data, window=None, n_band_average=1):
"""Compute one-sided power spectral density, subtracting mean automatically.
Parameters
----------
t : Time array
data : Time series data
window : {None, "Hanning"}
n_band_average : Number of samples over which to band average
Returns
-------
f : Frequency array
psd : Spectral density array
"""
dt = t[1] - t[0]
N = len(data)
data = data - np.mean(data)
if window == "Hanning":
data = data*np.hanning(N)
f = np.fft.fftfreq(N, dt)
y = np.fft.fft(data)
f = f[0:N/2]
psd = (2*dt/N)*abs(y)**2
psd = np.real(psd[0:N/2])
if n_band_average > 1:
f_raw, s_raw = f*1, psd*1
f = np.zeros(len(f_raw)//n_band_average)
psd = np.zeros(len(f_raw)//n_band_average)
for n in range(len(f_raw)//n_band_average):
f[n] = np.mean(f_raw[n*n_band_average:(n+1)*n_band_average])
psd[n] = np.mean(s_raw[n*n_band_average:(n+1)*n_band_average])
return f, psd | python | def psd(t, data, window=None, n_band_average=1):
"""Compute one-sided power spectral density, subtracting mean automatically.
Parameters
----------
t : Time array
data : Time series data
window : {None, "Hanning"}
n_band_average : Number of samples over which to band average
Returns
-------
f : Frequency array
psd : Spectral density array
"""
dt = t[1] - t[0]
N = len(data)
data = data - np.mean(data)
if window == "Hanning":
data = data*np.hanning(N)
f = np.fft.fftfreq(N, dt)
y = np.fft.fft(data)
f = f[0:N/2]
psd = (2*dt/N)*abs(y)**2
psd = np.real(psd[0:N/2])
if n_band_average > 1:
f_raw, s_raw = f*1, psd*1
f = np.zeros(len(f_raw)//n_band_average)
psd = np.zeros(len(f_raw)//n_band_average)
for n in range(len(f_raw)//n_band_average):
f[n] = np.mean(f_raw[n*n_band_average:(n+1)*n_band_average])
psd[n] = np.mean(s_raw[n*n_band_average:(n+1)*n_band_average])
return f, psd | [
"def",
"psd",
"(",
"t",
",",
"data",
",",
"window",
"=",
"None",
",",
"n_band_average",
"=",
"1",
")",
":",
"dt",
"=",
"t",
"[",
"1",
"]",
"-",
"t",
"[",
"0",
"]",
"N",
"=",
"len",
"(",
"data",
")",
"data",
"=",
"data",
"-",
"np",
".",
"m... | Compute one-sided power spectral density, subtracting mean automatically.
Parameters
----------
t : Time array
data : Time series data
window : {None, "Hanning"}
n_band_average : Number of samples over which to band average
Returns
-------
f : Frequency array
psd : Spectral density array | [
"Compute",
"one",
"-",
"sided",
"power",
"spectral",
"density",
"subtracting",
"mean",
"automatically",
".",
"Parameters",
"----------",
"t",
":",
"Time",
"array",
"data",
":",
"Time",
"series",
"data",
"window",
":",
"{",
"None",
"Hanning",
"}",
"n_band_avera... | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L23-L55 |
petebachant/PXL | pxl/timeseries.py | runningstd | def runningstd(t, data, width):
"""Compute the running standard deviation of a time series.
Returns `t_new`, `std_r`.
"""
ne = len(t) - width
t_new = np.zeros(ne)
std_r = np.zeros(ne)
for i in range(ne):
t_new[i] = np.mean(t[i:i+width+1])
std_r[i] = scipy.stats.nanstd(data[i:i+width+1])
return t_new, std_r | python | def runningstd(t, data, width):
"""Compute the running standard deviation of a time series.
Returns `t_new`, `std_r`.
"""
ne = len(t) - width
t_new = np.zeros(ne)
std_r = np.zeros(ne)
for i in range(ne):
t_new[i] = np.mean(t[i:i+width+1])
std_r[i] = scipy.stats.nanstd(data[i:i+width+1])
return t_new, std_r | [
"def",
"runningstd",
"(",
"t",
",",
"data",
",",
"width",
")",
":",
"ne",
"=",
"len",
"(",
"t",
")",
"-",
"width",
"t_new",
"=",
"np",
".",
"zeros",
"(",
"ne",
")",
"std_r",
"=",
"np",
".",
"zeros",
"(",
"ne",
")",
"for",
"i",
"in",
"range",
... | Compute the running standard deviation of a time series.
Returns `t_new`, `std_r`. | [
"Compute",
"the",
"running",
"standard",
"deviation",
"of",
"a",
"time",
"series",
".",
"Returns",
"t_new",
"std_r",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L58-L69 |
petebachant/PXL | pxl/timeseries.py | smooth | def smooth(data, fw):
"""Smooth data with a moving average."""
if fw == 0:
fdata = data
else:
fdata = lfilter(np.ones(fw)/fw, 1, data)
return fdata | python | def smooth(data, fw):
"""Smooth data with a moving average."""
if fw == 0:
fdata = data
else:
fdata = lfilter(np.ones(fw)/fw, 1, data)
return fdata | [
"def",
"smooth",
"(",
"data",
",",
"fw",
")",
":",
"if",
"fw",
"==",
"0",
":",
"fdata",
"=",
"data",
"else",
":",
"fdata",
"=",
"lfilter",
"(",
"np",
".",
"ones",
"(",
"fw",
")",
"/",
"fw",
",",
"1",
",",
"data",
")",
"return",
"fdata"
] | Smooth data with a moving average. | [
"Smooth",
"data",
"with",
"a",
"moving",
"average",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L72-L78 |
petebachant/PXL | pxl/timeseries.py | calcstats | def calcstats(data, t1, t2, sr):
"""Calculate the mean and standard deviation of some array between
t1 and t2 provided the sample rate sr.
"""
dataseg = data[sr*t1:sr*t2]
meandata = np.mean(dataseg[~np.isnan(dataseg)])
stddata = np.std(dataseg[~np.isnan(dataseg)])
return meandata, stddata | python | def calcstats(data, t1, t2, sr):
"""Calculate the mean and standard deviation of some array between
t1 and t2 provided the sample rate sr.
"""
dataseg = data[sr*t1:sr*t2]
meandata = np.mean(dataseg[~np.isnan(dataseg)])
stddata = np.std(dataseg[~np.isnan(dataseg)])
return meandata, stddata | [
"def",
"calcstats",
"(",
"data",
",",
"t1",
",",
"t2",
",",
"sr",
")",
":",
"dataseg",
"=",
"data",
"[",
"sr",
"*",
"t1",
":",
"sr",
"*",
"t2",
"]",
"meandata",
"=",
"np",
".",
"mean",
"(",
"dataseg",
"[",
"~",
"np",
".",
"isnan",
"(",
"datas... | Calculate the mean and standard deviation of some array between
t1 and t2 provided the sample rate sr. | [
"Calculate",
"the",
"mean",
"and",
"standard",
"deviation",
"of",
"some",
"array",
"between",
"t1",
"and",
"t2",
"provided",
"the",
"sample",
"rate",
"sr",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L81-L88 |
petebachant/PXL | pxl/timeseries.py | average_over_area | def average_over_area(q, x, y):
"""Averages a quantity `q` over a rectangular area given a 2D array and
the x and y vectors for sample locations, using the trapezoidal rule"""
area = (np.max(x) - np.min(x))*(np.max(y) - np.min(y))
integral = np.trapz(np.trapz(q, y, axis=0), x)
return integral/area | python | def average_over_area(q, x, y):
"""Averages a quantity `q` over a rectangular area given a 2D array and
the x and y vectors for sample locations, using the trapezoidal rule"""
area = (np.max(x) - np.min(x))*(np.max(y) - np.min(y))
integral = np.trapz(np.trapz(q, y, axis=0), x)
return integral/area | [
"def",
"average_over_area",
"(",
"q",
",",
"x",
",",
"y",
")",
":",
"area",
"=",
"(",
"np",
".",
"max",
"(",
"x",
")",
"-",
"np",
".",
"min",
"(",
"x",
")",
")",
"*",
"(",
"np",
".",
"max",
"(",
"y",
")",
"-",
"np",
".",
"min",
"(",
"y"... | Averages a quantity `q` over a rectangular area given a 2D array and
the x and y vectors for sample locations, using the trapezoidal rule | [
"Averages",
"a",
"quantity",
"q",
"over",
"a",
"rectangular",
"area",
"given",
"a",
"2D",
"array",
"and",
"the",
"x",
"and",
"y",
"vectors",
"for",
"sample",
"locations",
"using",
"the",
"trapezoidal",
"rule"
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L91-L96 |
petebachant/PXL | pxl/timeseries.py | build_plane_arrays | def build_plane_arrays(x, y, qlist):
"""Build a 2-D array out of data taken in the same plane, for contour
plotting.
"""
if type(qlist) is not list:
return_list = False
qlist = [qlist]
else:
return_list = True
xv = x[np.where(y==y[0])[0]]
yv = y[np.where(x==x[0])[0]]
qlistp = []
for n in range(len(qlist)):
qlistp.append(np.zeros((len(yv), len(xv))))
for j in range(len(qlist)):
for n in range(len(yv)):
i = np.where(y==yv[n])[0]
qlistp[j][n,:] = qlist[j][i]
if not return_list:
qlistp = qlistp[0]
return xv, yv, qlistp | python | def build_plane_arrays(x, y, qlist):
"""Build a 2-D array out of data taken in the same plane, for contour
plotting.
"""
if type(qlist) is not list:
return_list = False
qlist = [qlist]
else:
return_list = True
xv = x[np.where(y==y[0])[0]]
yv = y[np.where(x==x[0])[0]]
qlistp = []
for n in range(len(qlist)):
qlistp.append(np.zeros((len(yv), len(xv))))
for j in range(len(qlist)):
for n in range(len(yv)):
i = np.where(y==yv[n])[0]
qlistp[j][n,:] = qlist[j][i]
if not return_list:
qlistp = qlistp[0]
return xv, yv, qlistp | [
"def",
"build_plane_arrays",
"(",
"x",
",",
"y",
",",
"qlist",
")",
":",
"if",
"type",
"(",
"qlist",
")",
"is",
"not",
"list",
":",
"return_list",
"=",
"False",
"qlist",
"=",
"[",
"qlist",
"]",
"else",
":",
"return_list",
"=",
"True",
"xv",
"=",
"x... | Build a 2-D array out of data taken in the same plane, for contour
plotting. | [
"Build",
"a",
"2",
"-",
"D",
"array",
"out",
"of",
"data",
"taken",
"in",
"the",
"same",
"plane",
"for",
"contour",
"plotting",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L99-L119 |
petebachant/PXL | pxl/timeseries.py | corr_coeff | def corr_coeff(x1, x2, t, tau1, tau2):
"""Compute lagged correlation coefficient for two time series."""
dt = t[1] - t[0]
tau = np.arange(tau1, tau2+dt, dt)
rho = np.zeros(len(tau))
for n in range(len(tau)):
i = np.abs(int(tau[n]/dt))
if tau[n] >= 0: # Positive lag, push x2 forward in time
seg2 = x2[0:-1-i]
seg1 = x1[i:-1]
elif tau[n] < 0: # Negative lag, push x2 back in time
seg1 = x1[0:-i-1]
seg2 = x2[i:-1]
seg1 = seg1 - seg1.mean()
seg2 = seg2 - seg2.mean()
rho[n] = np.mean(seg1*seg2)/seg1.std()/seg2.std()
return tau, rho | python | def corr_coeff(x1, x2, t, tau1, tau2):
"""Compute lagged correlation coefficient for two time series."""
dt = t[1] - t[0]
tau = np.arange(tau1, tau2+dt, dt)
rho = np.zeros(len(tau))
for n in range(len(tau)):
i = np.abs(int(tau[n]/dt))
if tau[n] >= 0: # Positive lag, push x2 forward in time
seg2 = x2[0:-1-i]
seg1 = x1[i:-1]
elif tau[n] < 0: # Negative lag, push x2 back in time
seg1 = x1[0:-i-1]
seg2 = x2[i:-1]
seg1 = seg1 - seg1.mean()
seg2 = seg2 - seg2.mean()
rho[n] = np.mean(seg1*seg2)/seg1.std()/seg2.std()
return tau, rho | [
"def",
"corr_coeff",
"(",
"x1",
",",
"x2",
",",
"t",
",",
"tau1",
",",
"tau2",
")",
":",
"dt",
"=",
"t",
"[",
"1",
"]",
"-",
"t",
"[",
"0",
"]",
"tau",
"=",
"np",
".",
"arange",
"(",
"tau1",
",",
"tau2",
"+",
"dt",
",",
"dt",
")",
"rho",
... | Compute lagged correlation coefficient for two time series. | [
"Compute",
"lagged",
"correlation",
"coefficient",
"for",
"two",
"time",
"series",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L122-L138 |
petebachant/PXL | pxl/timeseries.py | autocorr_coeff | def autocorr_coeff(x, t, tau1, tau2):
"""Calculate the autocorrelation coefficient."""
return corr_coeff(x, x, t, tau1, tau2) | python | def autocorr_coeff(x, t, tau1, tau2):
"""Calculate the autocorrelation coefficient."""
return corr_coeff(x, x, t, tau1, tau2) | [
"def",
"autocorr_coeff",
"(",
"x",
",",
"t",
",",
"tau1",
",",
"tau2",
")",
":",
"return",
"corr_coeff",
"(",
"x",
",",
"x",
",",
"t",
",",
"tau1",
",",
"tau2",
")"
] | Calculate the autocorrelation coefficient. | [
"Calculate",
"the",
"autocorrelation",
"coefficient",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L141-L143 |
petebachant/PXL | pxl/timeseries.py | integral_scale | def integral_scale(u, t, tau1=0.0, tau2=1.0):
"""Calculate the integral scale of a time series by integrating up to
the first zero crossing.
"""
tau, rho = autocorr_coeff(u, t, tau1, tau2)
zero_cross_ind = np.where(np.diff(np.sign(rho)))[0][0]
int_scale = np.trapz(rho[:zero_cross_ind], tau[:zero_cross_ind])
return int_scale | python | def integral_scale(u, t, tau1=0.0, tau2=1.0):
"""Calculate the integral scale of a time series by integrating up to
the first zero crossing.
"""
tau, rho = autocorr_coeff(u, t, tau1, tau2)
zero_cross_ind = np.where(np.diff(np.sign(rho)))[0][0]
int_scale = np.trapz(rho[:zero_cross_ind], tau[:zero_cross_ind])
return int_scale | [
"def",
"integral_scale",
"(",
"u",
",",
"t",
",",
"tau1",
"=",
"0.0",
",",
"tau2",
"=",
"1.0",
")",
":",
"tau",
",",
"rho",
"=",
"autocorr_coeff",
"(",
"u",
",",
"t",
",",
"tau1",
",",
"tau2",
")",
"zero_cross_ind",
"=",
"np",
".",
"where",
"(",
... | Calculate the integral scale of a time series by integrating up to
the first zero crossing. | [
"Calculate",
"the",
"integral",
"scale",
"of",
"a",
"time",
"series",
"by",
"integrating",
"up",
"to",
"the",
"first",
"zero",
"crossing",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L146-L153 |
petebachant/PXL | pxl/timeseries.py | combine_std | def combine_std(n, mean, std):
"""Compute combined standard deviation for subsets.
See https://stats.stackexchange.com/questions/43159/\
how-to-calculate-pooled-variance-of-two-groups-given-known-group-variances-\
mean for derivation.
Parameters
----------
n : numpy array of sample sizes
mean : numpy array of sample means
std : numpy array of sample standard deviations
"""
# Calculate weighted mean
mean_tot = np.sum(n*mean)/np.sum(n)
var_tot = np.sum(n*(std**2 + mean**2))/np.sum(n) - mean_tot**2
return np.sqrt(var_tot) | python | def combine_std(n, mean, std):
"""Compute combined standard deviation for subsets.
See https://stats.stackexchange.com/questions/43159/\
how-to-calculate-pooled-variance-of-two-groups-given-known-group-variances-\
mean for derivation.
Parameters
----------
n : numpy array of sample sizes
mean : numpy array of sample means
std : numpy array of sample standard deviations
"""
# Calculate weighted mean
mean_tot = np.sum(n*mean)/np.sum(n)
var_tot = np.sum(n*(std**2 + mean**2))/np.sum(n) - mean_tot**2
return np.sqrt(var_tot) | [
"def",
"combine_std",
"(",
"n",
",",
"mean",
",",
"std",
")",
":",
"# Calculate weighted mean\r",
"mean_tot",
"=",
"np",
".",
"sum",
"(",
"n",
"*",
"mean",
")",
"/",
"np",
".",
"sum",
"(",
"n",
")",
"var_tot",
"=",
"np",
".",
"sum",
"(",
"n",
"*"... | Compute combined standard deviation for subsets.
See https://stats.stackexchange.com/questions/43159/\
how-to-calculate-pooled-variance-of-two-groups-given-known-group-variances-\
mean for derivation.
Parameters
----------
n : numpy array of sample sizes
mean : numpy array of sample means
std : numpy array of sample standard deviations | [
"Compute",
"combined",
"standard",
"deviation",
"for",
"subsets",
".",
"See",
"https",
":",
"//",
"stats",
".",
"stackexchange",
".",
"com",
"/",
"questions",
"/",
"43159",
"/",
"\\",
"how",
"-",
"to",
"-",
"calculate",
"-",
"pooled",
"-",
"variance",
"-... | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L156-L172 |
petebachant/PXL | pxl/timeseries.py | calc_multi_exp_unc | def calc_multi_exp_unc(sys_unc, n, mean, std, dof, confidence=0.95):
"""Calculate expanded uncertainty using values from multiple runs.
Note that this function assumes the statistic is a mean value, therefore
the combined standard deviation is divided by `sqrt(N)`.
Parameters
----------
sys_unc : numpy array of systematic uncertainties
n : numpy array of numbers of samples per set
std : numpy array of sample standard deviations
dof : numpy array of degrees of freedom
confidence : Confidence interval for t-statistic
"""
sys_unc = sys_unc.mean()
std_combined = combine_std(n, mean, std)
std_combined /= np.sqrt(n.sum())
std_unc_combined = np.sqrt(std_combined**2 + sys_unc**2)
dof = dof.sum()
t_combined = scipy.stats.t.interval(alpha=confidence, df=dof)[-1]
exp_unc_combined = t_combined*std_unc_combined
return exp_unc_combined | python | def calc_multi_exp_unc(sys_unc, n, mean, std, dof, confidence=0.95):
"""Calculate expanded uncertainty using values from multiple runs.
Note that this function assumes the statistic is a mean value, therefore
the combined standard deviation is divided by `sqrt(N)`.
Parameters
----------
sys_unc : numpy array of systematic uncertainties
n : numpy array of numbers of samples per set
std : numpy array of sample standard deviations
dof : numpy array of degrees of freedom
confidence : Confidence interval for t-statistic
"""
sys_unc = sys_unc.mean()
std_combined = combine_std(n, mean, std)
std_combined /= np.sqrt(n.sum())
std_unc_combined = np.sqrt(std_combined**2 + sys_unc**2)
dof = dof.sum()
t_combined = scipy.stats.t.interval(alpha=confidence, df=dof)[-1]
exp_unc_combined = t_combined*std_unc_combined
return exp_unc_combined | [
"def",
"calc_multi_exp_unc",
"(",
"sys_unc",
",",
"n",
",",
"mean",
",",
"std",
",",
"dof",
",",
"confidence",
"=",
"0.95",
")",
":",
"sys_unc",
"=",
"sys_unc",
".",
"mean",
"(",
")",
"std_combined",
"=",
"combine_std",
"(",
"n",
",",
"mean",
",",
"s... | Calculate expanded uncertainty using values from multiple runs.
Note that this function assumes the statistic is a mean value, therefore
the combined standard deviation is divided by `sqrt(N)`.
Parameters
----------
sys_unc : numpy array of systematic uncertainties
n : numpy array of numbers of samples per set
std : numpy array of sample standard deviations
dof : numpy array of degrees of freedom
confidence : Confidence interval for t-statistic | [
"Calculate",
"expanded",
"uncertainty",
"using",
"values",
"from",
"multiple",
"runs",
".",
"Note",
"that",
"this",
"function",
"assumes",
"the",
"statistic",
"is",
"a",
"mean",
"value",
"therefore",
"the",
"combined",
"standard",
"deviation",
"is",
"divided",
"... | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L175-L196 |
petebachant/PXL | pxl/timeseries.py | student_t | def student_t(degrees_of_freedom, confidence=0.95):
"""Return Student-t statistic for given DOF and confidence interval."""
return scipy.stats.t.interval(alpha=confidence,
df=degrees_of_freedom)[-1] | python | def student_t(degrees_of_freedom, confidence=0.95):
"""Return Student-t statistic for given DOF and confidence interval."""
return scipy.stats.t.interval(alpha=confidence,
df=degrees_of_freedom)[-1] | [
"def",
"student_t",
"(",
"degrees_of_freedom",
",",
"confidence",
"=",
"0.95",
")",
":",
"return",
"scipy",
".",
"stats",
".",
"t",
".",
"interval",
"(",
"alpha",
"=",
"confidence",
",",
"df",
"=",
"degrees_of_freedom",
")",
"[",
"-",
"1",
"]"
] | Return Student-t statistic for given DOF and confidence interval. | [
"Return",
"Student",
"-",
"t",
"statistic",
"for",
"given",
"DOF",
"and",
"confidence",
"interval",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L199-L202 |
petebachant/PXL | pxl/timeseries.py | calc_uncertainty | def calc_uncertainty(quantity, sys_unc, mean=True):
"""Calculate the combined standard uncertainty of a quantity."""
n = len(quantity)
std = np.nanstd(quantity)
if mean:
std /= np.sqrt(n)
return np.sqrt(std**2 + sys_unc**2) | python | def calc_uncertainty(quantity, sys_unc, mean=True):
"""Calculate the combined standard uncertainty of a quantity."""
n = len(quantity)
std = np.nanstd(quantity)
if mean:
std /= np.sqrt(n)
return np.sqrt(std**2 + sys_unc**2) | [
"def",
"calc_uncertainty",
"(",
"quantity",
",",
"sys_unc",
",",
"mean",
"=",
"True",
")",
":",
"n",
"=",
"len",
"(",
"quantity",
")",
"std",
"=",
"np",
".",
"nanstd",
"(",
"quantity",
")",
"if",
"mean",
":",
"std",
"/=",
"np",
".",
"sqrt",
"(",
... | Calculate the combined standard uncertainty of a quantity. | [
"Calculate",
"the",
"combined",
"standard",
"uncertainty",
"of",
"a",
"quantity",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L205-L211 |
petebachant/PXL | pxl/timeseries.py | calc_exp_uncertainty | def calc_exp_uncertainty(n, std, combined_unc, sys_unc, rel_unc=0.25,
confidence=0.95, mean=True):
"""Calculate expanded uncertainty.
Parameters
----------
n : Number of independent samples
std : Sample standard deviation
sys_unc : Systematic uncertainty (b in Coleman and Steele)
rel_unc : Relative uncertainty of each systematic error source (guess 0.25)
confidence : Confidence interval (0, 1)
mean : bool whether or not the quantity is a mean value
Returns
-------
exp_unc : Expanded uncertainty
nu_x : Degrees of freedom
"""
s_x = std
if mean:
s_x /= np.sqrt(n)
nu_s_x = n - 1
b = sys_unc
nu_b = 0.5*rel_unc**(-2)
nu_x = ((s_x**2 + b**2)**2)/(s_x**4/nu_s_x + b**4/nu_b)
t = scipy.stats.t.interval(alpha=0.95, df=nu_x)[-1]
exp_unc = t*combined_unc
return exp_unc, nu_x | python | def calc_exp_uncertainty(n, std, combined_unc, sys_unc, rel_unc=0.25,
confidence=0.95, mean=True):
"""Calculate expanded uncertainty.
Parameters
----------
n : Number of independent samples
std : Sample standard deviation
sys_unc : Systematic uncertainty (b in Coleman and Steele)
rel_unc : Relative uncertainty of each systematic error source (guess 0.25)
confidence : Confidence interval (0, 1)
mean : bool whether or not the quantity is a mean value
Returns
-------
exp_unc : Expanded uncertainty
nu_x : Degrees of freedom
"""
s_x = std
if mean:
s_x /= np.sqrt(n)
nu_s_x = n - 1
b = sys_unc
nu_b = 0.5*rel_unc**(-2)
nu_x = ((s_x**2 + b**2)**2)/(s_x**4/nu_s_x + b**4/nu_b)
t = scipy.stats.t.interval(alpha=0.95, df=nu_x)[-1]
exp_unc = t*combined_unc
return exp_unc, nu_x | [
"def",
"calc_exp_uncertainty",
"(",
"n",
",",
"std",
",",
"combined_unc",
",",
"sys_unc",
",",
"rel_unc",
"=",
"0.25",
",",
"confidence",
"=",
"0.95",
",",
"mean",
"=",
"True",
")",
":",
"s_x",
"=",
"std",
"if",
"mean",
":",
"s_x",
"/=",
"np",
".",
... | Calculate expanded uncertainty.
Parameters
----------
n : Number of independent samples
std : Sample standard deviation
sys_unc : Systematic uncertainty (b in Coleman and Steele)
rel_unc : Relative uncertainty of each systematic error source (guess 0.25)
confidence : Confidence interval (0, 1)
mean : bool whether or not the quantity is a mean value
Returns
-------
exp_unc : Expanded uncertainty
nu_x : Degrees of freedom | [
"Calculate",
"expanded",
"uncertainty",
".",
"Parameters",
"----------",
"n",
":",
"Number",
"of",
"independent",
"samples",
"std",
":",
"Sample",
"standard",
"deviation",
"sys_unc",
":",
"Systematic",
"uncertainty",
"(",
"b",
"in",
"Coleman",
"and",
"Steele",
"... | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L214-L241 |
petebachant/PXL | pxl/timeseries.py | find_amp_phase | def find_amp_phase(angle, data, npeaks=3, min_amp=None, min_phase=None):
"""Estimate amplitude and phase of an approximately sinusoidal quantity
using `scipy.optimize.curve_fit`.
Phase is defined as the angle at which the cosine curve fit reaches its
first peak. It is assumed that phase is positive. For example:
data_fit = amp*np.cos(npeaks*(angle - phase)) + mean_data
Parameters
----------
angle : numpy array
Time series of angle values in radians
data : numpy array
Time series of data to be fit
npeaks : int
Number of peaks per revolution, or normalized frequency
min_phase : float
Minimum phase to allow for guess to least squares fit
Returns
-------
amp : float
Amplitude of regressed cosine
phase : float
Angle of the first peak in radians
"""
# First subtract the mean of the data
data = data - data.mean()
# Make some guesses for parameters from a subset of data starting at an
# integer multiple of periods
if angle[0] != 0.0:
angle1 = angle[0] + (2*np.pi/npeaks - (2*np.pi/npeaks) % angle[0])
else:
angle1 = angle[0]
angle1 += min_phase
angle2 = angle1 + 2*np.pi/npeaks
ind = np.logical_and(angle >= angle1, angle <= angle2)
angle_sub = angle[ind]
data_sub = data[ind]
amp_guess = (data_sub.max() - data_sub.min())/2
phase_guess = angle[np.where(data_sub == data_sub.max())[0][0]] \
% (np.pi*2/npeaks)
# Define the function we will try to fit to
def func(angle, amp, phase, mean):
return amp*np.cos(npeaks*(angle - phase)) + mean
# Calculate fit
p0 = amp_guess, phase_guess, 0.0
popt, pcov = curve_fit(func, angle, data, p0=p0)
amp, phase, mean = popt
return amp, phase | python | def find_amp_phase(angle, data, npeaks=3, min_amp=None, min_phase=None):
"""Estimate amplitude and phase of an approximately sinusoidal quantity
using `scipy.optimize.curve_fit`.
Phase is defined as the angle at which the cosine curve fit reaches its
first peak. It is assumed that phase is positive. For example:
data_fit = amp*np.cos(npeaks*(angle - phase)) + mean_data
Parameters
----------
angle : numpy array
Time series of angle values in radians
data : numpy array
Time series of data to be fit
npeaks : int
Number of peaks per revolution, or normalized frequency
min_phase : float
Minimum phase to allow for guess to least squares fit
Returns
-------
amp : float
Amplitude of regressed cosine
phase : float
Angle of the first peak in radians
"""
# First subtract the mean of the data
data = data - data.mean()
# Make some guesses for parameters from a subset of data starting at an
# integer multiple of periods
if angle[0] != 0.0:
angle1 = angle[0] + (2*np.pi/npeaks - (2*np.pi/npeaks) % angle[0])
else:
angle1 = angle[0]
angle1 += min_phase
angle2 = angle1 + 2*np.pi/npeaks
ind = np.logical_and(angle >= angle1, angle <= angle2)
angle_sub = angle[ind]
data_sub = data[ind]
amp_guess = (data_sub.max() - data_sub.min())/2
phase_guess = angle[np.where(data_sub == data_sub.max())[0][0]] \
% (np.pi*2/npeaks)
# Define the function we will try to fit to
def func(angle, amp, phase, mean):
return amp*np.cos(npeaks*(angle - phase)) + mean
# Calculate fit
p0 = amp_guess, phase_guess, 0.0
popt, pcov = curve_fit(func, angle, data, p0=p0)
amp, phase, mean = popt
return amp, phase | [
"def",
"find_amp_phase",
"(",
"angle",
",",
"data",
",",
"npeaks",
"=",
"3",
",",
"min_amp",
"=",
"None",
",",
"min_phase",
"=",
"None",
")",
":",
"# First subtract the mean of the data\r",
"data",
"=",
"data",
"-",
"data",
".",
"mean",
"(",
")",
"# Make s... | Estimate amplitude and phase of an approximately sinusoidal quantity
using `scipy.optimize.curve_fit`.
Phase is defined as the angle at which the cosine curve fit reaches its
first peak. It is assumed that phase is positive. For example:
data_fit = amp*np.cos(npeaks*(angle - phase)) + mean_data
Parameters
----------
angle : numpy array
Time series of angle values in radians
data : numpy array
Time series of data to be fit
npeaks : int
Number of peaks per revolution, or normalized frequency
min_phase : float
Minimum phase to allow for guess to least squares fit
Returns
-------
amp : float
Amplitude of regressed cosine
phase : float
Angle of the first peak in radians | [
"Estimate",
"amplitude",
"and",
"phase",
"of",
"an",
"approximately",
"sinusoidal",
"quantity",
"using",
"scipy",
".",
"optimize",
".",
"curve_fit",
".",
"Phase",
"is",
"defined",
"as",
"the",
"angle",
"at",
"which",
"the",
"cosine",
"curve",
"fit",
"reaches",... | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/timeseries.py#L244-L294 |
ShawnClake/Apitax | apitax/ah/api/controllers/migrations/developers_controller.py | create_script | def create_script(create=None): # noqa: E501
"""Create a new script
Create a new script # noqa: E501
:param create: The data needed to create this script
:type create: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
create = Create.from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!' | python | def create_script(create=None): # noqa: E501
"""Create a new script
Create a new script # noqa: E501
:param create: The data needed to create this script
:type create: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
create = Create.from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!' | [
"def",
"create_script",
"(",
"create",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"create",
"=",
"Create",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501... | Create a new script
Create a new script # noqa: E501
:param create: The data needed to create this script
:type create: dict | bytes
:rtype: Response | [
"Create",
"a",
"new",
"script"
] | train | https://github.com/ShawnClake/Apitax/blob/2eb9c6990d4088b2503c7f13c2a76f8e59606e6d/apitax/ah/api/controllers/migrations/developers_controller.py#L13-L25 |
ShawnClake/Apitax | apitax/ah/api/controllers/migrations/developers_controller.py | delete_script | def delete_script(delete=None): # noqa: E501
"""Delete a script
Delete a script # noqa: E501
:param delete: The data needed to delete this script
:type delete: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
delete = Delete.from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!' | python | def delete_script(delete=None): # noqa: E501
"""Delete a script
Delete a script # noqa: E501
:param delete: The data needed to delete this script
:type delete: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
delete = Delete.from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!' | [
"def",
"delete_script",
"(",
"delete",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"delete",
"=",
"Delete",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501... | Delete a script
Delete a script # noqa: E501
:param delete: The data needed to delete this script
:type delete: dict | bytes
:rtype: Response | [
"Delete",
"a",
"script"
] | train | https://github.com/ShawnClake/Apitax/blob/2eb9c6990d4088b2503c7f13c2a76f8e59606e6d/apitax/ah/api/controllers/migrations/developers_controller.py#L28-L40 |
ShawnClake/Apitax | apitax/ah/api/controllers/migrations/developers_controller.py | rename_script | def rename_script(rename=None): # noqa: E501
"""Rename a script
Rename a script # noqa: E501
:param rename: The data needed to save this script
:type rename: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
rename = Rename.from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!' | python | def rename_script(rename=None): # noqa: E501
"""Rename a script
Rename a script # noqa: E501
:param rename: The data needed to save this script
:type rename: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
rename = Rename.from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!' | [
"def",
"rename_script",
"(",
"rename",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"rename",
"=",
"Rename",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501... | Rename a script
Rename a script # noqa: E501
:param rename: The data needed to save this script
:type rename: dict | bytes
:rtype: Response | [
"Rename",
"a",
"script"
] | train | https://github.com/ShawnClake/Apitax/blob/2eb9c6990d4088b2503c7f13c2a76f8e59606e6d/apitax/ah/api/controllers/migrations/developers_controller.py#L54-L66 |
ShawnClake/Apitax | apitax/ah/api/controllers/migrations/developers_controller.py | save_script | def save_script(save=None): # noqa: E501
"""Save a script
Save a script # noqa: E501
:param save: The data needed to save this script
:type save: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
save = Save.from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!' | python | def save_script(save=None): # noqa: E501
"""Save a script
Save a script # noqa: E501
:param save: The data needed to save this script
:type save: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
save = Save.from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!' | [
"def",
"save_script",
"(",
"save",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"save",
"=",
"Save",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501",
"re... | Save a script
Save a script # noqa: E501
:param save: The data needed to save this script
:type save: dict | bytes
:rtype: Response | [
"Save",
"a",
"script"
] | train | https://github.com/ShawnClake/Apitax/blob/2eb9c6990d4088b2503c7f13c2a76f8e59606e6d/apitax/ah/api/controllers/migrations/developers_controller.py#L69-L81 |
mgaitan/mts | mts/cli.py | get_numbers | def get_numbers(s):
"""Extracts all integers from a string an return them in a list"""
result = map(int, re.findall(r'[0-9]+', unicode(s)))
return result + [1] * (2 - len(result)) | python | def get_numbers(s):
"""Extracts all integers from a string an return them in a list"""
result = map(int, re.findall(r'[0-9]+', unicode(s)))
return result + [1] * (2 - len(result)) | [
"def",
"get_numbers",
"(",
"s",
")",
":",
"result",
"=",
"map",
"(",
"int",
",",
"re",
".",
"findall",
"(",
"r'[0-9]+'",
",",
"unicode",
"(",
"s",
")",
")",
")",
"return",
"result",
"+",
"[",
"1",
"]",
"*",
"(",
"2",
"-",
"len",
"(",
"result",
... | Extracts all integers from a string an return them in a list | [
"Extracts",
"all",
"integers",
"from",
"a",
"string",
"an",
"return",
"them",
"in",
"a",
"list"
] | train | https://github.com/mgaitan/mts/blob/bb018e987d4d6c10babb4627f117c894d0dd4c35/mts/cli.py#L42-L46 |
Gr1N/copypaste | copypaste/win.py | copy | def copy(string):
"""Copy given string into system clipboard.
"""
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(string)
win32clipboard.CloseClipboard() | python | def copy(string):
"""Copy given string into system clipboard.
"""
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(string)
win32clipboard.CloseClipboard() | [
"def",
"copy",
"(",
"string",
")",
":",
"win32clipboard",
".",
"OpenClipboard",
"(",
")",
"win32clipboard",
".",
"EmptyClipboard",
"(",
")",
"win32clipboard",
".",
"SetClipboardText",
"(",
"string",
")",
"win32clipboard",
".",
"CloseClipboard",
"(",
")"
] | Copy given string into system clipboard. | [
"Copy",
"given",
"string",
"into",
"system",
"clipboard",
"."
] | train | https://github.com/Gr1N/copypaste/blob/7d515d1d31db5ae686378b60e4c8717d7f6834de/copypaste/win.py#L14-L20 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Neo4jGraph.addVertex | def addVertex(self, _id=None):
"""Add param declared for compability with the API. Neo4j
creates the id automatically
@params _id: Node unique identifier
@returns The created Vertex or None"""
node = self.neograph.nodes.create(_id=_id)
return Vertex(node) | python | def addVertex(self, _id=None):
"""Add param declared for compability with the API. Neo4j
creates the id automatically
@params _id: Node unique identifier
@returns The created Vertex or None"""
node = self.neograph.nodes.create(_id=_id)
return Vertex(node) | [
"def",
"addVertex",
"(",
"self",
",",
"_id",
"=",
"None",
")",
":",
"node",
"=",
"self",
".",
"neograph",
".",
"nodes",
".",
"create",
"(",
"_id",
"=",
"_id",
")",
"return",
"Vertex",
"(",
"node",
")"
] | Add param declared for compability with the API. Neo4j
creates the id automatically
@params _id: Node unique identifier
@returns The created Vertex or None | [
"Add",
"param",
"declared",
"for",
"compability",
"with",
"the",
"API",
".",
"Neo4j",
"creates",
"the",
"id",
"automatically",
"@params",
"_id",
":",
"Node",
"unique",
"identifier"
] | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L33-L40 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Neo4jGraph.getVertex | def getVertex(self, _id):
"""Retrieves an existing vertex from the graph
@params _id: Node unique identifier
@returns The requested Vertex or None"""
try:
node = self.neograph.nodes.get(_id)
except client.NotFoundError:
return None
return Vertex(node) | python | def getVertex(self, _id):
"""Retrieves an existing vertex from the graph
@params _id: Node unique identifier
@returns The requested Vertex or None"""
try:
node = self.neograph.nodes.get(_id)
except client.NotFoundError:
return None
return Vertex(node) | [
"def",
"getVertex",
"(",
"self",
",",
"_id",
")",
":",
"try",
":",
"node",
"=",
"self",
".",
"neograph",
".",
"nodes",
".",
"get",
"(",
"_id",
")",
"except",
"client",
".",
"NotFoundError",
":",
"return",
"None",
"return",
"Vertex",
"(",
"node",
")"
... | Retrieves an existing vertex from the graph
@params _id: Node unique identifier
@returns The requested Vertex or None | [
"Retrieves",
"an",
"existing",
"vertex",
"from",
"the",
"graph",
"@params",
"_id",
":",
"Node",
"unique",
"identifier"
] | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L42-L51 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Neo4jGraph.addEdge | def addEdge(self, outVertex, inVertex, label):
"""Creates a new edge
@params outVertex: Edge origin Vertex
@params inVertex: Edge target vertex
@params label: Edge label
@returns The created Edge object"""
n1 = outVertex.neoelement
n2 = inVertex.neoelement
edge = n1.relationships.create(label, n2)
return Edge(edge) | python | def addEdge(self, outVertex, inVertex, label):
"""Creates a new edge
@params outVertex: Edge origin Vertex
@params inVertex: Edge target vertex
@params label: Edge label
@returns The created Edge object"""
n1 = outVertex.neoelement
n2 = inVertex.neoelement
edge = n1.relationships.create(label, n2)
return Edge(edge) | [
"def",
"addEdge",
"(",
"self",
",",
"outVertex",
",",
"inVertex",
",",
"label",
")",
":",
"n1",
"=",
"outVertex",
".",
"neoelement",
"n2",
"=",
"inVertex",
".",
"neoelement",
"edge",
"=",
"n1",
".",
"relationships",
".",
"create",
"(",
"label",
",",
"n... | Creates a new edge
@params outVertex: Edge origin Vertex
@params inVertex: Edge target vertex
@params label: Edge label
@returns The created Edge object | [
"Creates",
"a",
"new",
"edge",
"@params",
"outVertex",
":",
"Edge",
"origin",
"Vertex",
"@params",
"inVertex",
":",
"Edge",
"target",
"vertex",
"@params",
"label",
":",
"Edge",
"label"
] | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L62-L72 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Neo4jGraph.getEdge | def getEdge(self, _id):
"""Retrieves an existing edge from the graph
@params _id: Edge unique identifier
@returns The requested Edge or None"""
try:
edge = self.neograph.relationships.get(_id)
except client.NotFoundError:
return None
return Edge(edge) | python | def getEdge(self, _id):
"""Retrieves an existing edge from the graph
@params _id: Edge unique identifier
@returns The requested Edge or None"""
try:
edge = self.neograph.relationships.get(_id)
except client.NotFoundError:
return None
return Edge(edge) | [
"def",
"getEdge",
"(",
"self",
",",
"_id",
")",
":",
"try",
":",
"edge",
"=",
"self",
".",
"neograph",
".",
"relationships",
".",
"get",
"(",
"_id",
")",
"except",
"client",
".",
"NotFoundError",
":",
"return",
"None",
"return",
"Edge",
"(",
"edge",
... | Retrieves an existing edge from the graph
@params _id: Edge unique identifier
@returns The requested Edge or None | [
"Retrieves",
"an",
"existing",
"edge",
"from",
"the",
"graph",
"@params",
"_id",
":",
"Edge",
"unique",
"identifier"
] | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L74-L83 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Vertex.getOutEdges | def getOutEdges(self, label=None):
"""Gets all the outgoing edges of the node. If label
parameter is provided, it only returns the edges of
the given label
@params label: Optional parameter to filter the edges
@returns A generator function with the outgoing edges"""
if label:
for edge in self.neoelement.relationships.outgoing(types=[label]):
yield Edge(edge)
else:
for edge in self.neoelement.relationships.outgoing():
yield Edge(edge) | python | def getOutEdges(self, label=None):
"""Gets all the outgoing edges of the node. If label
parameter is provided, it only returns the edges of
the given label
@params label: Optional parameter to filter the edges
@returns A generator function with the outgoing edges"""
if label:
for edge in self.neoelement.relationships.outgoing(types=[label]):
yield Edge(edge)
else:
for edge in self.neoelement.relationships.outgoing():
yield Edge(edge) | [
"def",
"getOutEdges",
"(",
"self",
",",
"label",
"=",
"None",
")",
":",
"if",
"label",
":",
"for",
"edge",
"in",
"self",
".",
"neoelement",
".",
"relationships",
".",
"outgoing",
"(",
"types",
"=",
"[",
"label",
"]",
")",
":",
"yield",
"Edge",
"(",
... | Gets all the outgoing edges of the node. If label
parameter is provided, it only returns the edges of
the given label
@params label: Optional parameter to filter the edges
@returns A generator function with the outgoing edges | [
"Gets",
"all",
"the",
"outgoing",
"edges",
"of",
"the",
"node",
".",
"If",
"label",
"parameter",
"is",
"provided",
"it",
"only",
"returns",
"the",
"edges",
"of",
"the",
"given",
"label",
"@params",
"label",
":",
"Optional",
"parameter",
"to",
"filter",
"th... | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L155-L167 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Vertex.getInEdges | def getInEdges(self, label=None):
"""Gets all the incoming edges of the node. If label
parameter is provided, it only returns the edges of
the given label
@params label: Optional parameter to filter the edges
@returns A generator function with the incoming edges"""
if label:
for edge in self.neoelement.relationships.incoming(types=[label]):
yield Edge(edge)
else:
for edge in self.neoelement.relationships.incoming():
yield Edge(edge) | python | def getInEdges(self, label=None):
"""Gets all the incoming edges of the node. If label
parameter is provided, it only returns the edges of
the given label
@params label: Optional parameter to filter the edges
@returns A generator function with the incoming edges"""
if label:
for edge in self.neoelement.relationships.incoming(types=[label]):
yield Edge(edge)
else:
for edge in self.neoelement.relationships.incoming():
yield Edge(edge) | [
"def",
"getInEdges",
"(",
"self",
",",
"label",
"=",
"None",
")",
":",
"if",
"label",
":",
"for",
"edge",
"in",
"self",
".",
"neoelement",
".",
"relationships",
".",
"incoming",
"(",
"types",
"=",
"[",
"label",
"]",
")",
":",
"yield",
"Edge",
"(",
... | Gets all the incoming edges of the node. If label
parameter is provided, it only returns the edges of
the given label
@params label: Optional parameter to filter the edges
@returns A generator function with the incoming edges | [
"Gets",
"all",
"the",
"incoming",
"edges",
"of",
"the",
"node",
".",
"If",
"label",
"parameter",
"is",
"provided",
"it",
"only",
"returns",
"the",
"edges",
"of",
"the",
"given",
"label",
"@params",
"label",
":",
"Optional",
"parameter",
"to",
"filter",
"th... | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L169-L181 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Vertex.getBothEdges | def getBothEdges(self, label=None):
"""Gets all the edges of the node. If label
parameter is provided, it only returns the edges of
the given label
@params label: Optional parameter to filter the edges
@returns A generator function with the incoming edges"""
if label:
for edge in self.neoelement.relationships.all(types=[label]):
yield Edge(edge)
else:
for edge in self.neoelement.relationships.all():
yield Edge(edge) | python | def getBothEdges(self, label=None):
"""Gets all the edges of the node. If label
parameter is provided, it only returns the edges of
the given label
@params label: Optional parameter to filter the edges
@returns A generator function with the incoming edges"""
if label:
for edge in self.neoelement.relationships.all(types=[label]):
yield Edge(edge)
else:
for edge in self.neoelement.relationships.all():
yield Edge(edge) | [
"def",
"getBothEdges",
"(",
"self",
",",
"label",
"=",
"None",
")",
":",
"if",
"label",
":",
"for",
"edge",
"in",
"self",
".",
"neoelement",
".",
"relationships",
".",
"all",
"(",
"types",
"=",
"[",
"label",
"]",
")",
":",
"yield",
"Edge",
"(",
"ed... | Gets all the edges of the node. If label
parameter is provided, it only returns the edges of
the given label
@params label: Optional parameter to filter the edges
@returns A generator function with the incoming edges | [
"Gets",
"all",
"the",
"edges",
"of",
"the",
"node",
".",
"If",
"label",
"parameter",
"is",
"provided",
"it",
"only",
"returns",
"the",
"edges",
"of",
"the",
"given",
"label",
"@params",
"label",
":",
"Optional",
"parameter",
"to",
"filter",
"the",
"edges"
... | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L183-L195 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Index.put | def put(self, key, value, element):
"""Puts an element in an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@params element: Vertex or Edge element to be indexed"""
self.neoindex[key][value] = element.neoelement | python | def put(self, key, value, element):
"""Puts an element in an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@params element: Vertex or Edge element to be indexed"""
self.neoindex[key][value] = element.neoelement | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
",",
"element",
")",
":",
"self",
".",
"neoindex",
"[",
"key",
"]",
"[",
"value",
"]",
"=",
"element",
".",
"neoelement"
] | Puts an element in an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@params element: Vertex or Edge element to be indexed | [
"Puts",
"an",
"element",
"in",
"an",
"index",
"under",
"a",
"given",
"key",
"-",
"value",
"pair"
] | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L276-L282 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Index.get | def get(self, key, value):
"""Gets an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@returns A generator of Vertex or Edge objects"""
for element in self.neoindex[key][value]:
if self.indexClass == "vertex":
yield Vertex(element)
elif self.indexClass == "edge":
yield Edge(element)
else:
raise TypeError(self.indexClass) | python | def get(self, key, value):
"""Gets an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@returns A generator of Vertex or Edge objects"""
for element in self.neoindex[key][value]:
if self.indexClass == "vertex":
yield Vertex(element)
elif self.indexClass == "edge":
yield Edge(element)
else:
raise TypeError(self.indexClass) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"for",
"element",
"in",
"self",
".",
"neoindex",
"[",
"key",
"]",
"[",
"value",
"]",
":",
"if",
"self",
".",
"indexClass",
"==",
"\"vertex\"",
":",
"yield",
"Vertex",
"(",
"element",
")... | Gets an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@returns A generator of Vertex or Edge objects | [
"Gets",
"an",
"element",
"from",
"an",
"index",
"under",
"a",
"given",
"key",
"-",
"value",
"pair"
] | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L284-L296 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Index.remove | def remove(self, key, value, element):
"""Removes an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@params element: Vertex or Edge element to be removed"""
self.neoindex.delete(key, value, element.neoelement) | python | def remove(self, key, value, element):
"""Removes an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@params element: Vertex or Edge element to be removed"""
self.neoindex.delete(key, value, element.neoelement) | [
"def",
"remove",
"(",
"self",
",",
"key",
",",
"value",
",",
"element",
")",
":",
"self",
".",
"neoindex",
".",
"delete",
"(",
"key",
",",
"value",
",",
"element",
".",
"neoelement",
")"
] | Removes an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@params element: Vertex or Edge element to be removed | [
"Removes",
"an",
"element",
"from",
"an",
"index",
"under",
"a",
"given",
"key",
"-",
"value",
"pair"
] | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L298-L304 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Neo4jIndexableGraph.createManualIndex | def createManualIndex(self, indexName, indexClass):
"""Creates an index manually managed
@params name: The index name
@params indexClass: vertex or edge
@returns The created Index"""
indexClass = str(indexClass).lower()
if indexClass == "vertex":
index = self.neograph.nodes.indexes.create(indexName)
elif indexClass == "edge":
index = self.neograph.relationships.indexes.create(indexName)
else:
NameError("Unknown Index Class %s" % indexClass)
return Index(indexName, indexClass, "manual", index) | python | def createManualIndex(self, indexName, indexClass):
"""Creates an index manually managed
@params name: The index name
@params indexClass: vertex or edge
@returns The created Index"""
indexClass = str(indexClass).lower()
if indexClass == "vertex":
index = self.neograph.nodes.indexes.create(indexName)
elif indexClass == "edge":
index = self.neograph.relationships.indexes.create(indexName)
else:
NameError("Unknown Index Class %s" % indexClass)
return Index(indexName, indexClass, "manual", index) | [
"def",
"createManualIndex",
"(",
"self",
",",
"indexName",
",",
"indexClass",
")",
":",
"indexClass",
"=",
"str",
"(",
"indexClass",
")",
".",
"lower",
"(",
")",
"if",
"indexClass",
"==",
"\"vertex\"",
":",
"index",
"=",
"self",
".",
"neograph",
".",
"no... | Creates an index manually managed
@params name: The index name
@params indexClass: vertex or edge
@returns The created Index | [
"Creates",
"an",
"index",
"manually",
"managed",
"@params",
"name",
":",
"The",
"index",
"name",
"@params",
"indexClass",
":",
"vertex",
"or",
"edge"
] | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L316-L329 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Neo4jIndexableGraph.getIndex | def getIndex(self, indexName, indexClass):
"""Retrieves an index with a given index name and class
@params indexName: The index name
@params indexClass: vertex or edge
@return The Index object or None"""
if indexClass == "vertex":
try:
return Index(indexName, indexClass, "manual",
self.neograph.nodes.indexes.get(indexName))
except client.NotFoundError:
return None
elif indexClass == "edge":
try:
return Index(indexName, indexClass, "manual",
self.neograph.relationships.indexes.get(indexName))
except client.NotFoundError:
return None
else:
raise KeyError("Unknown Index Class (%s). Use vertex or edge"\
% indexClass) | python | def getIndex(self, indexName, indexClass):
"""Retrieves an index with a given index name and class
@params indexName: The index name
@params indexClass: vertex or edge
@return The Index object or None"""
if indexClass == "vertex":
try:
return Index(indexName, indexClass, "manual",
self.neograph.nodes.indexes.get(indexName))
except client.NotFoundError:
return None
elif indexClass == "edge":
try:
return Index(indexName, indexClass, "manual",
self.neograph.relationships.indexes.get(indexName))
except client.NotFoundError:
return None
else:
raise KeyError("Unknown Index Class (%s). Use vertex or edge"\
% indexClass) | [
"def",
"getIndex",
"(",
"self",
",",
"indexName",
",",
"indexClass",
")",
":",
"if",
"indexClass",
"==",
"\"vertex\"",
":",
"try",
":",
"return",
"Index",
"(",
"indexName",
",",
"indexClass",
",",
"\"manual\"",
",",
"self",
".",
"neograph",
".",
"nodes",
... | Retrieves an index with a given index name and class
@params indexName: The index name
@params indexClass: vertex or edge
@return The Index object or None | [
"Retrieves",
"an",
"index",
"with",
"a",
"given",
"index",
"name",
"and",
"class",
"@params",
"indexName",
":",
"The",
"index",
"name",
"@params",
"indexClass",
":",
"vertex",
"or",
"edge"
] | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L339-L359 |
escalant3/pyblueprints | pyblueprints/neo4j.py | Neo4jIndexableGraph.getIndices | def getIndices(self):
"""Returns a generator function over all the existing indexes
@returns A generator function over all rhe Index objects"""
for indexName in self.neograph.nodes.indexes.keys():
indexObject = self.neograph.nodes.indexes.get(indexName)
yield Index(indexName, "vertex", "manual", indexObject)
for indexName in self.neograph.relationships.indexes.keys():
indexObject = self.neograph.relationships.indexes.get(indexName)
yield Index(indexName, "edge", "manual", indexObject) | python | def getIndices(self):
"""Returns a generator function over all the existing indexes
@returns A generator function over all rhe Index objects"""
for indexName in self.neograph.nodes.indexes.keys():
indexObject = self.neograph.nodes.indexes.get(indexName)
yield Index(indexName, "vertex", "manual", indexObject)
for indexName in self.neograph.relationships.indexes.keys():
indexObject = self.neograph.relationships.indexes.get(indexName)
yield Index(indexName, "edge", "manual", indexObject) | [
"def",
"getIndices",
"(",
"self",
")",
":",
"for",
"indexName",
"in",
"self",
".",
"neograph",
".",
"nodes",
".",
"indexes",
".",
"keys",
"(",
")",
":",
"indexObject",
"=",
"self",
".",
"neograph",
".",
"nodes",
".",
"indexes",
".",
"get",
"(",
"inde... | Returns a generator function over all the existing indexes
@returns A generator function over all rhe Index objects | [
"Returns",
"a",
"generator",
"function",
"over",
"all",
"the",
"existing",
"indexes"
] | train | https://github.com/escalant3/pyblueprints/blob/087b8caa5dc4946c671234f58b43024fd47c35d9/pyblueprints/neo4j.py#L361-L370 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/subversion.py | Subversion.get_info | def get_info(self, location):
"""Returns (url, revision), where both are strings"""
assert not location.rstrip('/').endswith(self.dirname), 'Bad directory: %s' % location
output = call_subprocess(
[self.cmd, 'info', location], show_stdout=False, extra_environ={'LANG': 'C'})
match = _svn_url_re.search(output)
if not match:
logger.warn('Cannot determine URL of svn checkout %s' % display_path(location))
logger.info('Output that cannot be parsed: \n%s' % output)
return None, None
url = match.group(1).strip()
match = _svn_revision_re.search(output)
if not match:
logger.warn('Cannot determine revision of svn checkout %s' % display_path(location))
logger.info('Output that cannot be parsed: \n%s' % output)
return url, None
return url, match.group(1) | python | def get_info(self, location):
"""Returns (url, revision), where both are strings"""
assert not location.rstrip('/').endswith(self.dirname), 'Bad directory: %s' % location
output = call_subprocess(
[self.cmd, 'info', location], show_stdout=False, extra_environ={'LANG': 'C'})
match = _svn_url_re.search(output)
if not match:
logger.warn('Cannot determine URL of svn checkout %s' % display_path(location))
logger.info('Output that cannot be parsed: \n%s' % output)
return None, None
url = match.group(1).strip()
match = _svn_revision_re.search(output)
if not match:
logger.warn('Cannot determine revision of svn checkout %s' % display_path(location))
logger.info('Output that cannot be parsed: \n%s' % output)
return url, None
return url, match.group(1) | [
"def",
"get_info",
"(",
"self",
",",
"location",
")",
":",
"assert",
"not",
"location",
".",
"rstrip",
"(",
"'/'",
")",
".",
"endswith",
"(",
"self",
".",
"dirname",
")",
",",
"'Bad directory: %s'",
"%",
"location",
"output",
"=",
"call_subprocess",
"(",
... | Returns (url, revision), where both are strings | [
"Returns",
"(",
"url",
"revision",
")",
"where",
"both",
"are",
"strings"
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/subversion.py#L24-L40 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/subversion.py | Subversion.export | def export(self, location):
"""Export the svn repository at the url to the destination location"""
url, rev = self.get_url_rev()
logger.notify('Exporting svn repository %s to %s' % (url, location))
logger.indent += 2
try:
if os.path.exists(location):
# Subversion doesn't like to check out over an existing directory
# --force fixes this, but was only added in svn 1.5
rmtree(location)
call_subprocess(
[self.cmd, 'export', url, location],
filter_stdout=self._filter, show_stdout=False)
finally:
logger.indent -= 2 | python | def export(self, location):
"""Export the svn repository at the url to the destination location"""
url, rev = self.get_url_rev()
logger.notify('Exporting svn repository %s to %s' % (url, location))
logger.indent += 2
try:
if os.path.exists(location):
# Subversion doesn't like to check out over an existing directory
# --force fixes this, but was only added in svn 1.5
rmtree(location)
call_subprocess(
[self.cmd, 'export', url, location],
filter_stdout=self._filter, show_stdout=False)
finally:
logger.indent -= 2 | [
"def",
"export",
"(",
"self",
",",
"location",
")",
":",
"url",
",",
"rev",
"=",
"self",
".",
"get_url_rev",
"(",
")",
"logger",
".",
"notify",
"(",
"'Exporting svn repository %s to %s'",
"%",
"(",
"url",
",",
"location",
")",
")",
"logger",
".",
"indent... | Export the svn repository at the url to the destination location | [
"Export",
"the",
"svn",
"repository",
"at",
"the",
"url",
"to",
"the",
"destination",
"location"
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/subversion.py#L54-L68 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/subversion.py | Subversion.get_revision | def get_revision(self, location):
"""
Return the maximum revision for all files under a given location
"""
# Note: taken from setuptools.command.egg_info
revision = 0
for base, dirs, files in os.walk(location):
if self.dirname not in dirs:
dirs[:] = []
continue # no sense walking uncontrolled subdirs
dirs.remove(self.dirname)
entries_fn = os.path.join(base, self.dirname, 'entries')
if not os.path.exists(entries_fn):
## FIXME: should we warn?
continue
f = open(entries_fn)
data = f.read()
f.close()
if data.startswith('8') or data.startswith('9') or data.startswith('10'):
data = list(map(str.splitlines, data.split('\n\x0c\n')))
del data[0][0] # get rid of the '8'
dirurl = data[0][3]
revs = [int(d[9]) for d in data if len(d)>9 and d[9]]+[0]
if revs:
localrev = max(revs)
else:
localrev = 0
elif data.startswith('<?xml'):
dirurl = _svn_xml_url_re.search(data).group(1) # get repository URL
revs = [int(m.group(1)) for m in _svn_rev_re.finditer(data)]+[0]
if revs:
localrev = max(revs)
else:
localrev = 0
else:
logger.warn("Unrecognized .svn/entries format; skipping %s", base)
dirs[:] = []
continue
if base == location:
base_url = dirurl+'/' # save the root url
elif not dirurl.startswith(base_url):
dirs[:] = []
continue # not part of the same svn tree, skip it
revision = max(revision, localrev)
return revision | python | def get_revision(self, location):
"""
Return the maximum revision for all files under a given location
"""
# Note: taken from setuptools.command.egg_info
revision = 0
for base, dirs, files in os.walk(location):
if self.dirname not in dirs:
dirs[:] = []
continue # no sense walking uncontrolled subdirs
dirs.remove(self.dirname)
entries_fn = os.path.join(base, self.dirname, 'entries')
if not os.path.exists(entries_fn):
## FIXME: should we warn?
continue
f = open(entries_fn)
data = f.read()
f.close()
if data.startswith('8') or data.startswith('9') or data.startswith('10'):
data = list(map(str.splitlines, data.split('\n\x0c\n')))
del data[0][0] # get rid of the '8'
dirurl = data[0][3]
revs = [int(d[9]) for d in data if len(d)>9 and d[9]]+[0]
if revs:
localrev = max(revs)
else:
localrev = 0
elif data.startswith('<?xml'):
dirurl = _svn_xml_url_re.search(data).group(1) # get repository URL
revs = [int(m.group(1)) for m in _svn_rev_re.finditer(data)]+[0]
if revs:
localrev = max(revs)
else:
localrev = 0
else:
logger.warn("Unrecognized .svn/entries format; skipping %s", base)
dirs[:] = []
continue
if base == location:
base_url = dirurl+'/' # save the root url
elif not dirurl.startswith(base_url):
dirs[:] = []
continue # not part of the same svn tree, skip it
revision = max(revision, localrev)
return revision | [
"def",
"get_revision",
"(",
"self",
",",
"location",
")",
":",
"# Note: taken from setuptools.command.egg_info",
"revision",
"=",
"0",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"location",
")",
":",
"if",
"self",
".",
"dirname",... | Return the maximum revision for all files under a given location | [
"Return",
"the",
"maximum",
"revision",
"for",
"all",
"files",
"under",
"a",
"given",
"location"
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/subversion.py#L106-L152 |
duniter/duniter-python-api | examples/request_data_async.py | main | async def main():
"""
Main code (asynchronous requests)
You can send one millions request with aiohttp :
https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html
But don't do that on one server, it's DDOS !
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
tasks = []
# Get the node summary infos by dedicated method (with json schema validation)
print("\nCall bma.node.summary:")
task = asyncio.ensure_future(client(bma.node.summary))
tasks.append(task)
# Get the money parameters located in the first block
print("\nCall bma.blockchain.parameters:")
task = asyncio.ensure_future(client(bma.blockchain.parameters))
tasks.append(task)
responses = await asyncio.gather(*tasks)
# you now have all response bodies in this variable
print("\nResponses:")
print(responses)
# Close client aiohttp session
await client.close() | python | async def main():
"""
Main code (asynchronous requests)
You can send one millions request with aiohttp :
https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html
But don't do that on one server, it's DDOS !
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
tasks = []
# Get the node summary infos by dedicated method (with json schema validation)
print("\nCall bma.node.summary:")
task = asyncio.ensure_future(client(bma.node.summary))
tasks.append(task)
# Get the money parameters located in the first block
print("\nCall bma.blockchain.parameters:")
task = asyncio.ensure_future(client(bma.blockchain.parameters))
tasks.append(task)
responses = await asyncio.gather(*tasks)
# you now have all response bodies in this variable
print("\nResponses:")
print(responses)
# Close client aiohttp session
await client.close() | [
"async",
"def",
"main",
"(",
")",
":",
"# Create Client from endpoint string in Duniter format",
"client",
"=",
"Client",
"(",
"BMAS_ENDPOINT",
")",
"tasks",
"=",
"[",
"]",
"# Get the node summary infos by dedicated method (with json schema validation)",
"print",
"(",
"\"\\nC... | Main code (asynchronous requests)
You can send one millions request with aiohttp :
https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html
But don't do that on one server, it's DDOS ! | [
"Main",
"code",
"(",
"asynchronous",
"requests",
")"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/request_data_async.py#L21-L52 |
dsandersAzure/python_digits | python_digits/DigitWord.py | DigitWord.word | def word(self):
"""Property of the DigitWord returning (or setting) the DigitWord as a list of integers (or
string representations) of DigitModel. The property is called during instantiation as the
property validates the value passed and ensures that all digits are valid."""
if self.wordtype == DigitWord.DIGIT:
return self._word
else:
# Strip out '0x' from the string representation. Note, this could be replaced with the
# following code: str(hex(a))[2:] but is more obvious in the code below.
return [str(hex(a)).replace('0x', '') for a in self._word] | python | def word(self):
"""Property of the DigitWord returning (or setting) the DigitWord as a list of integers (or
string representations) of DigitModel. The property is called during instantiation as the
property validates the value passed and ensures that all digits are valid."""
if self.wordtype == DigitWord.DIGIT:
return self._word
else:
# Strip out '0x' from the string representation. Note, this could be replaced with the
# following code: str(hex(a))[2:] but is more obvious in the code below.
return [str(hex(a)).replace('0x', '') for a in self._word] | [
"def",
"word",
"(",
"self",
")",
":",
"if",
"self",
".",
"wordtype",
"==",
"DigitWord",
".",
"DIGIT",
":",
"return",
"self",
".",
"_word",
"else",
":",
"# Strip out '0x' from the string representation. Note, this could be replaced with the",
"# following code: str(hex(a))... | Property of the DigitWord returning (or setting) the DigitWord as a list of integers (or
string representations) of DigitModel. The property is called during instantiation as the
property validates the value passed and ensures that all digits are valid. | [
"Property",
"of",
"the",
"DigitWord",
"returning",
"(",
"or",
"setting",
")",
"the",
"DigitWord",
"as",
"a",
"list",
"of",
"integers",
"(",
"or",
"string",
"representations",
")",
"of",
"DigitModel",
".",
"The",
"property",
"is",
"called",
"during",
"instant... | train | https://github.com/dsandersAzure/python_digits/blob/a9b8bfffeaffd0638932193d0c6453c209696c8b/python_digits/DigitWord.py#L89-L99 |
dsandersAzure/python_digits | python_digits/DigitWord.py | DigitWord.word | def word(self, value):
"""Property of the DigitWord returning (or setting) the DigitWord as a list of integers (or
string representations) of DigitModel. The property is called during instantiation as the
property validates the value passed and ensures that all digits are valid. The values can
be passed as ANY iterable"""
self._validate_word(value=value)
_word = []
# Iterate the values passed.
for a in value:
# Check the value is an int or a string.
if not (isinstance(a, int) or isinstance(a, str) or isinstance(a, unicode)):
raise ValueError('DigitWords must be made from digits (strings or ints) '
'between 0 and 9 for decimal and 0 and 15 for hex')
# This convoluted check is caused by the remove of the unicode type in Python 3+
# If this is Python2.x, then we need to convert unicode to string, otherwise
# we leave it as is.
if sys.version_info[0] == 2 and isinstance(a, unicode):
_a = str(a)
else:
_a = a
# Create the correct type of Digit based on the wordtype of the DigitWord
if self.wordtype == DigitWord.DIGIT:
_digit = Digit(_a)
elif self.wordtype == DigitWord.HEXDIGIT:
_digit = HexDigit(_a)
else:
raise TypeError('The wordtype is not valid.')
_word.append(_digit)
self._word = _word | python | def word(self, value):
"""Property of the DigitWord returning (or setting) the DigitWord as a list of integers (or
string representations) of DigitModel. The property is called during instantiation as the
property validates the value passed and ensures that all digits are valid. The values can
be passed as ANY iterable"""
self._validate_word(value=value)
_word = []
# Iterate the values passed.
for a in value:
# Check the value is an int or a string.
if not (isinstance(a, int) or isinstance(a, str) or isinstance(a, unicode)):
raise ValueError('DigitWords must be made from digits (strings or ints) '
'between 0 and 9 for decimal and 0 and 15 for hex')
# This convoluted check is caused by the remove of the unicode type in Python 3+
# If this is Python2.x, then we need to convert unicode to string, otherwise
# we leave it as is.
if sys.version_info[0] == 2 and isinstance(a, unicode):
_a = str(a)
else:
_a = a
# Create the correct type of Digit based on the wordtype of the DigitWord
if self.wordtype == DigitWord.DIGIT:
_digit = Digit(_a)
elif self.wordtype == DigitWord.HEXDIGIT:
_digit = HexDigit(_a)
else:
raise TypeError('The wordtype is not valid.')
_word.append(_digit)
self._word = _word | [
"def",
"word",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_validate_word",
"(",
"value",
"=",
"value",
")",
"_word",
"=",
"[",
"]",
"# Iterate the values passed.",
"for",
"a",
"in",
"value",
":",
"# Check the value is an int or a string.",
"if",
"not",... | Property of the DigitWord returning (or setting) the DigitWord as a list of integers (or
string representations) of DigitModel. The property is called during instantiation as the
property validates the value passed and ensures that all digits are valid. The values can
be passed as ANY iterable | [
"Property",
"of",
"the",
"DigitWord",
"returning",
"(",
"or",
"setting",
")",
"the",
"DigitWord",
"as",
"a",
"list",
"of",
"integers",
"(",
"or",
"string",
"representations",
")",
"of",
"DigitModel",
".",
"The",
"property",
"is",
"called",
"during",
"instant... | train | https://github.com/dsandersAzure/python_digits/blob/a9b8bfffeaffd0638932193d0c6453c209696c8b/python_digits/DigitWord.py#L102-L137 |
dsandersAzure/python_digits | python_digits/DigitWord.py | DigitWord.load | def load(self, value):
"""Load the value of the DigitWord from a JSON representation of a list. The representation is
validated to be a string and the encoded data a list. The list is then validated to ensure each
digit is a valid digit"""
if not isinstance(value, str):
raise TypeError('Expected JSON string')
_value = json.loads(value)
self._validate_word(value=_value)
self.word = _value | python | def load(self, value):
"""Load the value of the DigitWord from a JSON representation of a list. The representation is
validated to be a string and the encoded data a list. The list is then validated to ensure each
digit is a valid digit"""
if not isinstance(value, str):
raise TypeError('Expected JSON string')
_value = json.loads(value)
self._validate_word(value=_value)
self.word = _value | [
"def",
"load",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Expected JSON string'",
")",
"_value",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"self",
".",
"_validate... | Load the value of the DigitWord from a JSON representation of a list. The representation is
validated to be a string and the encoded data a list. The list is then validated to ensure each
digit is a valid digit | [
"Load",
"the",
"value",
"of",
"the",
"DigitWord",
"from",
"a",
"JSON",
"representation",
"of",
"a",
"list",
".",
"The",
"representation",
"is",
"validated",
"to",
"be",
"a",
"string",
"and",
"the",
"encoded",
"data",
"a",
"list",
".",
"The",
"list",
"is"... | train | https://github.com/dsandersAzure/python_digits/blob/a9b8bfffeaffd0638932193d0c6453c209696c8b/python_digits/DigitWord.py#L155-L165 |
dsandersAzure/python_digits | python_digits/DigitWord.py | DigitWord.random | def random(self, length=4):
"""Method to randomize the DigitWord to a given length; for example obj.random(length=4) would
produce a DigitWord containing of four random Digits or HexDigits. The type of digit created
is set by the wordtype."""
if not isinstance(length, int):
raise TypeError('DigitWord can only be randomized by an integer length')
if self.wordtype == DigitWord.DIGIT:
self._word = [Digit(random.randint(0, 9)) for i in range(0, length)]
elif self.wordtype == DigitWord.HEXDIGIT:
self._word = [HexDigit(str(hex(random.randint(0, 15))).replace('0x',''))
for i in range(0, length)]
else:
raise TypeError('wordtype is invalid.') | python | def random(self, length=4):
"""Method to randomize the DigitWord to a given length; for example obj.random(length=4) would
produce a DigitWord containing of four random Digits or HexDigits. The type of digit created
is set by the wordtype."""
if not isinstance(length, int):
raise TypeError('DigitWord can only be randomized by an integer length')
if self.wordtype == DigitWord.DIGIT:
self._word = [Digit(random.randint(0, 9)) for i in range(0, length)]
elif self.wordtype == DigitWord.HEXDIGIT:
self._word = [HexDigit(str(hex(random.randint(0, 15))).replace('0x',''))
for i in range(0, length)]
else:
raise TypeError('wordtype is invalid.') | [
"def",
"random",
"(",
"self",
",",
"length",
"=",
"4",
")",
":",
"if",
"not",
"isinstance",
"(",
"length",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"'DigitWord can only be randomized by an integer length'",
")",
"if",
"self",
".",
"wordtype",
"==",
"... | Method to randomize the DigitWord to a given length; for example obj.random(length=4) would
produce a DigitWord containing of four random Digits or HexDigits. The type of digit created
is set by the wordtype. | [
"Method",
"to",
"randomize",
"the",
"DigitWord",
"to",
"a",
"given",
"length",
";",
"for",
"example",
"obj",
".",
"random",
"(",
"length",
"=",
"4",
")",
"would",
"produce",
"a",
"DigitWord",
"containing",
"of",
"four",
"random",
"Digits",
"or",
"HexDigits... | train | https://github.com/dsandersAzure/python_digits/blob/a9b8bfffeaffd0638932193d0c6453c209696c8b/python_digits/DigitWord.py#L167-L180 |
dsandersAzure/python_digits | python_digits/DigitWord.py | DigitWord.compare | def compare(self, other):
"""Compare the DigitWord with another DigitWord (other) and provided iterated analysis of the
matches (none or loose) and the occurrence (one or more) of each DigitEntry in both
DigitWords. The method returns a list of Comparison objects."""
self._validate_compare_parameters(other=other)
return_list = []
for idx, digit in enumerate(other):
dwa = DigitWordAnalysis(
index=idx,
digit=digit,
match=(digit == self._word[idx]),
in_word=(self._word.count(digit) > 0),
multiple=(self._word.count(digit) > 1)
)
return_list.append(dwa)
return return_list | python | def compare(self, other):
"""Compare the DigitWord with another DigitWord (other) and provided iterated analysis of the
matches (none or loose) and the occurrence (one or more) of each DigitEntry in both
DigitWords. The method returns a list of Comparison objects."""
self._validate_compare_parameters(other=other)
return_list = []
for idx, digit in enumerate(other):
dwa = DigitWordAnalysis(
index=idx,
digit=digit,
match=(digit == self._word[idx]),
in_word=(self._word.count(digit) > 0),
multiple=(self._word.count(digit) > 1)
)
return_list.append(dwa)
return return_list | [
"def",
"compare",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"_validate_compare_parameters",
"(",
"other",
"=",
"other",
")",
"return_list",
"=",
"[",
"]",
"for",
"idx",
",",
"digit",
"in",
"enumerate",
"(",
"other",
")",
":",
"dwa",
"=",
"Digit... | Compare the DigitWord with another DigitWord (other) and provided iterated analysis of the
matches (none or loose) and the occurrence (one or more) of each DigitEntry in both
DigitWords. The method returns a list of Comparison objects. | [
"Compare",
"the",
"DigitWord",
"with",
"another",
"DigitWord",
"(",
"other",
")",
"and",
"provided",
"iterated",
"analysis",
"of",
"the",
"matches",
"(",
"none",
"or",
"loose",
")",
"and",
"the",
"occurrence",
"(",
"one",
"or",
"more",
")",
"of",
"each",
... | train | https://github.com/dsandersAzure/python_digits/blob/a9b8bfffeaffd0638932193d0c6453c209696c8b/python_digits/DigitWord.py#L182-L200 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/commands/install.py | InstallCommand._build_package_finder | def _build_package_finder(self, options, index_urls):
"""
Create a package finder appropriate to this install command.
This method is meant to be overridden by subclasses, not
called directly.
"""
return PackageFinder(find_links=options.find_links,
index_urls=index_urls,
use_mirrors=options.use_mirrors,
mirrors=options.mirrors) | python | def _build_package_finder(self, options, index_urls):
"""
Create a package finder appropriate to this install command.
This method is meant to be overridden by subclasses, not
called directly.
"""
return PackageFinder(find_links=options.find_links,
index_urls=index_urls,
use_mirrors=options.use_mirrors,
mirrors=options.mirrors) | [
"def",
"_build_package_finder",
"(",
"self",
",",
"options",
",",
"index_urls",
")",
":",
"return",
"PackageFinder",
"(",
"find_links",
"=",
"options",
".",
"find_links",
",",
"index_urls",
"=",
"index_urls",
",",
"use_mirrors",
"=",
"options",
".",
"use_mirrors... | Create a package finder appropriate to this install command.
This method is meant to be overridden by subclasses, not
called directly. | [
"Create",
"a",
"package",
"finder",
"appropriate",
"to",
"this",
"install",
"command",
".",
"This",
"method",
"is",
"meant",
"to",
"be",
"overridden",
"by",
"subclasses",
"not",
"called",
"directly",
"."
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/commands/install.py#L153-L162 |
etcher-be/epab | epab/linters/_sort.py | sort | def sort(amend: bool = False, stage: bool = False):
"""
Runs iSort (https://pypi.python.org/pypi/isort)
Args:
amend: whether or not to commit results
stage: whether or not to stage changes
"""
_sort(amend, stage) | python | def sort(amend: bool = False, stage: bool = False):
"""
Runs iSort (https://pypi.python.org/pypi/isort)
Args:
amend: whether or not to commit results
stage: whether or not to stage changes
"""
_sort(amend, stage) | [
"def",
"sort",
"(",
"amend",
":",
"bool",
"=",
"False",
",",
"stage",
":",
"bool",
"=",
"False",
")",
":",
"_sort",
"(",
"amend",
",",
"stage",
")"
] | Runs iSort (https://pypi.python.org/pypi/isort)
Args:
amend: whether or not to commit results
stage: whether or not to stage changes | [
"Runs",
"iSort",
"(",
"https",
":",
"//",
"pypi",
".",
"python",
".",
"org",
"/",
"pypi",
"/",
"isort",
")"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/linters/_sort.py#L57-L65 |
larryng/narwal | narwal/reddit.py | Reddit.get | def get(self, *args, **kwargs):
"""Sends a GET request to a reddit path determined by ``args``. Basically ``.get('foo', 'bar', 'baz')`` will GET http://www.reddit.com/foo/bar/baz/.json. ``kwargs`` supplied will be passed to :meth:`requests.get` after having ``user_agent`` and ``cookies`` injected. Injection only occurs if they don't already exist.
Returns :class:`things.Blob` object or a subclass of :class:`things.Blob`, or raises :class:`exceptions.BadResponse` if not a 200 Response.
:param \*args: strings that will form the path to GET
:param \*\*kwargs: extra keyword arguments to be passed to :meth:`requests.get`
"""
kwargs = self._inject_request_kwargs(kwargs)
url = reddit_url(*args)
r = requests.get(url, **kwargs)
# print r.url
if r.status_code == 200:
thing = self._thingify(json.loads(r.content), path=urlparse(r.url).path)
return thing
else:
raise BadResponse(r) | python | def get(self, *args, **kwargs):
"""Sends a GET request to a reddit path determined by ``args``. Basically ``.get('foo', 'bar', 'baz')`` will GET http://www.reddit.com/foo/bar/baz/.json. ``kwargs`` supplied will be passed to :meth:`requests.get` after having ``user_agent`` and ``cookies`` injected. Injection only occurs if they don't already exist.
Returns :class:`things.Blob` object or a subclass of :class:`things.Blob`, or raises :class:`exceptions.BadResponse` if not a 200 Response.
:param \*args: strings that will form the path to GET
:param \*\*kwargs: extra keyword arguments to be passed to :meth:`requests.get`
"""
kwargs = self._inject_request_kwargs(kwargs)
url = reddit_url(*args)
r = requests.get(url, **kwargs)
# print r.url
if r.status_code == 200:
thing = self._thingify(json.loads(r.content), path=urlparse(r.url).path)
return thing
else:
raise BadResponse(r) | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"self",
".",
"_inject_request_kwargs",
"(",
"kwargs",
")",
"url",
"=",
"reddit_url",
"(",
"*",
"args",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"url",... | Sends a GET request to a reddit path determined by ``args``. Basically ``.get('foo', 'bar', 'baz')`` will GET http://www.reddit.com/foo/bar/baz/.json. ``kwargs`` supplied will be passed to :meth:`requests.get` after having ``user_agent`` and ``cookies`` injected. Injection only occurs if they don't already exist.
Returns :class:`things.Blob` object or a subclass of :class:`things.Blob`, or raises :class:`exceptions.BadResponse` if not a 200 Response.
:param \*args: strings that will form the path to GET
:param \*\*kwargs: extra keyword arguments to be passed to :meth:`requests.get` | [
"Sends",
"a",
"GET",
"request",
"to",
"a",
"reddit",
"path",
"determined",
"by",
"args",
".",
"Basically",
".",
"get",
"(",
"foo",
"bar",
"baz",
")",
"will",
"GET",
"http",
":",
"//",
"www",
".",
"reddit",
".",
"com",
"/",
"foo",
"/",
"bar",
"/",
... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L127-L143 |
larryng/narwal | narwal/reddit.py | Reddit.post | def post(self, *args, **kwargs):
"""Sends a POST request to a reddit path determined by ``args``. Basically ``.post('foo', 'bar', 'baz')`` will POST http://www.reddit.com/foo/bar/baz/.json. ``kwargs`` supplied will be passed to ``requests.post`` after having ``modhash`` and ``cookies`` injected, and after having modhash injected into ``kwargs['data']`` if logged in. Injection only occurs if they don't already exist.
Returns received response JSON content as a dict.
Raises :class:`exceptions.BadResponse` if not a 200 response or no JSON content received or raises :class:`exceptions.PostError` if a reddit error was returned.
:param \*args: strings that will form the path to POST
:param \*\*kwargs: extra keyword arguments to be passed to ``requests.POST``
"""
kwargs = self._inject_request_kwargs(kwargs)
kwargs = self._inject_post_data(kwargs)
url = reddit_url(*args)
r = requests.post(url, **kwargs)
if r.status_code == 200:
try:
j = json.loads(r.content)
except ValueError:
raise BadResponse(r)
try:
errors = j['json']['errors']
except Exception:
errors = None
if errors:
raise PostError(errors)
else:
return j
else:
raise BadResponse(r) | python | def post(self, *args, **kwargs):
"""Sends a POST request to a reddit path determined by ``args``. Basically ``.post('foo', 'bar', 'baz')`` will POST http://www.reddit.com/foo/bar/baz/.json. ``kwargs`` supplied will be passed to ``requests.post`` after having ``modhash`` and ``cookies`` injected, and after having modhash injected into ``kwargs['data']`` if logged in. Injection only occurs if they don't already exist.
Returns received response JSON content as a dict.
Raises :class:`exceptions.BadResponse` if not a 200 response or no JSON content received or raises :class:`exceptions.PostError` if a reddit error was returned.
:param \*args: strings that will form the path to POST
:param \*\*kwargs: extra keyword arguments to be passed to ``requests.POST``
"""
kwargs = self._inject_request_kwargs(kwargs)
kwargs = self._inject_post_data(kwargs)
url = reddit_url(*args)
r = requests.post(url, **kwargs)
if r.status_code == 200:
try:
j = json.loads(r.content)
except ValueError:
raise BadResponse(r)
try:
errors = j['json']['errors']
except Exception:
errors = None
if errors:
raise PostError(errors)
else:
return j
else:
raise BadResponse(r) | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"self",
".",
"_inject_request_kwargs",
"(",
"kwargs",
")",
"kwargs",
"=",
"self",
".",
"_inject_post_data",
"(",
"kwargs",
")",
"url",
"=",
"reddit_url",
"(... | Sends a POST request to a reddit path determined by ``args``. Basically ``.post('foo', 'bar', 'baz')`` will POST http://www.reddit.com/foo/bar/baz/.json. ``kwargs`` supplied will be passed to ``requests.post`` after having ``modhash`` and ``cookies`` injected, and after having modhash injected into ``kwargs['data']`` if logged in. Injection only occurs if they don't already exist.
Returns received response JSON content as a dict.
Raises :class:`exceptions.BadResponse` if not a 200 response or no JSON content received or raises :class:`exceptions.PostError` if a reddit error was returned.
:param \*args: strings that will form the path to POST
:param \*\*kwargs: extra keyword arguments to be passed to ``requests.POST`` | [
"Sends",
"a",
"POST",
"request",
"to",
"a",
"reddit",
"path",
"determined",
"by",
"args",
".",
"Basically",
".",
"post",
"(",
"foo",
"bar",
"baz",
")",
"will",
"POST",
"http",
":",
"//",
"www",
".",
"reddit",
".",
"com",
"/",
"foo",
"/",
"bar",
"/"... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L146-L174 |
larryng/narwal | narwal/reddit.py | Reddit.login | def login(self, username, password):
"""Logs into reddit with supplied credentials using SSL. Returns :class:`requests.Response` object, or raises :class:`exceptions.LoginFail` or :class:`exceptions.BadResponse` if not a 200 response.
URL: ``https://ssl.reddit.com/api/login``
:param username: reddit username
:param password: corresponding reddit password
"""
data = dict(user=username, passwd=password, api_type='json')
r = requests.post(LOGIN_URL, data=data)
if r.status_code == 200:
try:
j = json.loads(r.content)
self._cookies = r.cookies
self._modhash = j['json']['data']['modhash']
self._username = username
return r
except Exception:
raise LoginFail()
else:
raise BadResponse(r) | python | def login(self, username, password):
"""Logs into reddit with supplied credentials using SSL. Returns :class:`requests.Response` object, or raises :class:`exceptions.LoginFail` or :class:`exceptions.BadResponse` if not a 200 response.
URL: ``https://ssl.reddit.com/api/login``
:param username: reddit username
:param password: corresponding reddit password
"""
data = dict(user=username, passwd=password, api_type='json')
r = requests.post(LOGIN_URL, data=data)
if r.status_code == 200:
try:
j = json.loads(r.content)
self._cookies = r.cookies
self._modhash = j['json']['data']['modhash']
self._username = username
return r
except Exception:
raise LoginFail()
else:
raise BadResponse(r) | [
"def",
"login",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"data",
"=",
"dict",
"(",
"user",
"=",
"username",
",",
"passwd",
"=",
"password",
",",
"api_type",
"=",
"'json'",
")",
"r",
"=",
"requests",
".",
"post",
"(",
"LOGIN_URL",
",",... | Logs into reddit with supplied credentials using SSL. Returns :class:`requests.Response` object, or raises :class:`exceptions.LoginFail` or :class:`exceptions.BadResponse` if not a 200 response.
URL: ``https://ssl.reddit.com/api/login``
:param username: reddit username
:param password: corresponding reddit password | [
"Logs",
"into",
"reddit",
"with",
"supplied",
"credentials",
"using",
"SSL",
".",
"Returns",
":",
"class",
":",
"requests",
".",
"Response",
"object",
"or",
"raises",
":",
"class",
":",
"exceptions",
".",
"LoginFail",
"or",
":",
"class",
":",
"exceptions",
... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L176-L196 |
larryng/narwal | narwal/reddit.py | Reddit.info | def info(self, url, limit=None):
"""GETs "info" about ``url``. See https://github.com/reddit/reddit/wiki/API%3A-info.json.
URL: ``http://www.reddit.com/api/info/?url=<url>``
:param url: url
:param limit: max number of links to get
"""
return self._limit_get('api', 'info', params=dict(url=url), limit=limit) | python | def info(self, url, limit=None):
"""GETs "info" about ``url``. See https://github.com/reddit/reddit/wiki/API%3A-info.json.
URL: ``http://www.reddit.com/api/info/?url=<url>``
:param url: url
:param limit: max number of links to get
"""
return self._limit_get('api', 'info', params=dict(url=url), limit=limit) | [
"def",
"info",
"(",
"self",
",",
"url",
",",
"limit",
"=",
"None",
")",
":",
"return",
"self",
".",
"_limit_get",
"(",
"'api'",
",",
"'info'",
",",
"params",
"=",
"dict",
"(",
"url",
"=",
"url",
")",
",",
"limit",
"=",
"limit",
")"
] | GETs "info" about ``url``. See https://github.com/reddit/reddit/wiki/API%3A-info.json.
URL: ``http://www.reddit.com/api/info/?url=<url>``
:param url: url
:param limit: max number of links to get | [
"GETs",
"info",
"about",
"url",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"reddit",
"/",
"reddit",
"/",
"wiki",
"/",
"API%3A",
"-",
"info",
".",
"json",
".",
"URL",
":",
"http",
":",
"//",
"www",
".",
"reddit",
".",
"com",
"/",
... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L290-L298 |
larryng/narwal | narwal/reddit.py | Reddit.search | def search(self, query, limit=None):
"""Use reddit's search function. Returns :class:`things.Listing` object.
URL: ``http://www.reddit.com/search/?q=<query>&limit=<limit>``
:param query: query string
:param limit: max number of results to get
"""
return self._limit_get('search', params=dict(q=query), limit=limit) | python | def search(self, query, limit=None):
"""Use reddit's search function. Returns :class:`things.Listing` object.
URL: ``http://www.reddit.com/search/?q=<query>&limit=<limit>``
:param query: query string
:param limit: max number of results to get
"""
return self._limit_get('search', params=dict(q=query), limit=limit) | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"limit",
"=",
"None",
")",
":",
"return",
"self",
".",
"_limit_get",
"(",
"'search'",
",",
"params",
"=",
"dict",
"(",
"q",
"=",
"query",
")",
",",
"limit",
"=",
"limit",
")"
] | Use reddit's search function. Returns :class:`things.Listing` object.
URL: ``http://www.reddit.com/search/?q=<query>&limit=<limit>``
:param query: query string
:param limit: max number of results to get | [
"Use",
"reddit",
"s",
"search",
"function",
".",
"Returns",
":",
"class",
":",
"things",
".",
"Listing",
"object",
".",
"URL",
":",
"http",
":",
"//",
"www",
".",
"reddit",
".",
"com",
"/",
"search",
"/",
"?q",
"=",
"<query",
">",
"&limit",
"=",
"<... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L300-L308 |
larryng/narwal | narwal/reddit.py | Reddit.moderators | def moderators(self, sr, limit=None):
"""GETs moderators of subreddit ``sr``. Returns :class:`things.ListBlob` object.
**NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit returns. If you need full info on each moderator, you must individually GET them using :meth:`user` or :meth:`things.Account.about`.
URL: ``http://www.reddit.com/r/<sr>/about/moderators/``
:param sr: name of subreddit
"""
userlist = self._limit_get('r', sr, 'about', 'moderators', limit=limit)
return _process_userlist(userlist) | python | def moderators(self, sr, limit=None):
"""GETs moderators of subreddit ``sr``. Returns :class:`things.ListBlob` object.
**NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit returns. If you need full info on each moderator, you must individually GET them using :meth:`user` or :meth:`things.Account.about`.
URL: ``http://www.reddit.com/r/<sr>/about/moderators/``
:param sr: name of subreddit
"""
userlist = self._limit_get('r', sr, 'about', 'moderators', limit=limit)
return _process_userlist(userlist) | [
"def",
"moderators",
"(",
"self",
",",
"sr",
",",
"limit",
"=",
"None",
")",
":",
"userlist",
"=",
"self",
".",
"_limit_get",
"(",
"'r'",
",",
"sr",
",",
"'about'",
",",
"'moderators'",
",",
"limit",
"=",
"limit",
")",
"return",
"_process_userlist",
"(... | GETs moderators of subreddit ``sr``. Returns :class:`things.ListBlob` object.
**NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit returns. If you need full info on each moderator, you must individually GET them using :meth:`user` or :meth:`things.Account.about`.
URL: ``http://www.reddit.com/r/<sr>/about/moderators/``
:param sr: name of subreddit | [
"GETs",
"moderators",
"of",
"subreddit",
"sr",
".",
"Returns",
":",
"class",
":",
"things",
".",
"ListBlob",
"object",
".",
"**",
"NOTE",
"**",
":",
"The",
":",
"class",
":",
"things",
".",
"Account",
"objects",
"in",
"the",
"returned",
"ListBlob",
"*",
... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L344-L354 |
larryng/narwal | narwal/reddit.py | Reddit.vote | def vote(self, id_, dir_):
"""Login required. POSTs a vote. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
See https://github.com/reddit/reddit/wiki/API%3A-vote.
URL: ``http://www.reddit.com/api/vote/``
:param id\_: full id of object voting on
:param dir\_: direction of vote (1, 0, or -1)
"""
data = dict(id=id_, dir=dir_)
j = self.post('api', 'vote', data=data)
return assert_truthy(j) | python | def vote(self, id_, dir_):
"""Login required. POSTs a vote. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
See https://github.com/reddit/reddit/wiki/API%3A-vote.
URL: ``http://www.reddit.com/api/vote/``
:param id\_: full id of object voting on
:param dir\_: direction of vote (1, 0, or -1)
"""
data = dict(id=id_, dir=dir_)
j = self.post('api', 'vote', data=data)
return assert_truthy(j) | [
"def",
"vote",
"(",
"self",
",",
"id_",
",",
"dir_",
")",
":",
"data",
"=",
"dict",
"(",
"id",
"=",
"id_",
",",
"dir",
"=",
"dir_",
")",
"j",
"=",
"self",
".",
"post",
"(",
"'api'",
",",
"'vote'",
",",
"data",
"=",
"data",
")",
"return",
"ass... | Login required. POSTs a vote. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
See https://github.com/reddit/reddit/wiki/API%3A-vote.
URL: ``http://www.reddit.com/api/vote/``
:param id\_: full id of object voting on
:param dir\_: direction of vote (1, 0, or -1) | [
"Login",
"required",
".",
"POSTs",
"a",
"vote",
".",
"Returns",
"True",
"or",
"raises",
":",
"class",
":",
"exceptions",
".",
"UnexpectedResponse",
"if",
"non",
"-",
"truthy",
"value",
"in",
"response",
".",
"See",
"https",
":",
"//",
"github",
".",
"com... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L390-L402 |
larryng/narwal | narwal/reddit.py | Reddit.comment | def comment(self, parent, text):
"""Login required. POSTs a comment in response to ``parent``. Returns :class:`things.Comment` object.
See https://github.com/reddit/reddit/wiki/API%3A-comment.
URL: ``http://www.reddit.com/api/comment/``
:param parent: full id of thing commenting on
:param text: comment text
"""
data = dict(parent=parent, text=text)
j = self.post('api', 'comment', data=data)
try:
return self._thingify(j['json']['data']['things'][0])
except Exception:
raise UnexpectedResponse(j) | python | def comment(self, parent, text):
"""Login required. POSTs a comment in response to ``parent``. Returns :class:`things.Comment` object.
See https://github.com/reddit/reddit/wiki/API%3A-comment.
URL: ``http://www.reddit.com/api/comment/``
:param parent: full id of thing commenting on
:param text: comment text
"""
data = dict(parent=parent, text=text)
j = self.post('api', 'comment', data=data)
try:
return self._thingify(j['json']['data']['things'][0])
except Exception:
raise UnexpectedResponse(j) | [
"def",
"comment",
"(",
"self",
",",
"parent",
",",
"text",
")",
":",
"data",
"=",
"dict",
"(",
"parent",
"=",
"parent",
",",
"text",
"=",
"text",
")",
"j",
"=",
"self",
".",
"post",
"(",
"'api'",
",",
"'comment'",
",",
"data",
"=",
"data",
")",
... | Login required. POSTs a comment in response to ``parent``. Returns :class:`things.Comment` object.
See https://github.com/reddit/reddit/wiki/API%3A-comment.
URL: ``http://www.reddit.com/api/comment/``
:param parent: full id of thing commenting on
:param text: comment text | [
"Login",
"required",
".",
"POSTs",
"a",
"comment",
"in",
"response",
"to",
"parent",
".",
"Returns",
":",
"class",
":",
"things",
".",
"Comment",
"object",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"reddit",
"/",
"reddit",
"/",
"wiki",... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L441-L456 |
larryng/narwal | narwal/reddit.py | Reddit.edit | def edit(self, id_, text):
"""Login required. Sends POST to change selftext or comment text to ``text``. Returns :class:`things.Comment` or :class:`things.Link` object depending on what's being edited. Raises :class:`UnexpectedResponse` if neither is returned.
URL: ``http://www.reddit.com/api/editusertext/``
:param id\_: full id of link or comment to edit
:param text: new self or comment text
"""
data = dict(thing_id=id_, text=text)
j = self.post('api', 'editusertext', data=data)
try:
return self._thingify(j['json']['data']['things'][0])
except Exception:
raise UnexpectedResponse(j) | python | def edit(self, id_, text):
"""Login required. Sends POST to change selftext or comment text to ``text``. Returns :class:`things.Comment` or :class:`things.Link` object depending on what's being edited. Raises :class:`UnexpectedResponse` if neither is returned.
URL: ``http://www.reddit.com/api/editusertext/``
:param id\_: full id of link or comment to edit
:param text: new self or comment text
"""
data = dict(thing_id=id_, text=text)
j = self.post('api', 'editusertext', data=data)
try:
return self._thingify(j['json']['data']['things'][0])
except Exception:
raise UnexpectedResponse(j) | [
"def",
"edit",
"(",
"self",
",",
"id_",
",",
"text",
")",
":",
"data",
"=",
"dict",
"(",
"thing_id",
"=",
"id_",
",",
"text",
"=",
"text",
")",
"j",
"=",
"self",
".",
"post",
"(",
"'api'",
",",
"'editusertext'",
",",
"data",
"=",
"data",
")",
"... | Login required. Sends POST to change selftext or comment text to ``text``. Returns :class:`things.Comment` or :class:`things.Link` object depending on what's being edited. Raises :class:`UnexpectedResponse` if neither is returned.
URL: ``http://www.reddit.com/api/editusertext/``
:param id\_: full id of link or comment to edit
:param text: new self or comment text | [
"Login",
"required",
".",
"Sends",
"POST",
"to",
"change",
"selftext",
"or",
"comment",
"text",
"to",
"text",
".",
"Returns",
":",
"class",
":",
"things",
".",
"Comment",
"or",
":",
"class",
":",
"things",
".",
"Link",
"object",
"depending",
"on",
"what"... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L459-L472 |
larryng/narwal | narwal/reddit.py | Reddit.submit_link | def submit_link(self, sr, title, url, follow=True):
"""Login required. POSTs a link submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise.
Argument ``follow`` exists because reddit only returns the permalink after POSTing a submission. In order to get detailed info on the new submission, we need to make another request. If you don't want to make that additional request, just set ``follow=False``.
See https://github.com/reddit/reddit/wiki/API%3A-submit.
URL: ``http://www.reddit.com/api/submit/``
:param sr: name of subreddit to submit to
:param title: title of submission
:param url: submission link
:param follow: set to ``True`` to follow retrieved permalink to return detailed :class:`things.Link` object. ``False`` to just return permalink.
:type follow: bool
"""
return self._submit(sr, title, 'link', url=url, follow=follow) | python | def submit_link(self, sr, title, url, follow=True):
"""Login required. POSTs a link submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise.
Argument ``follow`` exists because reddit only returns the permalink after POSTing a submission. In order to get detailed info on the new submission, we need to make another request. If you don't want to make that additional request, just set ``follow=False``.
See https://github.com/reddit/reddit/wiki/API%3A-submit.
URL: ``http://www.reddit.com/api/submit/``
:param sr: name of subreddit to submit to
:param title: title of submission
:param url: submission link
:param follow: set to ``True`` to follow retrieved permalink to return detailed :class:`things.Link` object. ``False`` to just return permalink.
:type follow: bool
"""
return self._submit(sr, title, 'link', url=url, follow=follow) | [
"def",
"submit_link",
"(",
"self",
",",
"sr",
",",
"title",
",",
"url",
",",
"follow",
"=",
"True",
")",
":",
"return",
"self",
".",
"_submit",
"(",
"sr",
",",
"title",
",",
"'link'",
",",
"url",
"=",
"url",
",",
"follow",
"=",
"follow",
")"
] | Login required. POSTs a link submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise.
Argument ``follow`` exists because reddit only returns the permalink after POSTing a submission. In order to get detailed info on the new submission, we need to make another request. If you don't want to make that additional request, just set ``follow=False``.
See https://github.com/reddit/reddit/wiki/API%3A-submit.
URL: ``http://www.reddit.com/api/submit/``
:param sr: name of subreddit to submit to
:param title: title of submission
:param url: submission link
:param follow: set to ``True`` to follow retrieved permalink to return detailed :class:`things.Link` object. ``False`` to just return permalink.
:type follow: bool | [
"Login",
"required",
".",
"POSTs",
"a",
"link",
"submission",
".",
"Returns",
":",
"class",
":",
"things",
".",
"Link",
"object",
"if",
"follow",
"=",
"True",
"(",
"default",
")",
"or",
"the",
"string",
"permalink",
"of",
"the",
"new",
"submission",
"oth... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L494-L509 |
larryng/narwal | narwal/reddit.py | Reddit.submit_text | def submit_text(self, sr, title, text, follow=True):
"""Login required. POSTs a text submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise.
Argument ``follow`` exists because reddit only returns the permalink after POSTing a submission. In order to get detailed info on the new submission, we need to make another request. If you don't want to make that additional request, set ``follow=False``.
See https://github.com/reddit/reddit/wiki/API%3A-submit.
URL: ``http://www.reddit.com/api/submit/``
:param sr: name of subreddit to submit to
:param title: title of submission
:param text: submission self text
:param follow: set to ``True`` to follow retrieved permalink to return detailed :class:`things.Link` object. ``False`` to just return permalink.
:type follow: bool
"""
return self._submit(sr, title, 'self', text=text, follow=follow) | python | def submit_text(self, sr, title, text, follow=True):
"""Login required. POSTs a text submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise.
Argument ``follow`` exists because reddit only returns the permalink after POSTing a submission. In order to get detailed info on the new submission, we need to make another request. If you don't want to make that additional request, set ``follow=False``.
See https://github.com/reddit/reddit/wiki/API%3A-submit.
URL: ``http://www.reddit.com/api/submit/``
:param sr: name of subreddit to submit to
:param title: title of submission
:param text: submission self text
:param follow: set to ``True`` to follow retrieved permalink to return detailed :class:`things.Link` object. ``False`` to just return permalink.
:type follow: bool
"""
return self._submit(sr, title, 'self', text=text, follow=follow) | [
"def",
"submit_text",
"(",
"self",
",",
"sr",
",",
"title",
",",
"text",
",",
"follow",
"=",
"True",
")",
":",
"return",
"self",
".",
"_submit",
"(",
"sr",
",",
"title",
",",
"'self'",
",",
"text",
"=",
"text",
",",
"follow",
"=",
"follow",
")"
] | Login required. POSTs a text submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise.
Argument ``follow`` exists because reddit only returns the permalink after POSTing a submission. In order to get detailed info on the new submission, we need to make another request. If you don't want to make that additional request, set ``follow=False``.
See https://github.com/reddit/reddit/wiki/API%3A-submit.
URL: ``http://www.reddit.com/api/submit/``
:param sr: name of subreddit to submit to
:param title: title of submission
:param text: submission self text
:param follow: set to ``True`` to follow retrieved permalink to return detailed :class:`things.Link` object. ``False`` to just return permalink.
:type follow: bool | [
"Login",
"required",
".",
"POSTs",
"a",
"text",
"submission",
".",
"Returns",
":",
"class",
":",
"things",
".",
"Link",
"object",
"if",
"follow",
"=",
"True",
"(",
"default",
")",
"or",
"the",
"string",
"permalink",
"of",
"the",
"new",
"submission",
"oth... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L512-L527 |
larryng/narwal | narwal/reddit.py | Reddit.message | def message(self, to, subject, text):
"""Alias for :meth:`compose`."""
return self.compose(to, subject, text) | python | def message(self, to, subject, text):
"""Alias for :meth:`compose`."""
return self.compose(to, subject, text) | [
"def",
"message",
"(",
"self",
",",
"to",
",",
"subject",
",",
"text",
")",
":",
"return",
"self",
".",
"compose",
"(",
"to",
",",
"subject",
",",
"text",
")"
] | Alias for :meth:`compose`. | [
"Alias",
"for",
":",
"meth",
":",
"compose",
"."
] | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L640-L642 |
larryng/narwal | narwal/reddit.py | Reddit.compose | def compose(self, to, subject, text):
"""Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/compose/``
:param to: username or :class`things.Account` of user to send to
:param subject: subject of message
:param text: message body text
"""
if isinstance(to, Account):
to = to.name
data = dict(to=to, subject=subject, text=text)
j = self.post('api', 'compose', data=data)
return assert_truthy(j) | python | def compose(self, to, subject, text):
"""Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/compose/``
:param to: username or :class`things.Account` of user to send to
:param subject: subject of message
:param text: message body text
"""
if isinstance(to, Account):
to = to.name
data = dict(to=to, subject=subject, text=text)
j = self.post('api', 'compose', data=data)
return assert_truthy(j) | [
"def",
"compose",
"(",
"self",
",",
"to",
",",
"subject",
",",
"text",
")",
":",
"if",
"isinstance",
"(",
"to",
",",
"Account",
")",
":",
"to",
"=",
"to",
".",
"name",
"data",
"=",
"dict",
"(",
"to",
"=",
"to",
",",
"subject",
"=",
"subject",
"... | Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/compose/``
:param to: username or :class`things.Account` of user to send to
:param subject: subject of message
:param text: message body text | [
"Login",
"required",
".",
"Sends",
"POST",
"to",
"send",
"a",
"message",
"to",
"a",
"user",
".",
"Returns",
"True",
"or",
"raises",
":",
"class",
":",
"exceptions",
".",
"UnexpectedResponse",
"if",
"non",
"-",
"truthy",
"value",
"in",
"response",
".",
"U... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L645-L658 |
larryng/narwal | narwal/reddit.py | Reddit.read_message | def read_message(self, id_):
"""Login required. Send POST to mark a message as read. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/read_message/``
:param id\_: full id of message to mark
"""
data = dict(id=id_)
j = self.post('api', 'read_message', data=data)
return assert_truthy(j) | python | def read_message(self, id_):
"""Login required. Send POST to mark a message as read. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/read_message/``
:param id\_: full id of message to mark
"""
data = dict(id=id_)
j = self.post('api', 'read_message', data=data)
return assert_truthy(j) | [
"def",
"read_message",
"(",
"self",
",",
"id_",
")",
":",
"data",
"=",
"dict",
"(",
"id",
"=",
"id_",
")",
"j",
"=",
"self",
".",
"post",
"(",
"'api'",
",",
"'read_message'",
",",
"data",
"=",
"data",
")",
"return",
"assert_truthy",
"(",
"j",
")"
] | Login required. Send POST to mark a message as read. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/read_message/``
:param id\_: full id of message to mark | [
"Login",
"required",
".",
"Send",
"POST",
"to",
"mark",
"a",
"message",
"as",
"read",
".",
"Returns",
"True",
"or",
"raises",
":",
"class",
":",
"exceptions",
".",
"UnexpectedResponse",
"if",
"non",
"-",
"truthy",
"value",
"in",
"response",
".",
"URL",
"... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L661-L670 |
larryng/narwal | narwal/reddit.py | Reddit.subscribe | def subscribe(self, sr):
"""Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/subscribe/``
:param sr: full id of subreddit or name of subreddit (full id is preferred)
"""
if not sr.startswith('t5_'):
sr = self.subreddit(sr).name
data = dict(action='sub', sr=sr)
j = self.post('api', 'subscribe', data=data)
return assert_truthy(j) | python | def subscribe(self, sr):
"""Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/subscribe/``
:param sr: full id of subreddit or name of subreddit (full id is preferred)
"""
if not sr.startswith('t5_'):
sr = self.subreddit(sr).name
data = dict(action='sub', sr=sr)
j = self.post('api', 'subscribe', data=data)
return assert_truthy(j) | [
"def",
"subscribe",
"(",
"self",
",",
"sr",
")",
":",
"if",
"not",
"sr",
".",
"startswith",
"(",
"'t5_'",
")",
":",
"sr",
"=",
"self",
".",
"subreddit",
"(",
"sr",
")",
".",
"name",
"data",
"=",
"dict",
"(",
"action",
"=",
"'sub'",
",",
"sr",
"... | Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/subscribe/``
:param sr: full id of subreddit or name of subreddit (full id is preferred) | [
"Login",
"required",
".",
"Send",
"POST",
"to",
"subscribe",
"to",
"a",
"subreddit",
".",
"If",
"sr",
"is",
"the",
"name",
"of",
"the",
"subreddit",
"a",
"GET",
"request",
"is",
"sent",
"to",
"retrieve",
"the",
"full",
"id",
"of",
"the",
"subreddit",
"... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L685-L696 |
larryng/narwal | narwal/reddit.py | Reddit.distinguish | def distinguish(self, id_, how=True):
"""Login required. Sends POST to distinguish a submission or comment. Returns :class:`things.Link` or :class:`things.Comment`, or raises :class:`exceptions.UnexpectedResponse` otherwise.
URL: ``http://www.reddit.com/api/distinguish/``
:param id\_: full id of object to distinguish
:param how: either True, False, or 'admin'
"""
if how == True:
h = 'yes'
elif how == False:
h = 'no'
elif how == 'admin':
h = 'admin'
else:
raise ValueError("how must be either True, False, or 'admin'")
data = dict(id=id_)
j = self.post('api', 'distinguish', h, data=data)
try:
return self._thingify(j['json']['data']['things'][0])
except Exception:
raise UnexpectedResponse(j) | python | def distinguish(self, id_, how=True):
"""Login required. Sends POST to distinguish a submission or comment. Returns :class:`things.Link` or :class:`things.Comment`, or raises :class:`exceptions.UnexpectedResponse` otherwise.
URL: ``http://www.reddit.com/api/distinguish/``
:param id\_: full id of object to distinguish
:param how: either True, False, or 'admin'
"""
if how == True:
h = 'yes'
elif how == False:
h = 'no'
elif how == 'admin':
h = 'admin'
else:
raise ValueError("how must be either True, False, or 'admin'")
data = dict(id=id_)
j = self.post('api', 'distinguish', h, data=data)
try:
return self._thingify(j['json']['data']['things'][0])
except Exception:
raise UnexpectedResponse(j) | [
"def",
"distinguish",
"(",
"self",
",",
"id_",
",",
"how",
"=",
"True",
")",
":",
"if",
"how",
"==",
"True",
":",
"h",
"=",
"'yes'",
"elif",
"how",
"==",
"False",
":",
"h",
"=",
"'no'",
"elif",
"how",
"==",
"'admin'",
":",
"h",
"=",
"'admin'",
... | Login required. Sends POST to distinguish a submission or comment. Returns :class:`things.Link` or :class:`things.Comment`, or raises :class:`exceptions.UnexpectedResponse` otherwise.
URL: ``http://www.reddit.com/api/distinguish/``
:param id\_: full id of object to distinguish
:param how: either True, False, or 'admin' | [
"Login",
"required",
".",
"Sends",
"POST",
"to",
"distinguish",
"a",
"submission",
"or",
"comment",
".",
"Returns",
":",
"class",
":",
"things",
".",
"Link",
"or",
":",
"class",
":",
"things",
".",
"Comment",
"or",
"raises",
":",
"class",
":",
"exception... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L831-L852 |
larryng/narwal | narwal/reddit.py | Reddit.flairlist | def flairlist(self, r, limit=1000, after=None, before=None):
"""Login required. Gets flairlist for subreddit `r`. See https://github.com/reddit/reddit/wiki/API%3A-flairlist.
However, the wiki docs are wrong (as of 2012/5/4). Returns :class:`things.ListBlob` of :class:`things.Blob` objects, each object being a mapping with `user`, `flair\_css\_class`, and `flair\_text` attributes.
URL: ``http://www.reddit.com/r/<r>/api/flairlist``
:param r: name of subreddit
:param limit: max number of items to return
:param after: full id of user to return entries after
:param before: full id of user to return entries *before*
"""
params = dict(limit=limit)
if after:
params['after'] = after
elif before:
params['before'] = before
b = self.get('r', r, 'api', 'flairlist', params=params)
return b.users | python | def flairlist(self, r, limit=1000, after=None, before=None):
"""Login required. Gets flairlist for subreddit `r`. See https://github.com/reddit/reddit/wiki/API%3A-flairlist.
However, the wiki docs are wrong (as of 2012/5/4). Returns :class:`things.ListBlob` of :class:`things.Blob` objects, each object being a mapping with `user`, `flair\_css\_class`, and `flair\_text` attributes.
URL: ``http://www.reddit.com/r/<r>/api/flairlist``
:param r: name of subreddit
:param limit: max number of items to return
:param after: full id of user to return entries after
:param before: full id of user to return entries *before*
"""
params = dict(limit=limit)
if after:
params['after'] = after
elif before:
params['before'] = before
b = self.get('r', r, 'api', 'flairlist', params=params)
return b.users | [
"def",
"flairlist",
"(",
"self",
",",
"r",
",",
"limit",
"=",
"1000",
",",
"after",
"=",
"None",
",",
"before",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
"limit",
"=",
"limit",
")",
"if",
"after",
":",
"params",
"[",
"'after'",
"]",
"=",... | Login required. Gets flairlist for subreddit `r`. See https://github.com/reddit/reddit/wiki/API%3A-flairlist.
However, the wiki docs are wrong (as of 2012/5/4). Returns :class:`things.ListBlob` of :class:`things.Blob` objects, each object being a mapping with `user`, `flair\_css\_class`, and `flair\_text` attributes.
URL: ``http://www.reddit.com/r/<r>/api/flairlist``
:param r: name of subreddit
:param limit: max number of items to return
:param after: full id of user to return entries after
:param before: full id of user to return entries *before* | [
"Login",
"required",
".",
"Gets",
"flairlist",
"for",
"subreddit",
"r",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"reddit",
"/",
"reddit",
"/",
"wiki",
"/",
"API%3A",
"-",
"flairlist",
".",
"However",
"the",
"wiki",
"docs",
"are",
"wro... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L856-L874 |
larryng/narwal | narwal/reddit.py | Reddit.flair | def flair(self, r, name, text, css_class):
"""Login required. Sets flair for a user. See https://github.com/reddit/reddit/wiki/API%3A-flair. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/flair``
:param r: name of subreddit
:param name: name of the user
:param text: flair text to assign
:param css_class: CSS class to assign to flair text
"""
data = dict(r=r, name=name, text=text, css_class=css_class)
j = self.post('api', 'flair', data=data)
return assert_truthy(j) | python | def flair(self, r, name, text, css_class):
"""Login required. Sets flair for a user. See https://github.com/reddit/reddit/wiki/API%3A-flair. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/flair``
:param r: name of subreddit
:param name: name of the user
:param text: flair text to assign
:param css_class: CSS class to assign to flair text
"""
data = dict(r=r, name=name, text=text, css_class=css_class)
j = self.post('api', 'flair', data=data)
return assert_truthy(j) | [
"def",
"flair",
"(",
"self",
",",
"r",
",",
"name",
",",
"text",
",",
"css_class",
")",
":",
"data",
"=",
"dict",
"(",
"r",
"=",
"r",
",",
"name",
"=",
"name",
",",
"text",
"=",
"text",
",",
"css_class",
"=",
"css_class",
")",
"j",
"=",
"self",... | Login required. Sets flair for a user. See https://github.com/reddit/reddit/wiki/API%3A-flair. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/flair``
:param r: name of subreddit
:param name: name of the user
:param text: flair text to assign
:param css_class: CSS class to assign to flair text | [
"Login",
"required",
".",
"Sets",
"flair",
"for",
"a",
"user",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"reddit",
"/",
"reddit",
"/",
"wiki",
"/",
"API%3A",
"-",
"flair",
".",
"Returns",
"True",
"or",
"raises",
":",
"class",
":",
... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L877-L889 |
larryng/narwal | narwal/reddit.py | Reddit.flaircsv | def flaircsv(self, r, flair_csv):
"""Login required. Bulk sets flair for users. See https://github.com/reddit/reddit/wiki/API%3A-flaircsv/. Returns response JSON content as dict.
URL: ``http://www.reddit.com/api/flaircsv``
:param r: name of subreddit
:param flair_csv: csv string
"""
# TODO: handle the response better than just returning
data = dict(r=r, flair_csv=flair_csv)
return self.post('api', 'flaircsv', data=data) | python | def flaircsv(self, r, flair_csv):
"""Login required. Bulk sets flair for users. See https://github.com/reddit/reddit/wiki/API%3A-flaircsv/. Returns response JSON content as dict.
URL: ``http://www.reddit.com/api/flaircsv``
:param r: name of subreddit
:param flair_csv: csv string
"""
# TODO: handle the response better than just returning
data = dict(r=r, flair_csv=flair_csv)
return self.post('api', 'flaircsv', data=data) | [
"def",
"flaircsv",
"(",
"self",
",",
"r",
",",
"flair_csv",
")",
":",
"# TODO: handle the response better than just returning",
"data",
"=",
"dict",
"(",
"r",
"=",
"r",
",",
"flair_csv",
"=",
"flair_csv",
")",
"return",
"self",
".",
"post",
"(",
"'api'",
","... | Login required. Bulk sets flair for users. See https://github.com/reddit/reddit/wiki/API%3A-flaircsv/. Returns response JSON content as dict.
URL: ``http://www.reddit.com/api/flaircsv``
:param r: name of subreddit
:param flair_csv: csv string | [
"Login",
"required",
".",
"Bulk",
"sets",
"flair",
"for",
"users",
".",
"See",
"https",
":",
"//",
"github",
".",
"com",
"/",
"reddit",
"/",
"reddit",
"/",
"wiki",
"/",
"API%3A",
"-",
"flaircsv",
"/",
".",
"Returns",
"response",
"JSON",
"content",
"as"... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L892-L902 |
larryng/narwal | narwal/reddit.py | Reddit.contributors | def contributors(self, sr, limit=None):
"""Login required. GETs list of contributors to subreddit ``sr``. Returns :class:`things.ListBlob` object.
**NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit returns. If you need full info on each contributor, you must individually GET them using :meth:`user` or :meth:`things.Account.about`.
URL: ``http://www.reddit.com/r/<sr>/about/contributors/``
:param sr: name of subreddit
"""
userlist = self._limit_get('r', sr, 'about', 'contributors', limit=limit)
return _process_userlist(userlist) | python | def contributors(self, sr, limit=None):
"""Login required. GETs list of contributors to subreddit ``sr``. Returns :class:`things.ListBlob` object.
**NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit returns. If you need full info on each contributor, you must individually GET them using :meth:`user` or :meth:`things.Account.about`.
URL: ``http://www.reddit.com/r/<sr>/about/contributors/``
:param sr: name of subreddit
"""
userlist = self._limit_get('r', sr, 'about', 'contributors', limit=limit)
return _process_userlist(userlist) | [
"def",
"contributors",
"(",
"self",
",",
"sr",
",",
"limit",
"=",
"None",
")",
":",
"userlist",
"=",
"self",
".",
"_limit_get",
"(",
"'r'",
",",
"sr",
",",
"'about'",
",",
"'contributors'",
",",
"limit",
"=",
"limit",
")",
"return",
"_process_userlist",
... | Login required. GETs list of contributors to subreddit ``sr``. Returns :class:`things.ListBlob` object.
**NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit returns. If you need full info on each contributor, you must individually GET them using :meth:`user` or :meth:`things.Account.about`.
URL: ``http://www.reddit.com/r/<sr>/about/contributors/``
:param sr: name of subreddit | [
"Login",
"required",
".",
"GETs",
"list",
"of",
"contributors",
"to",
"subreddit",
"sr",
".",
"Returns",
":",
"class",
":",
"things",
".",
"ListBlob",
"object",
".",
"**",
"NOTE",
"**",
":",
"The",
":",
"class",
":",
"things",
".",
"Account",
"objects",
... | train | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L905-L915 |
clusterpoint/python-client-api | pycps/converters.py | etree_to_dict | def etree_to_dict(source):
""" Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- An etree Element or ElementTree.
Returns:
A dictionary representing sorce's xml structure where tags with multiple identical childrens
contain list of all their children dictionaries..
>>> etree_to_dict(ET.fromstring('<content><id>12</id><title/></content>'))
{'content': {'id': '12', 'title': None}}
>>> etree_to_dict(ET.fromstring('<content><list><li>foo</li><li>bar</li></list></content>'))
{'content': {'list': [{'li': 'foo'}, {'li': 'bar'}]}}
"""
def etree_to_dict_recursive(parent):
children = parent.getchildren()
if children:
d = {}
identical_children = False
for child in children:
if not identical_children:
if child.tag in d:
identical_children = True
l = [{key: d[key]} for key in d]
l.append({child.tag: etree_to_dict_recursive(child)})
del d
else:
d.update({child.tag: etree_to_dict_recursive(child)})
else:
l.append({child.tag: etree_to_dict_recursive(child)})
return (d if not identical_children else l)
else:
return parent.text
if hasattr(source, 'getroot'):
source = source.getroot()
if hasattr(source, 'tag'):
return {source.tag: etree_to_dict_recursive(source)}
else:
raise TypeError("Requires an Element or an ElementTree.") | python | def etree_to_dict(source):
""" Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- An etree Element or ElementTree.
Returns:
A dictionary representing sorce's xml structure where tags with multiple identical childrens
contain list of all their children dictionaries..
>>> etree_to_dict(ET.fromstring('<content><id>12</id><title/></content>'))
{'content': {'id': '12', 'title': None}}
>>> etree_to_dict(ET.fromstring('<content><list><li>foo</li><li>bar</li></list></content>'))
{'content': {'list': [{'li': 'foo'}, {'li': 'bar'}]}}
"""
def etree_to_dict_recursive(parent):
children = parent.getchildren()
if children:
d = {}
identical_children = False
for child in children:
if not identical_children:
if child.tag in d:
identical_children = True
l = [{key: d[key]} for key in d]
l.append({child.tag: etree_to_dict_recursive(child)})
del d
else:
d.update({child.tag: etree_to_dict_recursive(child)})
else:
l.append({child.tag: etree_to_dict_recursive(child)})
return (d if not identical_children else l)
else:
return parent.text
if hasattr(source, 'getroot'):
source = source.getroot()
if hasattr(source, 'tag'):
return {source.tag: etree_to_dict_recursive(source)}
else:
raise TypeError("Requires an Element or an ElementTree.") | [
"def",
"etree_to_dict",
"(",
"source",
")",
":",
"def",
"etree_to_dict_recursive",
"(",
"parent",
")",
":",
"children",
"=",
"parent",
".",
"getchildren",
"(",
")",
"if",
"children",
":",
"d",
"=",
"{",
"}",
"identical_children",
"=",
"False",
"for",
"chil... | Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- An etree Element or ElementTree.
Returns:
A dictionary representing sorce's xml structure where tags with multiple identical childrens
contain list of all their children dictionaries..
>>> etree_to_dict(ET.fromstring('<content><id>12</id><title/></content>'))
{'content': {'id': '12', 'title': None}}
>>> etree_to_dict(ET.fromstring('<content><list><li>foo</li><li>bar</li></list></content>'))
{'content': {'list': [{'li': 'foo'}, {'li': 'bar'}]}} | [
"Recursively",
"load",
"dict",
"/",
"list",
"representation",
"of",
"an",
"XML",
"tree",
"into",
"an",
"etree",
"representation",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/converters.py#L41-L82 |
clusterpoint/python-client-api | pycps/converters.py | dict_to_etree | def dict_to_etree(source, root_tag=None):
""" Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- A dictionary representing an XML document where identical children tags are
countained in a list.
Keyword args:
root_tag -- A parent tag in which to wrap the xml tree. If None, and the source dict
contains multiple root items, a list of etree's Elements will be returned.
Returns:
An ET.Element which is the root of an XML tree or a list of these.
>>> dict_to_etree({'foo': 'lorem'}) #doctest: +ELLIPSIS
<Element foo at 0x...>
>>> dict_to_etree({'foo': 'lorem', 'bar': 'ipsum'}) #doctest: +ELLIPSIS
[<Element foo at 0x...>, <Element bar at 0x...>]
>>> ET.tostring(dict_to_etree({'document': {'item1': 'foo', 'item2': 'bar'}}))
'<document><item2>bar</item2><item1>foo</item1></document>'
>>> ET.tostring(dict_to_etree({'foo': 'baz'}, root_tag='document'))
'<document><foo>baz</foo></document>'
>>> ET.tostring(dict_to_etree({'title': 'foo', 'list': [{'li':1}, {'li':2}]}, root_tag='document'))
'<document><list><li>1</li><li>2</li></list><title>foo</title></document>'
"""
def dict_to_etree_recursive(source, parent):
if hasattr(source, 'keys'):
for key, value in source.iteritems():
sub = ET.SubElement(parent, key)
dict_to_etree_recursive(value, sub)
elif isinstance(source, list):
for element in source:
dict_to_etree_recursive(element, parent)
else: # TODO: Add feature to include xml literals as special objects or a etree subtree
parent.text = source
if root_tag is None:
if len(source) == 1:
root_tag = source.keys()[0]
source = source[root_tag]
else:
roots = []
for tag, content in source.iteritems():
root = ET.Element(tag)
dict_to_etree_recursive(content, root)
roots.append(root)
return roots
root = ET.Element(root_tag)
dict_to_etree_recursive(source, root)
return root | python | def dict_to_etree(source, root_tag=None):
""" Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- A dictionary representing an XML document where identical children tags are
countained in a list.
Keyword args:
root_tag -- A parent tag in which to wrap the xml tree. If None, and the source dict
contains multiple root items, a list of etree's Elements will be returned.
Returns:
An ET.Element which is the root of an XML tree or a list of these.
>>> dict_to_etree({'foo': 'lorem'}) #doctest: +ELLIPSIS
<Element foo at 0x...>
>>> dict_to_etree({'foo': 'lorem', 'bar': 'ipsum'}) #doctest: +ELLIPSIS
[<Element foo at 0x...>, <Element bar at 0x...>]
>>> ET.tostring(dict_to_etree({'document': {'item1': 'foo', 'item2': 'bar'}}))
'<document><item2>bar</item2><item1>foo</item1></document>'
>>> ET.tostring(dict_to_etree({'foo': 'baz'}, root_tag='document'))
'<document><foo>baz</foo></document>'
>>> ET.tostring(dict_to_etree({'title': 'foo', 'list': [{'li':1}, {'li':2}]}, root_tag='document'))
'<document><list><li>1</li><li>2</li></list><title>foo</title></document>'
"""
def dict_to_etree_recursive(source, parent):
if hasattr(source, 'keys'):
for key, value in source.iteritems():
sub = ET.SubElement(parent, key)
dict_to_etree_recursive(value, sub)
elif isinstance(source, list):
for element in source:
dict_to_etree_recursive(element, parent)
else: # TODO: Add feature to include xml literals as special objects or a etree subtree
parent.text = source
if root_tag is None:
if len(source) == 1:
root_tag = source.keys()[0]
source = source[root_tag]
else:
roots = []
for tag, content in source.iteritems():
root = ET.Element(tag)
dict_to_etree_recursive(content, root)
roots.append(root)
return roots
root = ET.Element(root_tag)
dict_to_etree_recursive(source, root)
return root | [
"def",
"dict_to_etree",
"(",
"source",
",",
"root_tag",
"=",
"None",
")",
":",
"def",
"dict_to_etree_recursive",
"(",
"source",
",",
"parent",
")",
":",
"if",
"hasattr",
"(",
"source",
",",
"'keys'",
")",
":",
"for",
"key",
",",
"value",
"in",
"source",
... | Recursively load dict/list representation of an XML tree into an etree representation.
Args:
source -- A dictionary representing an XML document where identical children tags are
countained in a list.
Keyword args:
root_tag -- A parent tag in which to wrap the xml tree. If None, and the source dict
contains multiple root items, a list of etree's Elements will be returned.
Returns:
An ET.Element which is the root of an XML tree or a list of these.
>>> dict_to_etree({'foo': 'lorem'}) #doctest: +ELLIPSIS
<Element foo at 0x...>
>>> dict_to_etree({'foo': 'lorem', 'bar': 'ipsum'}) #doctest: +ELLIPSIS
[<Element foo at 0x...>, <Element bar at 0x...>]
>>> ET.tostring(dict_to_etree({'document': {'item1': 'foo', 'item2': 'bar'}}))
'<document><item2>bar</item2><item1>foo</item1></document>'
>>> ET.tostring(dict_to_etree({'foo': 'baz'}, root_tag='document'))
'<document><foo>baz</foo></document>'
>>> ET.tostring(dict_to_etree({'title': 'foo', 'list': [{'li':1}, {'li':2}]}, root_tag='document'))
'<document><list><li>1</li><li>2</li></list><title>foo</title></document>' | [
"Recursively",
"load",
"dict",
"/",
"list",
"representation",
"of",
"an",
"XML",
"tree",
"into",
"an",
"etree",
"representation",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/converters.py#L85-L138 |
clusterpoint/python-client-api | pycps/converters.py | to_etree | def to_etree(source, root_tag=None):
""" Convert various representations of an XML structure to a etree Element
Args:
source -- The source object to be converted - ET.Element\ElementTree, dict or string.
Keyword args:
root_tag -- A optional parent tag in which to wrap the xml tree if no root in dict representation.
See dict_to_etree()
Returns:
A etree Element matching the source object.
>>> to_etree("<content/>") #doctest: +ELLIPSIS
<Element content at 0x...>
>>> to_etree({'document': {'title': 'foo', 'list': [{'li':1}, {'li':2}]}}) #doctest: +ELLIPSIS
<Element document at 0x...>
>>> to_etree(ET.Element('root')) #doctest: +ELLIPSIS
<Element root at 0x...>
"""
if hasattr(source, 'get_root'): #XXX:
return source.get_root()
elif isinstance(source, type(ET.Element('x'))): #XXX: # cElementTree.Element isn't exposed directly
return source
elif isinstance(source, basestring):
try:
return ET.fromstring(source)
except:
raise XMLError(source)
elif hasattr(source, 'keys'): # Dict.
return dict_to_etree(source, root_tag)
else:
raise XMLError(source) | python | def to_etree(source, root_tag=None):
""" Convert various representations of an XML structure to a etree Element
Args:
source -- The source object to be converted - ET.Element\ElementTree, dict or string.
Keyword args:
root_tag -- A optional parent tag in which to wrap the xml tree if no root in dict representation.
See dict_to_etree()
Returns:
A etree Element matching the source object.
>>> to_etree("<content/>") #doctest: +ELLIPSIS
<Element content at 0x...>
>>> to_etree({'document': {'title': 'foo', 'list': [{'li':1}, {'li':2}]}}) #doctest: +ELLIPSIS
<Element document at 0x...>
>>> to_etree(ET.Element('root')) #doctest: +ELLIPSIS
<Element root at 0x...>
"""
if hasattr(source, 'get_root'): #XXX:
return source.get_root()
elif isinstance(source, type(ET.Element('x'))): #XXX: # cElementTree.Element isn't exposed directly
return source
elif isinstance(source, basestring):
try:
return ET.fromstring(source)
except:
raise XMLError(source)
elif hasattr(source, 'keys'): # Dict.
return dict_to_etree(source, root_tag)
else:
raise XMLError(source) | [
"def",
"to_etree",
"(",
"source",
",",
"root_tag",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"source",
",",
"'get_root'",
")",
":",
"#XXX:",
"return",
"source",
".",
"get_root",
"(",
")",
"elif",
"isinstance",
"(",
"source",
",",
"type",
"(",
"ET",
... | Convert various representations of an XML structure to a etree Element
Args:
source -- The source object to be converted - ET.Element\ElementTree, dict or string.
Keyword args:
root_tag -- A optional parent tag in which to wrap the xml tree if no root in dict representation.
See dict_to_etree()
Returns:
A etree Element matching the source object.
>>> to_etree("<content/>") #doctest: +ELLIPSIS
<Element content at 0x...>
>>> to_etree({'document': {'title': 'foo', 'list': [{'li':1}, {'li':2}]}}) #doctest: +ELLIPSIS
<Element document at 0x...>
>>> to_etree(ET.Element('root')) #doctest: +ELLIPSIS
<Element root at 0x...> | [
"Convert",
"various",
"representations",
"of",
"an",
"XML",
"structure",
"to",
"a",
"etree",
"Element"
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/converters.py#L141-L175 |
clusterpoint/python-client-api | pycps/converters.py | to_raw_xml | def to_raw_xml(source):
""" Convert various representations of an XML structure to a normal XML string.
Args:
source -- The source object to be converted - ET.Element, dict or string.
Returns:
A rew xml string matching the source object.
>>> to_raw_xml("<content/>")
'<content/>'
>>> to_raw_xml({'document': {'title': 'foo', 'list': [{'li':1}, {'li':2}]}})
'<document><list><li>1</li><li>2</li></list><title>foo</title></document>'
>>> to_raw_xml(ET.Element('root'))
'<root/>'
"""
if isinstance(source, basestring):
return source
elif hasattr(source, 'getiterator'): # Element or ElementTree.
return ET.tostring(source, encoding="utf-8")
elif hasattr(source, 'keys'): # Dict.
xml_root = dict_to_etree(source)
return ET.tostring(xml_root, encoding="utf-8")
else:
raise TypeError("Accepted representations of a document are string, dict and etree") | python | def to_raw_xml(source):
""" Convert various representations of an XML structure to a normal XML string.
Args:
source -- The source object to be converted - ET.Element, dict or string.
Returns:
A rew xml string matching the source object.
>>> to_raw_xml("<content/>")
'<content/>'
>>> to_raw_xml({'document': {'title': 'foo', 'list': [{'li':1}, {'li':2}]}})
'<document><list><li>1</li><li>2</li></list><title>foo</title></document>'
>>> to_raw_xml(ET.Element('root'))
'<root/>'
"""
if isinstance(source, basestring):
return source
elif hasattr(source, 'getiterator'): # Element or ElementTree.
return ET.tostring(source, encoding="utf-8")
elif hasattr(source, 'keys'): # Dict.
xml_root = dict_to_etree(source)
return ET.tostring(xml_root, encoding="utf-8")
else:
raise TypeError("Accepted representations of a document are string, dict and etree") | [
"def",
"to_raw_xml",
"(",
"source",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"basestring",
")",
":",
"return",
"source",
"elif",
"hasattr",
"(",
"source",
",",
"'getiterator'",
")",
":",
"# Element or ElementTree.",
"return",
"ET",
".",
"tostring",
... | Convert various representations of an XML structure to a normal XML string.
Args:
source -- The source object to be converted - ET.Element, dict or string.
Returns:
A rew xml string matching the source object.
>>> to_raw_xml("<content/>")
'<content/>'
>>> to_raw_xml({'document': {'title': 'foo', 'list': [{'li':1}, {'li':2}]}})
'<document><list><li>1</li><li>2</li></list><title>foo</title></document>'
>>> to_raw_xml(ET.Element('root'))
'<root/>' | [
"Convert",
"various",
"representations",
"of",
"an",
"XML",
"structure",
"to",
"a",
"normal",
"XML",
"string",
"."
] | train | https://github.com/clusterpoint/python-client-api/blob/fabf9bd8355aa54ba08fd6649e48f16e2c35eacd/pycps/converters.py#L178-L204 |
zhexiao/ezhost | ezhost/main.py | main | def main():
"""
Check args
"""
configure_obj = None
parser = argparse.ArgumentParser(description='自动化安装')
parser.add_argument(
'-s', '--server',
help='服务器代替名',
)
parser.add_argument(
'-ba', '--bigdata-app',
help='大数据服务应用替代名',
)
parser.add_argument(
'-add-slave', '--add-slave',
help='添加一个子节点服务器',
)
parser.add_argument(
'-skip-master', '--skip-master',
dest='skip_master',
action='store_true',
help='跳过master服务器的安装过程',
)
# force to install packages without ask question
parser.add_argument(
'-f', '--force',
dest='force',
action='store_true',
help='不询问是否安装',
)
parser.add_argument(
'-nf', '--not-force',
dest='force',
action='store_false',
help='询问是否安装',
)
parser.set_defaults(force=False)
# login to remote mysql, default is false
parser.add_argument(
'-my', '--mysql',
dest='login_mysql',
action='store_true',
help='登录到Mysql数据库',
)
parser.set_defaults(login_mysql=False)
# login to server
parser.add_argument(
'-login', '--login',
dest='login_server',
action='store_true',
help='登录到远程服务器',
)
parser.set_defaults(login_server=False)
parser.add_argument(
'-p', '--project',
help='项目名称,默认是demo',
default='demo'
)
parser.add_argument(
'-gp', '--git-pull',
help='Github项目的保存目录',
)
parser.add_argument(
'-C', '--config',
help='配置文件路径',
nargs=2
)
parser.add_argument(
'-H', '--host',
help='客户机地址',
)
parser.add_argument(
'-U', '--user',
help='客户机用户名',
)
parser.add_argument(
'-P', '--passwd',
help='客户机登录密码',
)
parser.add_argument(
'-K', '--keyfile',
help='客户机SSH KEY的路径',
)
parser.add_argument(
'-ap', '--active-port',
help='客户机已经开启的端口',
action='store_true'
)
args = parser.parse_args()
# if config file and host both not provide, throw a error
if args.config is None and args.host is None:
raise ValueError('缺少配置文件-C(--config)或客户机地址-H(--host)')
# check user and passwd
if args.host is not None:
if (args.user and (args.passwd or args.keyfile)) is None:
raise ValueError('缺少登录必要的信息')
# if exist config file, read configuration from file
configure = None
if args.config is not None:
# init configuration parser
configure = configparser.ConfigParser()
configure.read(args.config[0])
config_sections = configure.sections()
# check key exist
if args.config[1] not in config_sections:
raise KeyError('未找到与{0}对应的登录配置文件,存在的配置文件为{1}'
.format(args.config[1], config_sections))
configure_obj = configure[args.config[1]]
# init server
ServerBase(
args, configure_obj,
configure=configure
) | python | def main():
"""
Check args
"""
configure_obj = None
parser = argparse.ArgumentParser(description='自动化安装')
parser.add_argument(
'-s', '--server',
help='服务器代替名',
)
parser.add_argument(
'-ba', '--bigdata-app',
help='大数据服务应用替代名',
)
parser.add_argument(
'-add-slave', '--add-slave',
help='添加一个子节点服务器',
)
parser.add_argument(
'-skip-master', '--skip-master',
dest='skip_master',
action='store_true',
help='跳过master服务器的安装过程',
)
# force to install packages without ask question
parser.add_argument(
'-f', '--force',
dest='force',
action='store_true',
help='不询问是否安装',
)
parser.add_argument(
'-nf', '--not-force',
dest='force',
action='store_false',
help='询问是否安装',
)
parser.set_defaults(force=False)
# login to remote mysql, default is false
parser.add_argument(
'-my', '--mysql',
dest='login_mysql',
action='store_true',
help='登录到Mysql数据库',
)
parser.set_defaults(login_mysql=False)
# login to server
parser.add_argument(
'-login', '--login',
dest='login_server',
action='store_true',
help='登录到远程服务器',
)
parser.set_defaults(login_server=False)
parser.add_argument(
'-p', '--project',
help='项目名称,默认是demo',
default='demo'
)
parser.add_argument(
'-gp', '--git-pull',
help='Github项目的保存目录',
)
parser.add_argument(
'-C', '--config',
help='配置文件路径',
nargs=2
)
parser.add_argument(
'-H', '--host',
help='客户机地址',
)
parser.add_argument(
'-U', '--user',
help='客户机用户名',
)
parser.add_argument(
'-P', '--passwd',
help='客户机登录密码',
)
parser.add_argument(
'-K', '--keyfile',
help='客户机SSH KEY的路径',
)
parser.add_argument(
'-ap', '--active-port',
help='客户机已经开启的端口',
action='store_true'
)
args = parser.parse_args()
# if config file and host both not provide, throw a error
if args.config is None and args.host is None:
raise ValueError('缺少配置文件-C(--config)或客户机地址-H(--host)')
# check user and passwd
if args.host is not None:
if (args.user and (args.passwd or args.keyfile)) is None:
raise ValueError('缺少登录必要的信息')
# if exist config file, read configuration from file
configure = None
if args.config is not None:
# init configuration parser
configure = configparser.ConfigParser()
configure.read(args.config[0])
config_sections = configure.sections()
# check key exist
if args.config[1] not in config_sections:
raise KeyError('未找到与{0}对应的登录配置文件,存在的配置文件为{1}'
.format(args.config[1], config_sections))
configure_obj = configure[args.config[1]]
# init server
ServerBase(
args, configure_obj,
configure=configure
) | [
"def",
"main",
"(",
")",
":",
"configure_obj",
"=",
"None",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'自动化安装')",
"",
"parser",
".",
"add_argument",
"(",
"'-s'",
",",
"'--server'",
",",
"help",
"=",
"'服务器代替名',",
"",
")",
... | Check args | [
"Check",
"args"
] | train | https://github.com/zhexiao/ezhost/blob/4146bc0be14bb1bfe98ec19283d19fab420871b3/ezhost/main.py#L16-L150 |
mozilla/socorrolib | socorrolib/lib/external_common.py | parse_arguments | def parse_arguments(filters, arguments, modern=False):
"""
Return a dict of parameters.
Take a list of filters and for each try to get the corresponding
value in arguments or a default value. Then check that value's type.
The @modern parameter indicates how the arguments should be
interpreted. The old way is that you always specify a list and in
the list you write the names of types as strings. I.e. instad of
`str` you write `'str'`.
The modern way allows you to specify arguments by real Python types
and entering it as a list means you accept and expect it to be a list.
For example, using the modern way:
filters = [
("param1", "default", [str]),
("param2", None, int),
("param3", ["list", "of", 4, "values"], [str])
]
arguments = {
"param1": "value1",
"unknown": 12345
}
=>
{
"param1": ["value1"],
"param2": 0,
"param3": ["list", "of", "4", "values"]
}
And an example for the old way:
filters = [
("param1", "default", ["list", "str"]),
("param2", None, "int"),
("param3", ["list", "of", 4, "values"], ["list", "str"])
]
arguments = {
"param1": "value1",
"unknown": 12345
}
=>
{
"param1": ["value1"],
"param2": 0,
"param3": ["list", "of", "4", "values"]
}
The reason for having the modern and the non-modern way is
transition of legacy code. One day it will all be the modern way.
"""
params = DotDict()
for i in filters:
count = len(i)
param = None
if count <= 1:
param = arguments.get(i[0])
else:
param = arguments.get(i[0], i[1])
# proceed and do the type checking
if count >= 3:
types = i[2]
if modern:
if isinstance(types, list) and param is not None:
assert len(types) == 1
if not isinstance(param, list):
param = [param]
param = [check_type(x, types[0]) for x in param]
else:
param = check_type(param, types)
else:
if not isinstance(types, list):
types = [types]
for t in reversed(types):
if t == "list" and not isinstance(param, list):
if param is None or param == '':
param = []
else:
param = [param]
elif t == "list" and isinstance(param, list):
continue
elif isinstance(param, list) and "list" not in types:
param = " ".join(param)
param = check_type(param, t)
elif isinstance(param, list):
param = [check_type(x, t) for x in param]
else:
param = check_type(param, t)
params[i[0]] = param
return params | python | def parse_arguments(filters, arguments, modern=False):
"""
Return a dict of parameters.
Take a list of filters and for each try to get the corresponding
value in arguments or a default value. Then check that value's type.
The @modern parameter indicates how the arguments should be
interpreted. The old way is that you always specify a list and in
the list you write the names of types as strings. I.e. instad of
`str` you write `'str'`.
The modern way allows you to specify arguments by real Python types
and entering it as a list means you accept and expect it to be a list.
For example, using the modern way:
filters = [
("param1", "default", [str]),
("param2", None, int),
("param3", ["list", "of", 4, "values"], [str])
]
arguments = {
"param1": "value1",
"unknown": 12345
}
=>
{
"param1": ["value1"],
"param2": 0,
"param3": ["list", "of", "4", "values"]
}
And an example for the old way:
filters = [
("param1", "default", ["list", "str"]),
("param2", None, "int"),
("param3", ["list", "of", 4, "values"], ["list", "str"])
]
arguments = {
"param1": "value1",
"unknown": 12345
}
=>
{
"param1": ["value1"],
"param2": 0,
"param3": ["list", "of", "4", "values"]
}
The reason for having the modern and the non-modern way is
transition of legacy code. One day it will all be the modern way.
"""
params = DotDict()
for i in filters:
count = len(i)
param = None
if count <= 1:
param = arguments.get(i[0])
else:
param = arguments.get(i[0], i[1])
# proceed and do the type checking
if count >= 3:
types = i[2]
if modern:
if isinstance(types, list) and param is not None:
assert len(types) == 1
if not isinstance(param, list):
param = [param]
param = [check_type(x, types[0]) for x in param]
else:
param = check_type(param, types)
else:
if not isinstance(types, list):
types = [types]
for t in reversed(types):
if t == "list" and not isinstance(param, list):
if param is None or param == '':
param = []
else:
param = [param]
elif t == "list" and isinstance(param, list):
continue
elif isinstance(param, list) and "list" not in types:
param = " ".join(param)
param = check_type(param, t)
elif isinstance(param, list):
param = [check_type(x, t) for x in param]
else:
param = check_type(param, t)
params[i[0]] = param
return params | [
"def",
"parse_arguments",
"(",
"filters",
",",
"arguments",
",",
"modern",
"=",
"False",
")",
":",
"params",
"=",
"DotDict",
"(",
")",
"for",
"i",
"in",
"filters",
":",
"count",
"=",
"len",
"(",
"i",
")",
"param",
"=",
"None",
"if",
"count",
"<=",
... | Return a dict of parameters.
Take a list of filters and for each try to get the corresponding
value in arguments or a default value. Then check that value's type.
The @modern parameter indicates how the arguments should be
interpreted. The old way is that you always specify a list and in
the list you write the names of types as strings. I.e. instad of
`str` you write `'str'`.
The modern way allows you to specify arguments by real Python types
and entering it as a list means you accept and expect it to be a list.
For example, using the modern way:
filters = [
("param1", "default", [str]),
("param2", None, int),
("param3", ["list", "of", 4, "values"], [str])
]
arguments = {
"param1": "value1",
"unknown": 12345
}
=>
{
"param1": ["value1"],
"param2": 0,
"param3": ["list", "of", "4", "values"]
}
And an example for the old way:
filters = [
("param1", "default", ["list", "str"]),
("param2", None, "int"),
("param3", ["list", "of", 4, "values"], ["list", "str"])
]
arguments = {
"param1": "value1",
"unknown": 12345
}
=>
{
"param1": ["value1"],
"param2": 0,
"param3": ["list", "of", "4", "values"]
}
The reason for having the modern and the non-modern way is
transition of legacy code. One day it will all be the modern way. | [
"Return",
"a",
"dict",
"of",
"parameters",
".",
"Take",
"a",
"list",
"of",
"filters",
"and",
"for",
"each",
"try",
"to",
"get",
"the",
"corresponding",
"value",
"in",
"arguments",
"or",
"a",
"default",
"value",
".",
"Then",
"check",
"that",
"value",
"s",... | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/external_common.py#L17-L107 |
mozilla/socorrolib | socorrolib/lib/external_common.py | check_type | def check_type(param, datatype):
"""
Make sure that param is of type datatype and return it.
If param is None, return it.
If param is an instance of datatype, return it.
If param is not an instance of datatype and is not None, cast it as
datatype and return it.
"""
if param is None:
return param
if getattr(datatype, 'clean', None) and callable(datatype.clean):
try:
return datatype.clean(param)
except ValueError:
raise BadArgumentError(param)
elif isinstance(datatype, str):
# You've given it something like `'bool'` as a string.
# This is the legacy way of doing it.
datatype = {
'str': str,
'bool': bool,
'float': float,
'date': datetime.date,
'datetime': datetime.datetime,
'timedelta': datetime.timedelta,
'json': 'json', # exception
'int': int,
}[datatype]
if datatype is str and not isinstance(param, basestring):
try:
param = str(param)
except ValueError:
param = str()
elif datatype is int and not isinstance(param, int):
try:
param = int(param)
except ValueError:
param = int()
elif datatype is bool and not isinstance(param, bool):
param = str(param).lower() in ("true", "t", "1", "y", "yes")
elif (
datatype is datetime.datetime and
not isinstance(param, datetime.datetime)
):
try:
param = dtutil.string_to_datetime(param)
except ValueError:
param = None
elif datatype is datetime.date and not isinstance(param, datetime.date):
try:
param = dtutil.string_to_datetime(param).date()
except ValueError:
param = None
elif (
datatype is datetime.timedelta and
not isinstance(param, datetime.timedelta)
):
try:
param = dtutil.strHoursToTimeDelta(param)
except ValueError:
param = None
elif datatype == "json" and isinstance(param, basestring):
try:
param = json.loads(param)
except ValueError:
param = None
return param | python | def check_type(param, datatype):
"""
Make sure that param is of type datatype and return it.
If param is None, return it.
If param is an instance of datatype, return it.
If param is not an instance of datatype and is not None, cast it as
datatype and return it.
"""
if param is None:
return param
if getattr(datatype, 'clean', None) and callable(datatype.clean):
try:
return datatype.clean(param)
except ValueError:
raise BadArgumentError(param)
elif isinstance(datatype, str):
# You've given it something like `'bool'` as a string.
# This is the legacy way of doing it.
datatype = {
'str': str,
'bool': bool,
'float': float,
'date': datetime.date,
'datetime': datetime.datetime,
'timedelta': datetime.timedelta,
'json': 'json', # exception
'int': int,
}[datatype]
if datatype is str and not isinstance(param, basestring):
try:
param = str(param)
except ValueError:
param = str()
elif datatype is int and not isinstance(param, int):
try:
param = int(param)
except ValueError:
param = int()
elif datatype is bool and not isinstance(param, bool):
param = str(param).lower() in ("true", "t", "1", "y", "yes")
elif (
datatype is datetime.datetime and
not isinstance(param, datetime.datetime)
):
try:
param = dtutil.string_to_datetime(param)
except ValueError:
param = None
elif datatype is datetime.date and not isinstance(param, datetime.date):
try:
param = dtutil.string_to_datetime(param).date()
except ValueError:
param = None
elif (
datatype is datetime.timedelta and
not isinstance(param, datetime.timedelta)
):
try:
param = dtutil.strHoursToTimeDelta(param)
except ValueError:
param = None
elif datatype == "json" and isinstance(param, basestring):
try:
param = json.loads(param)
except ValueError:
param = None
return param | [
"def",
"check_type",
"(",
"param",
",",
"datatype",
")",
":",
"if",
"param",
"is",
"None",
":",
"return",
"param",
"if",
"getattr",
"(",
"datatype",
",",
"'clean'",
",",
"None",
")",
"and",
"callable",
"(",
"datatype",
".",
"clean",
")",
":",
"try",
... | Make sure that param is of type datatype and return it.
If param is None, return it.
If param is an instance of datatype, return it.
If param is not an instance of datatype and is not None, cast it as
datatype and return it. | [
"Make",
"sure",
"that",
"param",
"is",
"of",
"type",
"datatype",
"and",
"return",
"it",
".",
"If",
"param",
"is",
"None",
"return",
"it",
".",
"If",
"param",
"is",
"an",
"instance",
"of",
"datatype",
"return",
"it",
".",
"If",
"param",
"is",
"not",
"... | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/external_common.py#L110-L186 |
ShawnClake/Apitax | apitax/ah/api/controllers/any_controller.py | authenticate | def authenticate(user=None): # noqa: E501
"""Authenticate
Authenticate with the API # noqa: E501
:param user: The user authentication object.
:type user: dict | bytes
:rtype: UserAuth
"""
if connexion.request.is_json:
user = UserAuth.from_dict(connexion.request.get_json()) # noqa: E501
credentials = mapUserAuthToCredentials(user)
auth = ApitaxAuthentication.login(credentials)
if(not auth):
return ErrorResponse(status=401, message="Invalid credentials")
access_token = create_access_token(identity={'username': user.username, 'role': auth['role']})
refresh_token = create_refresh_token(identity={'username': user.username, 'role': auth['role']})
return AuthResponse(status=201, message='User ' + user.username + ' was authenticated as ' + auth['role'], access_token=access_token, refresh_token=refresh_token, auth=UserAuth(username=auth['credentials'].username, api_token=auth['credentials'].token)) | python | def authenticate(user=None): # noqa: E501
"""Authenticate
Authenticate with the API # noqa: E501
:param user: The user authentication object.
:type user: dict | bytes
:rtype: UserAuth
"""
if connexion.request.is_json:
user = UserAuth.from_dict(connexion.request.get_json()) # noqa: E501
credentials = mapUserAuthToCredentials(user)
auth = ApitaxAuthentication.login(credentials)
if(not auth):
return ErrorResponse(status=401, message="Invalid credentials")
access_token = create_access_token(identity={'username': user.username, 'role': auth['role']})
refresh_token = create_refresh_token(identity={'username': user.username, 'role': auth['role']})
return AuthResponse(status=201, message='User ' + user.username + ' was authenticated as ' + auth['role'], access_token=access_token, refresh_token=refresh_token, auth=UserAuth(username=auth['credentials'].username, api_token=auth['credentials'].token)) | [
"def",
"authenticate",
"(",
"user",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"user",
"=",
"UserAuth",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501",
... | Authenticate
Authenticate with the API # noqa: E501
:param user: The user authentication object.
:type user: dict | bytes
:rtype: UserAuth | [
"Authenticate"
] | train | https://github.com/ShawnClake/Apitax/blob/2eb9c6990d4088b2503c7f13c2a76f8e59606e6d/apitax/ah/api/controllers/any_controller.py#L16-L37 |
salesking/salesking_python_sdk | salesking/utils/resolver.py | LocalRefResolver.resolve_local | def resolve_local(self, uri, base_uri, ref):
"""
Resolve a local ``uri``.
Does not check the store first.
:argument str uri: the URI to resolve
:returns: the retrieved document
"""
# read it from the filesystem
file_path = None
# make the reference saleskingstyle
item_name = None
if (uri.startswith(u"file") or
uri.startswith(u"File")):
if ref.startswith(u"./"):
ref = ref.split(u"./")[-1]
org_ref = ref
if ref.find(u"#properties") != -1:
ref = ref.split(u"#properties")[0]
if ref.find(u".json") != -1:
item_name = ref.split(u".json")[0]
# on windwos systesm this needs to happen
if base_uri.startswith(u"file://") is True:
base_uri = base_uri.split(u"file://")[1]
elif base_uri.startswith(u"File://") is True:
base_uri = base_uri.split(u"File://")[1]
file_path = os.path.join(base_uri, ref)
result = None
try:
schema_file = open(file_path, "r").read()
result = json.loads(schema_file.decode("utf-8"))
except IOError as e:
log.error(u"file not found %s" % e)
msg = "Could not find schema file. %s" % file_path
raise SalesKingException("SCHEMA_NOT_FOUND", msg)
if self.cache_remote:
self.store[uri] = result
return result | python | def resolve_local(self, uri, base_uri, ref):
"""
Resolve a local ``uri``.
Does not check the store first.
:argument str uri: the URI to resolve
:returns: the retrieved document
"""
# read it from the filesystem
file_path = None
# make the reference saleskingstyle
item_name = None
if (uri.startswith(u"file") or
uri.startswith(u"File")):
if ref.startswith(u"./"):
ref = ref.split(u"./")[-1]
org_ref = ref
if ref.find(u"#properties") != -1:
ref = ref.split(u"#properties")[0]
if ref.find(u".json") != -1:
item_name = ref.split(u".json")[0]
# on windwos systesm this needs to happen
if base_uri.startswith(u"file://") is True:
base_uri = base_uri.split(u"file://")[1]
elif base_uri.startswith(u"File://") is True:
base_uri = base_uri.split(u"File://")[1]
file_path = os.path.join(base_uri, ref)
result = None
try:
schema_file = open(file_path, "r").read()
result = json.loads(schema_file.decode("utf-8"))
except IOError as e:
log.error(u"file not found %s" % e)
msg = "Could not find schema file. %s" % file_path
raise SalesKingException("SCHEMA_NOT_FOUND", msg)
if self.cache_remote:
self.store[uri] = result
return result | [
"def",
"resolve_local",
"(",
"self",
",",
"uri",
",",
"base_uri",
",",
"ref",
")",
":",
"# read it from the filesystem",
"file_path",
"=",
"None",
"# make the reference saleskingstyle",
"item_name",
"=",
"None",
"if",
"(",
"uri",
".",
"startswith",
"(",
"u\"file\"... | Resolve a local ``uri``.
Does not check the store first.
:argument str uri: the URI to resolve
:returns: the retrieved document | [
"Resolve",
"a",
"local",
"uri",
".",
"Does",
"not",
"check",
"the",
"store",
"first",
"."
] | train | https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/utils/resolver.py#L32-L73 |
salesking/salesking_python_sdk | salesking/utils/resolver.py | LocalRefResolver.resolving | def resolving(self, ref):
"""
Context manager which resolves a JSON ``ref`` and enters the
resolution scope of this ref.
:argument str ref: reference to resolve
"""
# print u"resol_scope: %s, ref: %s" % (self.resolution_scope, ref)
full_uri = urljoin(self.resolution_scope, ref)
uri, fragment = urldefrag(full_uri)
if not uri:
uri = self.base_uri
if uri in self.store:
document = self.store[uri]
else:
if (uri.startswith(u"file") or uri.startswith(u"File")):
try:
document = self.resolve_local(full_uri, self.resolution_scope, ref)
except Exception as exc:
raise RefResolutionError(exc)
else:
try:
document = self.resolve_remote(uri)
except Exception as exc:
raise RefResolutionError(exc)
old_base_uri, self.base_uri = self.base_uri, uri
try:
with self.in_scope(uri):
yield self.resolve_fragment(document, fragment)
finally:
self.base_uri = old_base_uri | python | def resolving(self, ref):
"""
Context manager which resolves a JSON ``ref`` and enters the
resolution scope of this ref.
:argument str ref: reference to resolve
"""
# print u"resol_scope: %s, ref: %s" % (self.resolution_scope, ref)
full_uri = urljoin(self.resolution_scope, ref)
uri, fragment = urldefrag(full_uri)
if not uri:
uri = self.base_uri
if uri in self.store:
document = self.store[uri]
else:
if (uri.startswith(u"file") or uri.startswith(u"File")):
try:
document = self.resolve_local(full_uri, self.resolution_scope, ref)
except Exception as exc:
raise RefResolutionError(exc)
else:
try:
document = self.resolve_remote(uri)
except Exception as exc:
raise RefResolutionError(exc)
old_base_uri, self.base_uri = self.base_uri, uri
try:
with self.in_scope(uri):
yield self.resolve_fragment(document, fragment)
finally:
self.base_uri = old_base_uri | [
"def",
"resolving",
"(",
"self",
",",
"ref",
")",
":",
"# print u\"resol_scope: %s, ref: %s\" % (self.resolution_scope, ref)",
"full_uri",
"=",
"urljoin",
"(",
"self",
".",
"resolution_scope",
",",
"ref",
")",
"uri",
",",
"fragment",
"=",
"urldefrag",
"(",
"full_uri... | Context manager which resolves a JSON ``ref`` and enters the
resolution scope of this ref.
:argument str ref: reference to resolve | [
"Context",
"manager",
"which",
"resolves",
"a",
"JSON",
"ref",
"and",
"enters",
"the",
"resolution",
"scope",
"of",
"this",
"ref",
"."
] | train | https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/utils/resolver.py#L77-L111 |
cloudboss/friend | friend/utils.py | cached | def cached(func):
"""
A decorator function to cache values. It uses the decorated
function's arguments as the keys to determine if the function
has been called previously.
"""
cache = {}
@f.wraps(func)
def wrapper(*args, **kwargs):
key = func.__name__ + str(sorted(args)) + str(sorted(kwargs.items()))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper | python | def cached(func):
"""
A decorator function to cache values. It uses the decorated
function's arguments as the keys to determine if the function
has been called previously.
"""
cache = {}
@f.wraps(func)
def wrapper(*args, **kwargs):
key = func.__name__ + str(sorted(args)) + str(sorted(kwargs.items()))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper | [
"def",
"cached",
"(",
"func",
")",
":",
"cache",
"=",
"{",
"}",
"@",
"f",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"func",
".",
"__name__",
"+",
"str",
"(",
"sorted",
"... | A decorator function to cache values. It uses the decorated
function's arguments as the keys to determine if the function
has been called previously. | [
"A",
"decorator",
"function",
"to",
"cache",
"values",
".",
"It",
"uses",
"the",
"decorated",
"function",
"s",
"arguments",
"as",
"the",
"keys",
"to",
"determine",
"if",
"the",
"function",
"has",
"been",
"called",
"previously",
"."
] | train | https://github.com/cloudboss/friend/blob/3357e6ec849552e3ae9ed28017ff0926e4006e4e/friend/utils.py#L40-L54 |
cloudboss/friend | friend/utils.py | retry_wait_time | def retry_wait_time(attempt, cap):
"""
Determine a retry wait time based on the number of the
retry attempt and a cap on the wait time. The wait time
uses an exponential backoff with a random jitter.
The algorithm used is explained at
https://www.awsarchitectureblog.com/2015/03/backoff.html.
:param int attempt: The number of the attempt
:param int cap: A cap on the wait time in milliseconds
:returns: The number of milliseconds to wait
:rtype: int
"""
base = 100
max_wait = min(cap, base * (2 ** attempt))
return random.choice(range(0, max_wait)) | python | def retry_wait_time(attempt, cap):
"""
Determine a retry wait time based on the number of the
retry attempt and a cap on the wait time. The wait time
uses an exponential backoff with a random jitter.
The algorithm used is explained at
https://www.awsarchitectureblog.com/2015/03/backoff.html.
:param int attempt: The number of the attempt
:param int cap: A cap on the wait time in milliseconds
:returns: The number of milliseconds to wait
:rtype: int
"""
base = 100
max_wait = min(cap, base * (2 ** attempt))
return random.choice(range(0, max_wait)) | [
"def",
"retry_wait_time",
"(",
"attempt",
",",
"cap",
")",
":",
"base",
"=",
"100",
"max_wait",
"=",
"min",
"(",
"cap",
",",
"base",
"*",
"(",
"2",
"**",
"attempt",
")",
")",
"return",
"random",
".",
"choice",
"(",
"range",
"(",
"0",
",",
"max_wait... | Determine a retry wait time based on the number of the
retry attempt and a cap on the wait time. The wait time
uses an exponential backoff with a random jitter.
The algorithm used is explained at
https://www.awsarchitectureblog.com/2015/03/backoff.html.
:param int attempt: The number of the attempt
:param int cap: A cap on the wait time in milliseconds
:returns: The number of milliseconds to wait
:rtype: int | [
"Determine",
"a",
"retry",
"wait",
"time",
"based",
"on",
"the",
"number",
"of",
"the",
"retry",
"attempt",
"and",
"a",
"cap",
"on",
"the",
"wait",
"time",
".",
"The",
"wait",
"time",
"uses",
"an",
"exponential",
"backoff",
"with",
"a",
"random",
"jitter... | train | https://github.com/cloudboss/friend/blob/3357e6ec849552e3ae9ed28017ff0926e4006e4e/friend/utils.py#L57-L72 |
cloudboss/friend | friend/utils.py | retry_ex | def retry_ex(callback, times=3, cap=120000):
"""
Retry a callback function if any exception is raised.
:param function callback: The function to call
:keyword int times: Number of times to retry on initial failure
:keyword int cap: Maximum wait time in milliseconds
:returns: The return value of the callback
:raises Exception: If the callback raises an exception after
exhausting all retries
"""
for attempt in range(times + 1):
if attempt > 0:
time.sleep(retry_wait_time(attempt, cap) / 1000.0)
try:
return callback()
except:
if attempt == times:
raise | python | def retry_ex(callback, times=3, cap=120000):
"""
Retry a callback function if any exception is raised.
:param function callback: The function to call
:keyword int times: Number of times to retry on initial failure
:keyword int cap: Maximum wait time in milliseconds
:returns: The return value of the callback
:raises Exception: If the callback raises an exception after
exhausting all retries
"""
for attempt in range(times + 1):
if attempt > 0:
time.sleep(retry_wait_time(attempt, cap) / 1000.0)
try:
return callback()
except:
if attempt == times:
raise | [
"def",
"retry_ex",
"(",
"callback",
",",
"times",
"=",
"3",
",",
"cap",
"=",
"120000",
")",
":",
"for",
"attempt",
"in",
"range",
"(",
"times",
"+",
"1",
")",
":",
"if",
"attempt",
">",
"0",
":",
"time",
".",
"sleep",
"(",
"retry_wait_time",
"(",
... | Retry a callback function if any exception is raised.
:param function callback: The function to call
:keyword int times: Number of times to retry on initial failure
:keyword int cap: Maximum wait time in milliseconds
:returns: The return value of the callback
:raises Exception: If the callback raises an exception after
exhausting all retries | [
"Retry",
"a",
"callback",
"function",
"if",
"any",
"exception",
"is",
"raised",
"."
] | train | https://github.com/cloudboss/friend/blob/3357e6ec849552e3ae9ed28017ff0926e4006e4e/friend/utils.py#L75-L93 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.