repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
b3j0f/utils
b3j0f/utils/property.py
firsts
def firsts(properties): """ Transform a dictionary of {name: [(elt, value)+]} (resulting from get_properties) to a dictionary of {name, value} where names are first encountered in input properties. :param dict properties: properties to firsts. :return: dictionary of parameter values by ...
python
def firsts(properties): """ Transform a dictionary of {name: [(elt, value)+]} (resulting from get_properties) to a dictionary of {name, value} where names are first encountered in input properties. :param dict properties: properties to firsts. :return: dictionary of parameter values by ...
[ "def", "firsts", "(", "properties", ")", ":", "result", "=", "{", "}", "# parse elts", "for", "name", "in", "properties", ":", "elt_properties", "=", "properties", "[", "name", "]", "# add property values in result[name]", "result", "[", "name", "]", "=", "elt...
Transform a dictionary of {name: [(elt, value)+]} (resulting from get_properties) to a dictionary of {name, value} where names are first encountered in input properties. :param dict properties: properties to firsts. :return: dictionary of parameter values by names. :rtype: dict
[ "Transform", "a", "dictionary", "of", "{", "name", ":", "[", "(", "elt", "value", ")", "+", "]", "}", "(", "resulting", "from", "get_properties", ")", "to", "a", "dictionary", "of", "{", "name", "value", "}", "where", "names", "are", "first", "encounte...
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L638-L657
b3j0f/utils
b3j0f/utils/property.py
remove_ctx
def remove_ctx(properties): """ Transform a dictionary of {name: [(elt, value)+]} into a dictionary of {name: [value+]}. :param dict properties: properties from where get only values. :return: dictionary of parameter values by names. :rtype: dict """ result = {} for name in pro...
python
def remove_ctx(properties): """ Transform a dictionary of {name: [(elt, value)+]} into a dictionary of {name: [value+]}. :param dict properties: properties from where get only values. :return: dictionary of parameter values by names. :rtype: dict """ result = {} for name in pro...
[ "def", "remove_ctx", "(", "properties", ")", ":", "result", "=", "{", "}", "for", "name", "in", "properties", ":", "elt_properties", "=", "properties", "[", "name", "]", "result", "[", "name", "]", "=", "[", "]", "for", "_", ",", "value", "in", "elt_...
Transform a dictionary of {name: [(elt, value)+]} into a dictionary of {name: [value+]}. :param dict properties: properties from where get only values. :return: dictionary of parameter values by names. :rtype: dict
[ "Transform", "a", "dictionary", "of", "{", "name", ":", "[", "(", "elt", "value", ")", "+", "]", "}", "into", "a", "dictionary", "of", "{", "name", ":", "[", "value", "+", "]", "}", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L660-L677
b3j0f/utils
b3j0f/utils/property.py
setdefault
def setdefault(elt, key, default, ctx=None): """ Get a local property and create default value if local property does not exist. :param elt: local proprety elt to get/create. Not None methods. :param str key: proprety name. :param default: property value to set if key no in local properties...
python
def setdefault(elt, key, default, ctx=None): """ Get a local property and create default value if local property does not exist. :param elt: local proprety elt to get/create. Not None methods. :param str key: proprety name. :param default: property value to set if key no in local properties...
[ "def", "setdefault", "(", "elt", ",", "key", ",", "default", ",", "ctx", "=", "None", ")", ":", "result", "=", "default", "# get the best context", "if", "ctx", "is", "None", ":", "ctx", "=", "find_ctx", "(", "elt", "=", "elt", ")", "# get elt properties...
Get a local property and create default value if local property does not exist. :param elt: local proprety elt to get/create. Not None methods. :param str key: proprety name. :param default: property value to set if key no in local properties. :return: property value or default if property doe...
[ "Get", "a", "local", "property", "and", "create", "default", "value", "if", "local", "property", "does", "not", "exist", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L680-L708
b3j0f/utils
b3j0f/utils/property.py
addproperties
def addproperties( names, bfget=None, afget=None, enableget=True, bfset=None, afset=None, enableset=True, bfdel=None, afdel=None, enabledel=True ): """Decorator in charge of adding python properties to cls. {a/b}fget, {a/b}fset and {a/b}fdel are applied to all properties matchin...
python
def addproperties( names, bfget=None, afget=None, enableget=True, bfset=None, afset=None, enableset=True, bfdel=None, afdel=None, enabledel=True ): """Decorator in charge of adding python properties to cls. {a/b}fget, {a/b}fset and {a/b}fdel are applied to all properties matchin...
[ "def", "addproperties", "(", "names", ",", "bfget", "=", "None", ",", "afget", "=", "None", ",", "enableget", "=", "True", ",", "bfset", "=", "None", ",", "afset", "=", "None", ",", "enableset", "=", "True", ",", "bfdel", "=", "None", ",", "afdel", ...
Decorator in charge of adding python properties to cls. {a/b}fget, {a/b}fset and {a/b}fdel are applied to all properties matching names in taking care to not forget default/existing properties. The prefixes *a* and *b* are respectively for after and before default/existing property getter/setter/delete...
[ "Decorator", "in", "charge", "of", "adding", "python", "properties", "to", "cls", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L722-L943
benjaoming/simple-pypi-statistics
simple_pypi_statistics/api.py
get_jsonparsed_data
def get_jsonparsed_data(url): """Receive the content of ``url``, parse it as JSON and return the object. """ response = urlopen(url) data = response.read().decode('utf-8') return json.loads(data)
python
def get_jsonparsed_data(url): """Receive the content of ``url``, parse it as JSON and return the object. """ response = urlopen(url) data = response.read().decode('utf-8') return json.loads(data)
[ "def", "get_jsonparsed_data", "(", "url", ")", ":", "response", "=", "urlopen", "(", "url", ")", "data", "=", "response", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "return", "json", ".", "loads", "(", "data", ")" ]
Receive the content of ``url``, parse it as JSON and return the object.
[ "Receive", "the", "content", "of", "url", "parse", "it", "as", "JSON", "and", "return", "the", "object", "." ]
train
https://github.com/benjaoming/simple-pypi-statistics/blob/de93b94877004ae18a5c8e5b96b213aa38fb29a8/simple_pypi_statistics/api.py#L90-L96
benjaoming/simple-pypi-statistics
simple_pypi_statistics/api.py
get_stats
def get_stats(package): """ Fetch raw statistics of a package, no corrections are made to this data. You should use get_corrected_stats(). """ grand_total = 0 if '==' in package: package, version = package.split('==') try: package = normalize(package) version = None...
python
def get_stats(package): """ Fetch raw statistics of a package, no corrections are made to this data. You should use get_corrected_stats(). """ grand_total = 0 if '==' in package: package, version = package.split('==') try: package = normalize(package) version = None...
[ "def", "get_stats", "(", "package", ")", ":", "grand_total", "=", "0", "if", "'=='", "in", "package", ":", "package", ",", "version", "=", "package", ".", "split", "(", "'=='", ")", "try", ":", "package", "=", "normalize", "(", "package", ")", "version...
Fetch raw statistics of a package, no corrections are made to this data. You should use get_corrected_stats().
[ "Fetch", "raw", "statistics", "of", "a", "package", "no", "corrections", "are", "made", "to", "this", "data", ".", "You", "should", "use", "get_corrected_stats", "()", "." ]
train
https://github.com/benjaoming/simple-pypi-statistics/blob/de93b94877004ae18a5c8e5b96b213aa38fb29a8/simple_pypi_statistics/api.py#L158-L188
benjaoming/simple-pypi-statistics
simple_pypi_statistics/api.py
get_corrected_stats
def get_corrected_stats(package, use_honeypot=True): """ Fetches statistics for `package` and then corrects them using a special honeypot. """ honeypot, __, __ = get_stats('python-bogus-project-honeypot') if not honeypot: raise RuntimeError("Could not get honeypot data") honeypot ...
python
def get_corrected_stats(package, use_honeypot=True): """ Fetches statistics for `package` and then corrects them using a special honeypot. """ honeypot, __, __ = get_stats('python-bogus-project-honeypot') if not honeypot: raise RuntimeError("Could not get honeypot data") honeypot ...
[ "def", "get_corrected_stats", "(", "package", ",", "use_honeypot", "=", "True", ")", ":", "honeypot", ",", "__", ",", "__", "=", "get_stats", "(", "'python-bogus-project-honeypot'", ")", "if", "not", "honeypot", ":", "raise", "RuntimeError", "(", "\"Could not ge...
Fetches statistics for `package` and then corrects them using a special honeypot.
[ "Fetches", "statistics", "for", "package", "and", "then", "corrects", "them", "using", "a", "special", "honeypot", "." ]
train
https://github.com/benjaoming/simple-pypi-statistics/blob/de93b94877004ae18a5c8e5b96b213aa38fb29a8/simple_pypi_statistics/api.py#L191-L233
kejbaly2/members
members/facebook_group.py
extract
def extract(group_id, access_token, fields=None): ''' FIXME: DOCS... Links: * https://developers.facebook.com/tools/explorer/ ''' fields = fields or ['id', 'owner', 'email', 'name', 'members'] # TEST that fields are a subset of valid fields assert set(fields).issubset(VALID_FIELDS) ...
python
def extract(group_id, access_token, fields=None): ''' FIXME: DOCS... Links: * https://developers.facebook.com/tools/explorer/ ''' fields = fields or ['id', 'owner', 'email', 'name', 'members'] # TEST that fields are a subset of valid fields assert set(fields).issubset(VALID_FIELDS) ...
[ "def", "extract", "(", "group_id", ",", "access_token", ",", "fields", "=", "None", ")", ":", "fields", "=", "fields", "or", "[", "'id'", ",", "'owner'", ",", "'email'", ",", "'name'", ",", "'members'", "]", "# TEST that fields are a subset of valid fields", "...
FIXME: DOCS... Links: * https://developers.facebook.com/tools/explorer/
[ "FIXME", ":", "DOCS", "...", "Links", ":", "*", "https", ":", "//", "developers", ".", "facebook", ".", "com", "/", "tools", "/", "explorer", "/" ]
train
https://github.com/kejbaly2/members/blob/28e70a25cceade514c550e3ce9963f73167e8572/members/facebook_group.py#L26-L53
foxx/python-helpful
helpful.py
unique_iter
def unique_iter(seq): """ See http://www.peterbe.com/plog/uniqifiers-benchmark Originally f8 written by Dave Kirby """ seen = set() return [x for x in seq if x not in seen and not seen.add(x)]
python
def unique_iter(seq): """ See http://www.peterbe.com/plog/uniqifiers-benchmark Originally f8 written by Dave Kirby """ seen = set() return [x for x in seq if x not in seen and not seen.add(x)]
[ "def", "unique_iter", "(", "seq", ")", ":", "seen", "=", "set", "(", ")", "return", "[", "x", "for", "x", "in", "seq", "if", "x", "not", "in", "seen", "and", "not", "seen", ".", "add", "(", "x", ")", "]" ]
See http://www.peterbe.com/plog/uniqifiers-benchmark Originally f8 written by Dave Kirby
[ "See", "http", ":", "//", "www", ".", "peterbe", ".", "com", "/", "plog", "/", "uniqifiers", "-", "benchmark", "Originally", "f8", "written", "by", "Dave", "Kirby" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L55-L61
foxx/python-helpful
helpful.py
ensure_subclass
def ensure_subclass(value, types): """ Ensure value is a subclass of types >>> class Hello(object): pass >>> ensure_subclass(Hello, Hello) >>> ensure_subclass(object, Hello) Traceback (most recent call last): TypeError: """ ensure_class(value) if not issubclass(value, types): ...
python
def ensure_subclass(value, types): """ Ensure value is a subclass of types >>> class Hello(object): pass >>> ensure_subclass(Hello, Hello) >>> ensure_subclass(object, Hello) Traceback (most recent call last): TypeError: """ ensure_class(value) if not issubclass(value, types): ...
[ "def", "ensure_subclass", "(", "value", ",", "types", ")", ":", "ensure_class", "(", "value", ")", "if", "not", "issubclass", "(", "value", ",", "types", ")", ":", "raise", "TypeError", "(", "\"expected subclass of {}, not {}\"", ".", "format", "(", "types", ...
Ensure value is a subclass of types >>> class Hello(object): pass >>> ensure_subclass(Hello, Hello) >>> ensure_subclass(object, Hello) Traceback (most recent call last): TypeError:
[ "Ensure", "value", "is", "a", "subclass", "of", "types" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L157-L171
foxx/python-helpful
helpful.py
ensure_instance
def ensure_instance(value, types): """ Ensure value is an instance of a certain type >>> ensure_instance(1, [str]) Traceback (most recent call last): TypeError: >>> ensure_instance(1, str) Traceback (most recent call last): TypeError: >>> ensure_instance(1, int) >>> ensure_ins...
python
def ensure_instance(value, types): """ Ensure value is an instance of a certain type >>> ensure_instance(1, [str]) Traceback (most recent call last): TypeError: >>> ensure_instance(1, str) Traceback (most recent call last): TypeError: >>> ensure_instance(1, int) >>> ensure_ins...
[ "def", "ensure_instance", "(", "value", ",", "types", ")", ":", "if", "not", "isinstance", "(", "value", ",", "types", ")", ":", "raise", "TypeError", "(", "\"expected instance of {}, got {}\"", ".", "format", "(", "types", ",", "value", ")", ")" ]
Ensure value is an instance of a certain type >>> ensure_instance(1, [str]) Traceback (most recent call last): TypeError: >>> ensure_instance(1, str) Traceback (most recent call last): TypeError: >>> ensure_instance(1, int) >>> ensure_instance(1, (int, str)) :attr types: Type of ...
[ "Ensure", "value", "is", "an", "instance", "of", "a", "certain", "type" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L173-L193
foxx/python-helpful
helpful.py
iter_ensure_instance
def iter_ensure_instance(iterable, types): """ Iterate over object and check each item type >>> iter_ensure_instance([1,2,3], [str]) Traceback (most recent call last): TypeError: >>> iter_ensure_instance([1,2,3], int) >>> iter_ensure_instance(1, int) Traceback (most recent call last): ...
python
def iter_ensure_instance(iterable, types): """ Iterate over object and check each item type >>> iter_ensure_instance([1,2,3], [str]) Traceback (most recent call last): TypeError: >>> iter_ensure_instance([1,2,3], int) >>> iter_ensure_instance(1, int) Traceback (most recent call last): ...
[ "def", "iter_ensure_instance", "(", "iterable", ",", "types", ")", ":", "ensure_instance", "(", "iterable", ",", "Iterable", ")", "[", "ensure_instance", "(", "item", ",", "types", ")", "for", "item", "in", "iterable", "]" ]
Iterate over object and check each item type >>> iter_ensure_instance([1,2,3], [str]) Traceback (most recent call last): TypeError: >>> iter_ensure_instance([1,2,3], int) >>> iter_ensure_instance(1, int) Traceback (most recent call last): TypeError:
[ "Iterate", "over", "object", "and", "check", "each", "item", "type" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L196-L209
foxx/python-helpful
helpful.py
import_recursive
def import_recursive(path): """ Recursively import all modules and packages Thanks http://stackoverflow.com/a/25562415/1267398 XXX: Needs UT :attr path: Path to package/module """ results = {} obj = importlib.import_module(path) results[path] = obj path = getattr(obj, '__path__'...
python
def import_recursive(path): """ Recursively import all modules and packages Thanks http://stackoverflow.com/a/25562415/1267398 XXX: Needs UT :attr path: Path to package/module """ results = {} obj = importlib.import_module(path) results[path] = obj path = getattr(obj, '__path__'...
[ "def", "import_recursive", "(", "path", ")", ":", "results", "=", "{", "}", "obj", "=", "importlib", ".", "import_module", "(", "path", ")", "results", "[", "path", "]", "=", "obj", "path", "=", "getattr", "(", "obj", ",", "'__path__'", ",", "os", "....
Recursively import all modules and packages Thanks http://stackoverflow.com/a/25562415/1267398 XXX: Needs UT :attr path: Path to package/module
[ "Recursively", "import", "all", "modules", "and", "packages", "Thanks", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "25562415", "/", "1267398", "XXX", ":", "Needs", "UT" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L224-L241
foxx/python-helpful
helpful.py
extend_instance
def extend_instance(instance, *bases, **kwargs): """ Apply subclass (mixin) to a class object or its instance By default, the mixin is placed at the start of bases to ensure its called first as per MRO. If you wish to have it injected last, which is useful for monkeypatching, then you can speci...
python
def extend_instance(instance, *bases, **kwargs): """ Apply subclass (mixin) to a class object or its instance By default, the mixin is placed at the start of bases to ensure its called first as per MRO. If you wish to have it injected last, which is useful for monkeypatching, then you can speci...
[ "def", "extend_instance", "(", "instance", ",", "*", "bases", ",", "*", "*", "kwargs", ")", ":", "last", "=", "kwargs", ".", "get", "(", "'last'", ",", "False", ")", "bases", "=", "tuple", "(", "bases", ")", "for", "base", "in", "bases", ":", "asse...
Apply subclass (mixin) to a class object or its instance By default, the mixin is placed at the start of bases to ensure its called first as per MRO. If you wish to have it injected last, which is useful for monkeypatching, then you can specify 'last=True'. See here: http://stackoverflow.com/a/1001...
[ "Apply", "subclass", "(", "mixin", ")", "to", "a", "class", "object", "or", "its", "instance" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L244-L281
foxx/python-helpful
helpful.py
add_bases
def add_bases(cls, *bases): """ Add bases to class >>> class Base(object): pass >>> class A(Base): pass >>> class B(Base): pass >>> issubclass(A, B) False >>> add_bases(A, B) >>> issubclass(A, B) True """ assert inspect.isclass(cls), "Expected class object" for mixin...
python
def add_bases(cls, *bases): """ Add bases to class >>> class Base(object): pass >>> class A(Base): pass >>> class B(Base): pass >>> issubclass(A, B) False >>> add_bases(A, B) >>> issubclass(A, B) True """ assert inspect.isclass(cls), "Expected class object" for mixin...
[ "def", "add_bases", "(", "cls", ",", "*", "bases", ")", ":", "assert", "inspect", ".", "isclass", "(", "cls", ")", ",", "\"Expected class object\"", "for", "mixin", "in", "bases", ":", "assert", "inspect", ".", "isclass", "(", "mixin", ")", ",", "\"Expec...
Add bases to class >>> class Base(object): pass >>> class A(Base): pass >>> class B(Base): pass >>> issubclass(A, B) False >>> add_bases(A, B) >>> issubclass(A, B) True
[ "Add", "bases", "to", "class" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L284-L301
foxx/python-helpful
helpful.py
subclass
def subclass(cls, *bases, **kwargs): """ Add bases to class (late subclassing) Annoyingly we cannot yet modify __bases__ of an existing class, instead we must create another subclass, see here; http://bugs.python.org/issue672115 >>> class A(object): pass >>> class B(object): pass >>> c...
python
def subclass(cls, *bases, **kwargs): """ Add bases to class (late subclassing) Annoyingly we cannot yet modify __bases__ of an existing class, instead we must create another subclass, see here; http://bugs.python.org/issue672115 >>> class A(object): pass >>> class B(object): pass >>> c...
[ "def", "subclass", "(", "cls", ",", "*", "bases", ",", "*", "*", "kwargs", ")", ":", "last", "=", "kwargs", ".", "get", "(", "'last'", ",", "False", ")", "bases", "=", "tuple", "(", "bases", ")", "for", "base", "in", "bases", ":", "assert", "insp...
Add bases to class (late subclassing) Annoyingly we cannot yet modify __bases__ of an existing class, instead we must create another subclass, see here; http://bugs.python.org/issue672115 >>> class A(object): pass >>> class B(object): pass >>> class C(object): pass >>> issubclass(B, A) ...
[ "Add", "bases", "to", "class", "(", "late", "subclassing", ")" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L304-L329
foxx/python-helpful
helpful.py
import_from_path
def import_from_path(path): """ Imports a package, module or attribute from path Thanks http://stackoverflow.com/a/14050282/1267398 >>> import_from_path('os.path') <module 'posixpath' ... >>> import_from_path('os.path.basename') <function basename at ... >>> import_from_path('os') <...
python
def import_from_path(path): """ Imports a package, module or attribute from path Thanks http://stackoverflow.com/a/14050282/1267398 >>> import_from_path('os.path') <module 'posixpath' ... >>> import_from_path('os.path.basename') <function basename at ... >>> import_from_path('os') <...
[ "def", "import_from_path", "(", "path", ")", ":", "try", ":", "return", "importlib", ".", "import_module", "(", "path", ")", "except", "ImportError", ":", "if", "'.'", "not", "in", "path", ":", "raise", "module_name", ",", "attr_name", "=", "path", ".", ...
Imports a package, module or attribute from path Thanks http://stackoverflow.com/a/14050282/1267398 >>> import_from_path('os.path') <module 'posixpath' ... >>> import_from_path('os.path.basename') <function basename at ... >>> import_from_path('os') <module 'os' from ... >>> import_from...
[ "Imports", "a", "package", "module", "or", "attribute", "from", "path", "Thanks", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "14050282", "/", "1267398" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L332-L365
foxx/python-helpful
helpful.py
sort_dict_by_key
def sort_dict_by_key(obj): """ Sort dict by its keys >>> sort_dict_by_key(dict(c=1, b=2, a=3, d=4)) OrderedDict([('a', 3), ('b', 2), ('c', 1), ('d', 4)]) """ sort_func = lambda x: x[0] return OrderedDict(sorted(obj.items(), key=sort_func))
python
def sort_dict_by_key(obj): """ Sort dict by its keys >>> sort_dict_by_key(dict(c=1, b=2, a=3, d=4)) OrderedDict([('a', 3), ('b', 2), ('c', 1), ('d', 4)]) """ sort_func = lambda x: x[0] return OrderedDict(sorted(obj.items(), key=sort_func))
[ "def", "sort_dict_by_key", "(", "obj", ")", ":", "sort_func", "=", "lambda", "x", ":", "x", "[", "0", "]", "return", "OrderedDict", "(", "sorted", "(", "obj", ".", "items", "(", ")", ",", "key", "=", "sort_func", ")", ")" ]
Sort dict by its keys >>> sort_dict_by_key(dict(c=1, b=2, a=3, d=4)) OrderedDict([('a', 3), ('b', 2), ('c', 1), ('d', 4)])
[ "Sort", "dict", "by", "its", "keys" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L384-L392
foxx/python-helpful
helpful.py
generate_random_token
def generate_random_token(length=32): """ Generate random secure token >>> len(generate_random_token()) 32 >>> len(generate_random_token(6)) 6 """ chars = (string.ascii_lowercase + string.ascii_uppercase + string.digits) return ''.join(random.choice(chars) for _ in range(length))
python
def generate_random_token(length=32): """ Generate random secure token >>> len(generate_random_token()) 32 >>> len(generate_random_token(6)) 6 """ chars = (string.ascii_lowercase + string.ascii_uppercase + string.digits) return ''.join(random.choice(chars) for _ in range(length))
[ "def", "generate_random_token", "(", "length", "=", "32", ")", ":", "chars", "=", "(", "string", ".", "ascii_lowercase", "+", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "return", "''", ".", "join", "(", "random", ".", "choice", ...
Generate random secure token >>> len(generate_random_token()) 32 >>> len(generate_random_token(6)) 6
[ "Generate", "random", "secure", "token" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L395-L405
foxx/python-helpful
helpful.py
default
def default(*args, **kwargs): """ Return first argument which is "truthy" >>> default(None, None, 1) 1 >>> default(None, None, 123) 123 >>> print(default(None, None)) None """ default = kwargs.get('default', None) for arg in args: if arg: return arg r...
python
def default(*args, **kwargs): """ Return first argument which is "truthy" >>> default(None, None, 1) 1 >>> default(None, None, 123) 123 >>> print(default(None, None)) None """ default = kwargs.get('default', None) for arg in args: if arg: return arg r...
[ "def", "default", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "default", "=", "kwargs", ".", "get", "(", "'default'", ",", "None", ")", "for", "arg", "in", "args", ":", "if", "arg", ":", "return", "arg", "return", "default" ]
Return first argument which is "truthy" >>> default(None, None, 1) 1 >>> default(None, None, 123) 123 >>> print(default(None, None)) None
[ "Return", "first", "argument", "which", "is", "truthy" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L408-L423
foxx/python-helpful
helpful.py
urljoin
def urljoin(*args): """ Joins given arguments into a url, removing duplicate slashes Thanks http://stackoverflow.com/a/11326230/1267398 >>> urljoin('/lol', '///lol', '/lol//') '/lol/lol/lol' """ value = "/".join(map(lambda x: str(x).strip('/'), args)) return "/{}".format(value)
python
def urljoin(*args): """ Joins given arguments into a url, removing duplicate slashes Thanks http://stackoverflow.com/a/11326230/1267398 >>> urljoin('/lol', '///lol', '/lol//') '/lol/lol/lol' """ value = "/".join(map(lambda x: str(x).strip('/'), args)) return "/{}".format(value)
[ "def", "urljoin", "(", "*", "args", ")", ":", "value", "=", "\"/\"", ".", "join", "(", "map", "(", "lambda", "x", ":", "str", "(", "x", ")", ".", "strip", "(", "'/'", ")", ",", "args", ")", ")", "return", "\"/{}\"", ".", "format", "(", "value",...
Joins given arguments into a url, removing duplicate slashes Thanks http://stackoverflow.com/a/11326230/1267398 >>> urljoin('/lol', '///lol', '/lol//') '/lol/lol/lol'
[ "Joins", "given", "arguments", "into", "a", "url", "removing", "duplicate", "slashes", "Thanks", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "11326230", "/", "1267398" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L426-L435
foxx/python-helpful
helpful.py
is_int
def is_int(value): """ Check if value is an int :type value: int, str, bytes, float, Decimal >>> is_int(123), is_int('123'), is_int(Decimal('10')) (True, True, True) >>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1')) (False, False, False) >>> is_int(object) Traceback (most rec...
python
def is_int(value): """ Check if value is an int :type value: int, str, bytes, float, Decimal >>> is_int(123), is_int('123'), is_int(Decimal('10')) (True, True, True) >>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1')) (False, False, False) >>> is_int(object) Traceback (most rec...
[ "def", "is_int", "(", "value", ")", ":", "ensure_instance", "(", "value", ",", "(", "int", ",", "str", ",", "bytes", ",", "float", ",", "Decimal", ")", ")", "if", "isinstance", "(", "value", ",", "int", ")", ":", "return", "True", "elif", "isinstance...
Check if value is an int :type value: int, str, bytes, float, Decimal >>> is_int(123), is_int('123'), is_int(Decimal('10')) (True, True, True) >>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1')) (False, False, False) >>> is_int(object) Traceback (most recent call last): TypeError:
[ "Check", "if", "value", "is", "an", "int" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L455-L478
foxx/python-helpful
helpful.py
padded_split
def padded_split(value, sep, maxsplit=None, pad=None): """ Modified split() to include padding See http://code.activestate.com/lists/python-ideas/3366/ :attr value: see str.split() :attr sep: see str.split() :attr maxsplit: see str.split() :attr pad: Value to use for padding maxsplit >...
python
def padded_split(value, sep, maxsplit=None, pad=None): """ Modified split() to include padding See http://code.activestate.com/lists/python-ideas/3366/ :attr value: see str.split() :attr sep: see str.split() :attr maxsplit: see str.split() :attr pad: Value to use for padding maxsplit >...
[ "def", "padded_split", "(", "value", ",", "sep", ",", "maxsplit", "=", "None", ",", "pad", "=", "None", ")", ":", "result", "=", "value", ".", "split", "(", "sep", ",", "maxsplit", ")", "if", "maxsplit", "is", "not", "None", ":", "result", ".", "ex...
Modified split() to include padding See http://code.activestate.com/lists/python-ideas/3366/ :attr value: see str.split() :attr sep: see str.split() :attr maxsplit: see str.split() :attr pad: Value to use for padding maxsplit >>> padded_split('text/html', ';', 1) ['text/html', None] >>...
[ "Modified", "split", "()", "to", "include", "padding", "See", "http", ":", "//", "code", ".", "activestate", ".", "com", "/", "lists", "/", "python", "-", "ideas", "/", "3366", "/" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L481-L508
foxx/python-helpful
helpful.py
coerce_to_bytes
def coerce_to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'): """ Coerce value to bytes >>> a = coerce_to_bytes('hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(b'hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(None) >>> assert a is None ...
python
def coerce_to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'): """ Coerce value to bytes >>> a = coerce_to_bytes('hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(b'hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(None) >>> assert a is None ...
[ "def", "coerce_to_bytes", "(", "x", ",", "charset", "=", "sys", ".", "getdefaultencoding", "(", ")", ",", "errors", "=", "'strict'", ")", ":", "PY2", "=", "sys", ".", "version_info", "[", "0", "]", "==", "2", "if", "PY2", ":", "# pragma: nocover", "if"...
Coerce value to bytes >>> a = coerce_to_bytes('hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(b'hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(None) >>> assert a is None >>> coerce_to_bytes(object()) Traceback (most recent call last): ... TypeEr...
[ "Coerce", "value", "to", "bytes" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L511-L543
foxx/python-helpful
helpful.py
random_date_between
def random_date_between(start_date, end_date): """Return random date between start/end""" assert isinstance(start_date, datetime.date) delta_secs = int((end_date - start_date).total_seconds()) delta = datetime.timedelta(seconds=random.randint(0, delta_secs)) return (start_date + delta)
python
def random_date_between(start_date, end_date): """Return random date between start/end""" assert isinstance(start_date, datetime.date) delta_secs = int((end_date - start_date).total_seconds()) delta = datetime.timedelta(seconds=random.randint(0, delta_secs)) return (start_date + delta)
[ "def", "random_date_between", "(", "start_date", ",", "end_date", ")", ":", "assert", "isinstance", "(", "start_date", ",", "datetime", ".", "date", ")", "delta_secs", "=", "int", "(", "(", "end_date", "-", "start_date", ")", ".", "total_seconds", "(", ")", ...
Return random date between start/end
[ "Return", "random", "date", "between", "start", "/", "end" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L567-L572
foxx/python-helpful
helpful.py
Tempfile.cleanup
def cleanup(self): """Remove any created temp paths""" for path in self.paths: if isinstance(path, tuple): os.close(path[0]) os.unlink(path[1]) else: shutil.rmtree(path) self.paths = []
python
def cleanup(self): """Remove any created temp paths""" for path in self.paths: if isinstance(path, tuple): os.close(path[0]) os.unlink(path[1]) else: shutil.rmtree(path) self.paths = []
[ "def", "cleanup", "(", "self", ")", ":", "for", "path", "in", "self", ".", "paths", ":", "if", "isinstance", "(", "path", ",", "tuple", ")", ":", "os", ".", "close", "(", "path", "[", "0", "]", ")", "os", ".", "unlink", "(", "path", "[", "1", ...
Remove any created temp paths
[ "Remove", "any", "created", "temp", "paths" ]
train
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L599-L607
aganezov/gos
gos/tmp/scaffolding_no_repeats.py
get_vertex_surrounding_multicolor
def get_vertex_surrounding_multicolor(graph, vertex): """ Loops over all edges that are incident to supplied vertex and accumulates all colors, that are present in those edges """ result = Multicolor() for edge in graph.get_edges_by_vertex(vertex): result += edge.multicolor return r...
python
def get_vertex_surrounding_multicolor(graph, vertex): """ Loops over all edges that are incident to supplied vertex and accumulates all colors, that are present in those edges """ result = Multicolor() for edge in graph.get_edges_by_vertex(vertex): result += edge.multicolor return r...
[ "def", "get_vertex_surrounding_multicolor", "(", "graph", ",", "vertex", ")", ":", "result", "=", "Multicolor", "(", ")", "for", "edge", "in", "graph", ".", "get_edges_by_vertex", "(", "vertex", ")", ":", "result", "+=", "edge", ".", "multicolor", "return", ...
Loops over all edges that are incident to supplied vertex and accumulates all colors, that are present in those edges
[ "Loops", "over", "all", "edges", "that", "are", "incident", "to", "supplied", "vertex", "and", "accumulates", "all", "colors", "that", "are", "present", "in", "those", "edges" ]
train
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tmp/scaffolding_no_repeats.py#L19-L27
aganezov/gos
gos/tmp/scaffolding_no_repeats.py
get_irregular_edge_by_vertex
def get_irregular_edge_by_vertex(graph, vertex): """ Loops over all edges that are incident to supplied vertex and return a first irregular edge in "no repeat" scenario such irregular edge can be only one for any given supplied vertex """ for edge in graph.get_edges_by_vertex(vertex): if...
python
def get_irregular_edge_by_vertex(graph, vertex): """ Loops over all edges that are incident to supplied vertex and return a first irregular edge in "no repeat" scenario such irregular edge can be only one for any given supplied vertex """ for edge in graph.get_edges_by_vertex(vertex): if...
[ "def", "get_irregular_edge_by_vertex", "(", "graph", ",", "vertex", ")", ":", "for", "edge", "in", "graph", ".", "get_edges_by_vertex", "(", "vertex", ")", ":", "if", "edge", ".", "is_irregular_edge", ":", "return", "edge", "return", "None" ]
Loops over all edges that are incident to supplied vertex and return a first irregular edge in "no repeat" scenario such irregular edge can be only one for any given supplied vertex
[ "Loops", "over", "all", "edges", "that", "are", "incident", "to", "supplied", "vertex", "and", "return", "a", "first", "irregular", "edge", "in", "no", "repeat", "scenario", "such", "irregular", "edge", "can", "be", "only", "one", "for", "any", "given", "s...
train
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tmp/scaffolding_no_repeats.py#L30-L38
aganezov/gos
gos/tmp/scaffolding_no_repeats.py
get_support_edge_scores
def get_support_edge_scores(graph, subnet, target_multicolor, tree, verbose=False, verbose_destination=None): """ For supplied connected components (this connected components is assumed to be pre-filtered before hand) for every regular edge in it (which after pre-filtration would correspond to "supporting"...
python
def get_support_edge_scores(graph, subnet, target_multicolor, tree, verbose=False, verbose_destination=None): """ For supplied connected components (this connected components is assumed to be pre-filtered before hand) for every regular edge in it (which after pre-filtration would correspond to "supporting"...
[ "def", "get_support_edge_scores", "(", "graph", ",", "subnet", ",", "target_multicolor", ",", "tree", ",", "verbose", "=", "False", ",", "verbose_destination", "=", "None", ")", ":", "result", "=", "[", "]", "# we iterate over all regular edges in pre-filtered connect...
For supplied connected components (this connected components is assumed to be pre-filtered before hand) for every regular edge in it (which after pre-filtration would correspond to "supporting" edge only) computes an summands ("before" and "after") for its "assembly score" (which is defined as "before" - "aft...
[ "For", "supplied", "connected", "components", "(", "this", "connected", "components", "is", "assumed", "to", "be", "pre", "-", "filtered", "before", "hand", ")", "for", "every", "regular", "edge", "in", "it", "(", "which", "after", "pre", "-", "filtration", ...
train
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tmp/scaffolding_no_repeats.py#L67-L204
aganezov/gos
gos/tmp/scaffolding_no_repeats.py
get_irregular_subnets
def get_irregular_subnets(cc, target_multicolor, exclude, verbose=False, verbose_destination=None): """ For a supplied connected component (which is assumed to be a deepcopy from an original breakpoint graph) we filter out all edges, that are of no interest for the scaffolding purposes with current target m...
python
def get_irregular_subnets(cc, target_multicolor, exclude, verbose=False, verbose_destination=None): """ For a supplied connected component (which is assumed to be a deepcopy from an original breakpoint graph) we filter out all edges, that are of no interest for the scaffolding purposes with current target m...
[ "def", "get_irregular_subnets", "(", "cc", ",", "target_multicolor", ",", "exclude", ",", "verbose", "=", "False", ",", "verbose_destination", "=", "None", ")", ":", "to_remove", "=", "[", "]", "if", "verbose", ":", "print", "(", "\">Getting irregular subnets\""...
For a supplied connected component (which is assumed to be a deepcopy from an original breakpoint graph) we filter out all edges, that are of no interest for the scaffolding purposes with current target multicolor: 1. target multicolor must be fully present in the irregular edge 2. all colors from t...
[ "For", "a", "supplied", "connected", "component", "(", "which", "is", "assumed", "to", "be", "a", "deepcopy", "from", "an", "original", "breakpoint", "graph", ")", "we", "filter", "out", "all", "edges", "that", "are", "of", "no", "interest", "for", "the", ...
train
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tmp/scaffolding_no_repeats.py#L207-L308
aganezov/gos
gos/tmp/scaffolding_no_repeats.py
identify_assembly_points
def identify_assembly_points(graph, bgtree, target_multicolor, exclude=None, verbose=False, verbose_destination=None): """ The main granular assembling function, that IDENTIFIES assembly points, but does not perform the assembly on its own It DOES NOT change the supplied breakpoint graph in any way!!! "...
python
def identify_assembly_points(graph, bgtree, target_multicolor, exclude=None, verbose=False, verbose_destination=None): """ The main granular assembling function, that IDENTIFIES assembly points, but does not perform the assembly on its own It DOES NOT change the supplied breakpoint graph in any way!!! "...
[ "def", "identify_assembly_points", "(", "graph", ",", "bgtree", ",", "target_multicolor", ",", "exclude", "=", "None", ",", "verbose", "=", "False", ",", "verbose_destination", "=", "None", ")", ":", "if", "verbose", ":", "print", "(", "\">>Identifying assemblie...
The main granular assembling function, that IDENTIFIES assembly points, but does not perform the assembly on its own It DOES NOT change the supplied breakpoint graph in any way!!!
[ "The", "main", "granular", "assembling", "function", "that", "IDENTIFIES", "assembly", "points", "but", "does", "not", "perform", "the", "assembly", "on", "its", "own", "It", "DOES", "NOT", "change", "the", "supplied", "breakpoint", "graph", "in", "any", "way!...
train
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tmp/scaffolding_no_repeats.py#L311-L400
aganezov/gos
gos/tmp/scaffolding_no_repeats.py
assemble_points
def assemble_points(graph, assemblies, multicolor, verbose=False, verbose_destination=None): """ This function actually does assembling being provided a graph, to play with a list of assembly points and a multicolor, which to assemble """ if verbose: print(">>Assembling f...
python
def assemble_points(graph, assemblies, multicolor, verbose=False, verbose_destination=None): """ This function actually does assembling being provided a graph, to play with a list of assembly points and a multicolor, which to assemble """ if verbose: print(">>Assembling f...
[ "def", "assemble_points", "(", "graph", ",", "assemblies", ",", "multicolor", ",", "verbose", "=", "False", ",", "verbose_destination", "=", "None", ")", ":", "if", "verbose", ":", "print", "(", "\">>Assembling for multicolor\"", ",", "[", "e", ".", "name", ...
This function actually does assembling being provided a graph, to play with a list of assembly points and a multicolor, which to assemble
[ "This", "function", "actually", "does", "assembling", "being", "provided", "a", "graph", "to", "play", "with", "a", "list", "of", "assembly", "points", "and", "a", "multicolor", "which", "to", "assemble" ]
train
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tmp/scaffolding_no_repeats.py#L403-L423
shad7/tvdbapi_client
tvdbapi_client/exceptions.py
error_map
def error_map(func): """Wrap exceptions raised by requests. .. py:decorator:: error_map """ @six.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exceptions.RequestException as err: raise TVDBRequestException( ...
python
def error_map(func): """Wrap exceptions raised by requests. .. py:decorator:: error_map """ @six.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exceptions.RequestException as err: raise TVDBRequestException( ...
[ "def", "error_map", "(", "func", ")", ":", "@", "six", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except"...
Wrap exceptions raised by requests. .. py:decorator:: error_map
[ "Wrap", "exceptions", "raised", "by", "requests", "." ]
train
https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/exceptions.py#L6-L20
tagcubeio/tagcube-cli
tagcube_cli/subcommands/batch.py
create_scans
def create_scans(urls_file): """ This method is rather simple, it will group the urls to be scanner together based on (protocol, domain and port). :param urls_file: The filename with all the URLs :return: A list of scans to be run """ cli_logger.debug('Starting to process batch input file')...
python
def create_scans(urls_file): """ This method is rather simple, it will group the urls to be scanner together based on (protocol, domain and port). :param urls_file: The filename with all the URLs :return: A list of scans to be run """ cli_logger.debug('Starting to process batch input file')...
[ "def", "create_scans", "(", "urls_file", ")", ":", "cli_logger", ".", "debug", "(", "'Starting to process batch input file'", ")", "created_scans", "=", "[", "]", "for", "line", "in", "urls_file", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line...
This method is rather simple, it will group the urls to be scanner together based on (protocol, domain and port). :param urls_file: The filename with all the URLs :return: A list of scans to be run
[ "This", "method", "is", "rather", "simple", "it", "will", "group", "the", "urls", "to", "be", "scanner", "together", "based", "on", "(", "protocol", "domain", "and", "port", ")", "." ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/subcommands/batch.py#L23-L61
tagcubeio/tagcube-cli
tagcube_cli/subcommands/batch.py
parse_url
def parse_url(url): """ Parse a URL into the parts I need for processing: * protocol * domain * port * path :param url: A string :return: A tuple containing the above """ split_url = url.split('/', 3) if len(split_url) == 3: # http://foo.com p...
python
def parse_url(url): """ Parse a URL into the parts I need for processing: * protocol * domain * port * path :param url: A string :return: A tuple containing the above """ split_url = url.split('/', 3) if len(split_url) == 3: # http://foo.com p...
[ "def", "parse_url", "(", "url", ")", ":", "split_url", "=", "url", ".", "split", "(", "'/'", ",", "3", ")", "if", "len", "(", "split_url", ")", "==", "3", ":", "# http://foo.com", "path", "=", "'/'", "elif", "len", "(", "split_url", ")", "==", "4",...
Parse a URL into the parts I need for processing: * protocol * domain * port * path :param url: A string :return: A tuple containing the above
[ "Parse", "a", "URL", "into", "the", "parts", "I", "need", "for", "processing", ":", "*", "protocol", "*", "domain", "*", "port", "*", "path" ]
train
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/subcommands/batch.py#L64-L110
eeue56/PyChat.js
pychatjs/server/protocol.py
create_message
def create_message(username, message): """ Creates a standard message from a given user with the message Replaces newline with html break """ message = message.replace('\n', '<br/>') return '{{"service":1, "data":{{"message":"{mes}", "username":"{user}"}} }}'.format(mes=message, user=username)
python
def create_message(username, message): """ Creates a standard message from a given user with the message Replaces newline with html break """ message = message.replace('\n', '<br/>') return '{{"service":1, "data":{{"message":"{mes}", "username":"{user}"}} }}'.format(mes=message, user=username)
[ "def", "create_message", "(", "username", ",", "message", ")", ":", "message", "=", "message", ".", "replace", "(", "'\\n'", ",", "'<br/>'", ")", "return", "'{{\"service\":1, \"data\":{{\"message\":\"{mes}\", \"username\":\"{user}\"}} }}'", ".", "format", "(", "mes", ...
Creates a standard message from a given user with the message Replaces newline with html break
[ "Creates", "a", "standard", "message", "from", "a", "given", "user", "with", "the", "message", "Replaces", "newline", "with", "html", "break" ]
train
https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/protocol.py#L17-L21
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor._add
def _add(self, xer, primary, type): """ Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example). """ if xer not in primary: primary[xer]...
python
def _add(self, xer, primary, type): """ Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example). """ if xer not in primary: primary[xer]...
[ "def", "_add", "(", "self", ",", "xer", ",", "primary", ",", "type", ")", ":", "if", "xer", "not", "in", "primary", ":", "primary", "[", "xer", "]", "=", "TwistedSocketNotifier", "(", "None", ",", "self", ",", "xer", ",", "type", ")" ]
Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example).
[ "Private", "method", "for", "adding", "a", "descriptor", "from", "the", "event", "loop", "." ]
train
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L146-L154
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor.addReader
def addReader(self, reader): """ Add a FileDescriptor for notification of data available to read. """ self._add(reader, self._reads, QtCore.QSocketNotifier.Read)
python
def addReader(self, reader): """ Add a FileDescriptor for notification of data available to read. """ self._add(reader, self._reads, QtCore.QSocketNotifier.Read)
[ "def", "addReader", "(", "self", ",", "reader", ")", ":", "self", ".", "_add", "(", "reader", ",", "self", ".", "_reads", ",", "QtCore", ".", "QSocketNotifier", ".", "Read", ")" ]
Add a FileDescriptor for notification of data available to read.
[ "Add", "a", "FileDescriptor", "for", "notification", "of", "data", "available", "to", "read", "." ]
train
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L157-L161
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor.addWriter
def addWriter(self, writer): """ Add a FileDescriptor for notification of data available to write. """ self._add(writer, self._writes, QtCore.QSocketNotifier.Write)
python
def addWriter(self, writer): """ Add a FileDescriptor for notification of data available to write. """ self._add(writer, self._writes, QtCore.QSocketNotifier.Write)
[ "def", "addWriter", "(", "self", ",", "writer", ")", ":", "self", ".", "_add", "(", "writer", ",", "self", ".", "_writes", ",", "QtCore", ".", "QSocketNotifier", ".", "Write", ")" ]
Add a FileDescriptor for notification of data available to write.
[ "Add", "a", "FileDescriptor", "for", "notification", "of", "data", "available", "to", "write", "." ]
train
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L164-L168
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor._remove
def _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """ if xer in primary: notifier = primary.pop(xer) notifier.s...
python
def _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """ if xer in primary: notifier = primary.pop(xer) notifier.s...
[ "def", "_remove", "(", "self", ",", "xer", ",", "primary", ")", ":", "if", "xer", "in", "primary", ":", "notifier", "=", "primary", ".", "pop", "(", "xer", ")", "notifier", ".", "shutdown", "(", ")" ]
Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away.
[ "Private", "method", "for", "removing", "a", "descriptor", "from", "the", "event", "loop", "." ]
train
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L171-L180
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor.removeAll
def removeAll(self): """ Remove all selectables, and return a list of them. """ rv = self._removeAll(self._reads, self._writes) return rv
python
def removeAll(self): """ Remove all selectables, and return a list of them. """ rv = self._removeAll(self._reads, self._writes) return rv
[ "def", "removeAll", "(", "self", ")", ":", "rv", "=", "self", ".", "_removeAll", "(", "self", ".", "_reads", ",", "self", ".", "_writes", ")", "return", "rv" ]
Remove all selectables, and return a list of them.
[ "Remove", "all", "selectables", "and", "return", "a", "list", "of", "them", "." ]
train
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L197-L202
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor._iterate
def _iterate(self, delay=None, fromqt=False): """See twisted.internet.interfaces.IReactorCore.iterate. """ self.runUntilCurrent() self.doIteration(delay, fromqt)
python
def _iterate(self, delay=None, fromqt=False): """See twisted.internet.interfaces.IReactorCore.iterate. """ self.runUntilCurrent() self.doIteration(delay, fromqt)
[ "def", "_iterate", "(", "self", ",", "delay", "=", "None", ",", "fromqt", "=", "False", ")", ":", "self", ".", "runUntilCurrent", "(", ")", "self", ".", "doIteration", "(", "delay", ",", "fromqt", ")" ]
See twisted.internet.interfaces.IReactorCore.iterate.
[ "See", "twisted", ".", "internet", ".", "interfaces", ".", "IReactorCore", ".", "iterate", "." ]
train
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L225-L229
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor.doIteration
def doIteration(self, delay=None, fromqt=False): 'This method is called by a Qt timer or by network activity on a file descriptor' if not self.running and self._blockApp: self._blockApp.quit() self._timer.stop() delay = max(delay, 1) if not fromqt: ...
python
def doIteration(self, delay=None, fromqt=False): 'This method is called by a Qt timer or by network activity on a file descriptor' if not self.running and self._blockApp: self._blockApp.quit() self._timer.stop() delay = max(delay, 1) if not fromqt: ...
[ "def", "doIteration", "(", "self", ",", "delay", "=", "None", ",", "fromqt", "=", "False", ")", ":", "if", "not", "self", ".", "running", "and", "self", ".", "_blockApp", ":", "self", ".", "_blockApp", ".", "quit", "(", ")", "self", ".", "_timer", ...
This method is called by a Qt timer or by network activity on a file descriptor
[ "This", "method", "is", "called", "by", "a", "Qt", "timer", "or", "by", "network", "activity", "on", "a", "file", "descriptor" ]
train
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L233-L249
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtEventReactor.addEvent
def addEvent(self, event, fd, action): """ Add a new win32 event to the event loop. """ self._events[event] = (fd, action)
python
def addEvent(self, event, fd, action): """ Add a new win32 event to the event loop. """ self._events[event] = (fd, action)
[ "def", "addEvent", "(", "self", ",", "event", ",", "fd", ",", "action", ")", ":", "self", ".", "_events", "[", "event", "]", "=", "(", "fd", ",", "action", ")" ]
Add a new win32 event to the event loop.
[ "Add", "a", "new", "win32", "event", "to", "the", "event", "loop", "." ]
train
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L272-L276
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtEventReactor.iterate
def iterate(self, delay=None): """See twisted.internet.interfaces.IReactorCore.iterate. """ self.runUntilCurrent() self.doEvents() self.doIteration(delay)
python
def iterate(self, delay=None): """See twisted.internet.interfaces.IReactorCore.iterate. """ self.runUntilCurrent() self.doEvents() self.doIteration(delay)
[ "def", "iterate", "(", "self", ",", "delay", "=", "None", ")", ":", "self", ".", "runUntilCurrent", "(", ")", "self", ".", "doEvents", "(", ")", "self", ".", "doIteration", "(", "delay", ")" ]
See twisted.internet.interfaces.IReactorCore.iterate.
[ "See", "twisted", ".", "internet", ".", "interfaces", ".", "IReactorCore", ".", "iterate", "." ]
train
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L321-L326
chrlie/howabout
src/howabout/__init__.py
get_levenshtein
def get_levenshtein(first, second): """\ Get the Levenshtein distance between two strings. :param first: the first string :param second: the second string """ if not first: return len(second) if not second: return len(first) prev_distances = range(0, len(second)...
python
def get_levenshtein(first, second): """\ Get the Levenshtein distance between two strings. :param first: the first string :param second: the second string """ if not first: return len(second) if not second: return len(first) prev_distances = range(0, len(second)...
[ "def", "get_levenshtein", "(", "first", ",", "second", ")", ":", "if", "not", "first", ":", "return", "len", "(", "second", ")", "if", "not", "second", ":", "return", "len", "(", "first", ")", "prev_distances", "=", "range", "(", "0", ",", "len", "("...
\ Get the Levenshtein distance between two strings. :param first: the first string :param second: the second string
[ "\\", "Get", "the", "Levenshtein", "distance", "between", "two", "strings", "." ]
train
https://github.com/chrlie/howabout/blob/780cacbdd9156106cc77f643c75191a824b034bb/src/howabout/__init__.py#L6-L47
chrlie/howabout
src/howabout/__init__.py
Matcher.all_matches
def all_matches(self, target, choices, group=False, include_rank=False): """\ Get all choices listed from best match to worst match. If `group` is `True`, then matches are grouped based on their distance returned from `get_distance(target, choice)` and returned as an iterator. O...
python
def all_matches(self, target, choices, group=False, include_rank=False): """\ Get all choices listed from best match to worst match. If `group` is `True`, then matches are grouped based on their distance returned from `get_distance(target, choice)` and returned as an iterator. O...
[ "def", "all_matches", "(", "self", ",", "target", ",", "choices", ",", "group", "=", "False", ",", "include_rank", "=", "False", ")", ":", "dist", "=", "self", ".", "get_distance", "# Keep everything here as an iterator in case we're given a lot of", "# choices", "m...
\ Get all choices listed from best match to worst match. If `group` is `True`, then matches are grouped based on their distance returned from `get_distance(target, choice)` and returned as an iterator. Otherwise, an iterator of all matches is returned. For example :: ...
[ "\\", "Get", "all", "choices", "listed", "from", "best", "match", "to", "worst", "match", "." ]
train
https://github.com/chrlie/howabout/blob/780cacbdd9156106cc77f643c75191a824b034bb/src/howabout/__init__.py#L68-L109
chrlie/howabout
src/howabout/__init__.py
Matcher.best_matches
def best_matches(self, target, choices): """\ Get all the first choices listed from best match to worst match, optionally grouping on equal matches. :param target: :param choices: :param group: """ all = self.all_matches try: matches...
python
def best_matches(self, target, choices): """\ Get all the first choices listed from best match to worst match, optionally grouping on equal matches. :param target: :param choices: :param group: """ all = self.all_matches try: matches...
[ "def", "best_matches", "(", "self", ",", "target", ",", "choices", ")", ":", "all", "=", "self", ".", "all_matches", "try", ":", "matches", "=", "next", "(", "all", "(", "target", ",", "choices", ",", "group", "=", "True", ")", ")", "for", "match", ...
\ Get all the first choices listed from best match to worst match, optionally grouping on equal matches. :param target: :param choices: :param group:
[ "\\", "Get", "all", "the", "first", "choices", "listed", "from", "best", "match", "to", "worst", "match", "optionally", "grouping", "on", "equal", "matches", "." ]
train
https://github.com/chrlie/howabout/blob/780cacbdd9156106cc77f643c75191a824b034bb/src/howabout/__init__.py#L111-L128
chrlie/howabout
src/howabout/__init__.py
Matcher.best_match
def best_match(self, target, choices): """\ Return the best match. """ all = self.all_matches try: best = next(all(target, choices, group=False)) return best except StopIteration: pass
python
def best_match(self, target, choices): """\ Return the best match. """ all = self.all_matches try: best = next(all(target, choices, group=False)) return best except StopIteration: pass
[ "def", "best_match", "(", "self", ",", "target", ",", "choices", ")", ":", "all", "=", "self", ".", "all_matches", "try", ":", "best", "=", "next", "(", "all", "(", "target", ",", "choices", ",", "group", "=", "False", ")", ")", "return", "best", "...
\ Return the best match.
[ "\\", "Return", "the", "best", "match", "." ]
train
https://github.com/chrlie/howabout/blob/780cacbdd9156106cc77f643c75191a824b034bb/src/howabout/__init__.py#L130-L141
TheOneHyer/arandomness
build/lib.linux-x86_64-3.6/arandomness/arandom/agenerator.py
agenerator
def agenerator(): """Arandom number generator""" free_mem = psutil.virtual_memory().available mem_24 = 0.24 * free_mem mem_26 = 0.26 * free_mem a = MemEater(int(mem_24)) b = MemEater(int(mem_26)) sleep(5) return free_mem/1000/1000, psutil.virtual_memory().available/1000/1000
python
def agenerator(): """Arandom number generator""" free_mem = psutil.virtual_memory().available mem_24 = 0.24 * free_mem mem_26 = 0.26 * free_mem a = MemEater(int(mem_24)) b = MemEater(int(mem_26)) sleep(5) return free_mem/1000/1000, psutil.virtual_memory().available/1000/1000
[ "def", "agenerator", "(", ")", ":", "free_mem", "=", "psutil", ".", "virtual_memory", "(", ")", ".", "available", "mem_24", "=", "0.24", "*", "free_mem", "mem_26", "=", "0.26", "*", "free_mem", "a", "=", "MemEater", "(", "int", "(", "mem_24", ")", ")",...
Arandom number generator
[ "Arandom", "number", "generator" ]
train
https://github.com/TheOneHyer/arandomness/blob/ae9f630e9a1d67b0eb6d61644a49756de8a5268c/build/lib.linux-x86_64-3.6/arandomness/arandom/agenerator.py#L35-L44
geertj/looping
lib/looping/pyuv.py
PyUVEventLoop._validate_signal
def _validate_signal(self, sig): """Internal helper to validate a signal. Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if there is a problem setting up the handler. """ if not isinstance(sig, int): raise TypeError('sig must be a...
python
def _validate_signal(self, sig): """Internal helper to validate a signal. Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if there is a problem setting up the handler. """ if not isinstance(sig, int): raise TypeError('sig must be a...
[ "def", "_validate_signal", "(", "self", ",", "sig", ")", ":", "if", "not", "isinstance", "(", "sig", ",", "int", ")", ":", "raise", "TypeError", "(", "'sig must be an int, not {!r}'", ".", "format", "(", "sig", ")", ")", "if", "signal", "is", "None", ":"...
Internal helper to validate a signal. Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if there is a problem setting up the handler.
[ "Internal", "helper", "to", "validate", "a", "signal", "." ]
train
https://github.com/geertj/looping/blob/b60303714685aede18b37c0d80f8f55175ad7a65/lib/looping/pyuv.py#L358-L371
rackerlabs/silverberg
silverberg/client.py
CQLClient.describe_version
def describe_version(self): """ Query the Cassandra server for the version. :returns: string -- the version tag """ def _vers(client): return client.describe_version() d = self._connection() d.addCallback(_vers) return d
python
def describe_version(self): """ Query the Cassandra server for the version. :returns: string -- the version tag """ def _vers(client): return client.describe_version() d = self._connection() d.addCallback(_vers) return d
[ "def", "describe_version", "(", "self", ")", ":", "def", "_vers", "(", "client", ")", ":", "return", "client", ".", "describe_version", "(", ")", "d", "=", "self", ".", "_connection", "(", ")", "d", ".", "addCallback", "(", "_vers", ")", "return", "d" ...
Query the Cassandra server for the version. :returns: string -- the version tag
[ "Query", "the", "Cassandra", "server", "for", "the", "version", "." ]
train
https://github.com/rackerlabs/silverberg/blob/c6fae78923a019f1615e9516ab30fa105c72a542/silverberg/client.py#L106-L117
rackerlabs/silverberg
silverberg/client.py
CQLClient.execute
def execute(self, query, args, consistency): """ Execute a CQL query against the server. :param query: The CQL query to execute :type query: str. :param args: The arguments to substitute :type args: dict. :param consistency: The consistency level :type ...
python
def execute(self, query, args, consistency): """ Execute a CQL query against the server. :param query: The CQL query to execute :type query: str. :param args: The arguments to substitute :type args: dict. :param consistency: The consistency level :type ...
[ "def", "execute", "(", "self", ",", "query", ",", "args", ",", "consistency", ")", ":", "prep_query", "=", "prepare", "(", "query", ",", "args", ")", "def", "_execute", "(", "client", ")", ":", "exec_d", "=", "client", ".", "execute_cql3_query", "(", "...
Execute a CQL query against the server. :param query: The CQL query to execute :type query: str. :param args: The arguments to substitute :type args: dict. :param consistency: The consistency level :type consistency: ConsistencyLevel In order to avoid unpleasa...
[ "Execute", "a", "CQL", "query", "against", "the", "server", "." ]
train
https://github.com/rackerlabs/silverberg/blob/c6fae78923a019f1615e9516ab30fa105c72a542/silverberg/client.py#L161-L221
akissa/sachannelupdate
sachannelupdate/base.py
getfiles
def getfiles(qfiles, dirname, names): """Get rule files in a directory""" for name in names: fullname = os.path.join(dirname, name) if os.path.isfile(fullname) and \ fullname.endswith('.cf') or \ fullname.endswith('.post'): qfiles.put(fullname)
python
def getfiles(qfiles, dirname, names): """Get rule files in a directory""" for name in names: fullname = os.path.join(dirname, name) if os.path.isfile(fullname) and \ fullname.endswith('.cf') or \ fullname.endswith('.post'): qfiles.put(fullname)
[ "def", "getfiles", "(", "qfiles", ",", "dirname", ",", "names", ")", ":", "for", "name", "in", "names", ":", "fullname", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "name", ")", "if", "os", ".", "path", ".", "isfile", "(", "fullname",...
Get rule files in a directory
[ "Get", "rule", "files", "in", "a", "directory" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L49-L56
akissa/sachannelupdate
sachannelupdate/base.py
deploy_file
def deploy_file(source, dest): """Deploy a file""" date = datetime.utcnow().strftime('%Y-%m-%d') shandle = open(source) with open(dest, 'w') as handle: for line in shandle: if line == '# Updated: %date%\n': newline = '# Updated: %s\n' % date else: ...
python
def deploy_file(source, dest): """Deploy a file""" date = datetime.utcnow().strftime('%Y-%m-%d') shandle = open(source) with open(dest, 'w') as handle: for line in shandle: if line == '# Updated: %date%\n': newline = '# Updated: %s\n' % date else: ...
[ "def", "deploy_file", "(", "source", ",", "dest", ")", ":", "date", "=", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", "shandle", "=", "open", "(", "source", ")", "with", "open", "(", "dest", ",", "'w'", ")", "as", "...
Deploy a file
[ "Deploy", "a", "file" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L59-L71
akissa/sachannelupdate
sachannelupdate/base.py
package
def package(dest, tardir, p_version): """Package files""" os.chdir(dest) p_filename = '%s.tar.gz' % p_version p_path = os.path.join(tardir, p_filename) tar = tarfile.open(p_path, mode='w:gz') for cf_file in os.listdir('.'): if os.path.isfile(cf_file): tar.add(cf_file) tar...
python
def package(dest, tardir, p_version): """Package files""" os.chdir(dest) p_filename = '%s.tar.gz' % p_version p_path = os.path.join(tardir, p_filename) tar = tarfile.open(p_path, mode='w:gz') for cf_file in os.listdir('.'): if os.path.isfile(cf_file): tar.add(cf_file) tar...
[ "def", "package", "(", "dest", ",", "tardir", ",", "p_version", ")", ":", "os", ".", "chdir", "(", "dest", ")", "p_filename", "=", "'%s.tar.gz'", "%", "p_version", "p_path", "=", "os", ".", "path", ".", "join", "(", "tardir", ",", "p_filename", ")", ...
Package files
[ "Package", "files" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L74-L83
akissa/sachannelupdate
sachannelupdate/base.py
process
def process(dest, rulefiles): """process rules""" deploy = False while not rulefiles.empty(): rulefile = rulefiles.get() base = os.path.basename(rulefile) dest = os.path.join(dest, base) if os.path.exists(dest): # check if older oldtime = os.stat(rulef...
python
def process(dest, rulefiles): """process rules""" deploy = False while not rulefiles.empty(): rulefile = rulefiles.get() base = os.path.basename(rulefile) dest = os.path.join(dest, base) if os.path.exists(dest): # check if older oldtime = os.stat(rulef...
[ "def", "process", "(", "dest", ",", "rulefiles", ")", ":", "deploy", "=", "False", "while", "not", "rulefiles", ".", "empty", "(", ")", ":", "rulefile", "=", "rulefiles", ".", "get", "(", ")", "base", "=", "os", ".", "path", ".", "basename", "(", "...
process rules
[ "process", "rules" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L86-L103
akissa/sachannelupdate
sachannelupdate/base.py
get_counter
def get_counter(counterfile): """Get the counter value""" try: version_num = open(counterfile).read() version_num = int(version_num) + 1 except (ValueError, IOError): version_num = 1 create_file(counterfile, "%d" % version_num) except BaseException as msg: raise S...
python
def get_counter(counterfile): """Get the counter value""" try: version_num = open(counterfile).read() version_num = int(version_num) + 1 except (ValueError, IOError): version_num = 1 create_file(counterfile, "%d" % version_num) except BaseException as msg: raise S...
[ "def", "get_counter", "(", "counterfile", ")", ":", "try", ":", "version_num", "=", "open", "(", "counterfile", ")", ".", "read", "(", ")", "version_num", "=", "int", "(", "version_num", ")", "+", "1", "except", "(", "ValueError", ",", "IOError", ")", ...
Get the counter value
[ "Get", "the", "counter", "value" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L106-L116
akissa/sachannelupdate
sachannelupdate/base.py
update_dns
def update_dns(config, record, sa_version): "Update the DNS record" try: domain = config.get('domain_name', 'sa.baruwa.com.') dns_key = config.get('domain_key') dns_ip = config.get('domain_ip', '127.0.0.1') keyring = tsigkeyring.from_text({domain: dns_key}) transaction = ...
python
def update_dns(config, record, sa_version): "Update the DNS record" try: domain = config.get('domain_name', 'sa.baruwa.com.') dns_key = config.get('domain_key') dns_ip = config.get('domain_ip', '127.0.0.1') keyring = tsigkeyring.from_text({domain: dns_key}) transaction = ...
[ "def", "update_dns", "(", "config", ",", "record", ",", "sa_version", ")", ":", "try", ":", "domain", "=", "config", ".", "get", "(", "'domain_name'", ",", "'sa.baruwa.com.'", ")", "dns_key", "=", "config", ".", "get", "(", "'domain_key'", ")", "dns_ip", ...
Update the DNS record
[ "Update", "the", "DNS", "record" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L119-L135
akissa/sachannelupdate
sachannelupdate/base.py
sign
def sign(config, s_filename): """sign the package""" gpg_home = config.get('gpg_dir', '/var/lib/sachannelupdate/gnupg') gpg_pass = config.get('gpg_passphrase') gpg_keyid = config.get('gpg_keyid') gpg = GPG(gnupghome=gpg_home) try: plaintext = open(s_filename, 'rb') signature = gp...
python
def sign(config, s_filename): """sign the package""" gpg_home = config.get('gpg_dir', '/var/lib/sachannelupdate/gnupg') gpg_pass = config.get('gpg_passphrase') gpg_keyid = config.get('gpg_keyid') gpg = GPG(gnupghome=gpg_home) try: plaintext = open(s_filename, 'rb') signature = gp...
[ "def", "sign", "(", "config", ",", "s_filename", ")", ":", "gpg_home", "=", "config", ".", "get", "(", "'gpg_dir'", ",", "'/var/lib/sachannelupdate/gnupg'", ")", "gpg_pass", "=", "config", ".", "get", "(", "'gpg_passphrase'", ")", "gpg_keyid", "=", "config", ...
sign the package
[ "sign", "the", "package" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L138-L152
akissa/sachannelupdate
sachannelupdate/base.py
hash_file
def hash_file(tar_filename): """hash the file""" hasher = sha1() with open(tar_filename, 'rb') as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) data = HASHTMPL % (hasher.hexdigest(), os.path.basename(tar_file...
python
def hash_file(tar_filename): """hash the file""" hasher = sha1() with open(tar_filename, 'rb') as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) data = HASHTMPL % (hasher.hexdigest(), os.path.basename(tar_file...
[ "def", "hash_file", "(", "tar_filename", ")", ":", "hasher", "=", "sha1", "(", ")", "with", "open", "(", "tar_filename", ",", "'rb'", ")", "as", "afile", ":", "buf", "=", "afile", ".", "read", "(", "BLOCKSIZE", ")", "while", "len", "(", "buf", ")", ...
hash the file
[ "hash", "the", "file" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L155-L164
akissa/sachannelupdate
sachannelupdate/base.py
upload
def upload(config, remote_loc, u_filename): """Upload the files""" rcode = False try: sftp, transport = get_sftp_conn(config) remote_dir = get_remote_path(remote_loc) for part in ['sha1', 'asc']: local_file = '%s.%s' % (u_filename, part) remote_file = os.path....
python
def upload(config, remote_loc, u_filename): """Upload the files""" rcode = False try: sftp, transport = get_sftp_conn(config) remote_dir = get_remote_path(remote_loc) for part in ['sha1', 'asc']: local_file = '%s.%s' % (u_filename, part) remote_file = os.path....
[ "def", "upload", "(", "config", ",", "remote_loc", ",", "u_filename", ")", ":", "rcode", "=", "False", "try", ":", "sftp", ",", "transport", "=", "get_sftp_conn", "(", "config", ")", "remote_dir", "=", "get_remote_path", "(", "remote_loc", ")", "for", "par...
Upload the files
[ "Upload", "the", "files" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L167-L184
akissa/sachannelupdate
sachannelupdate/base.py
queue_files
def queue_files(dirpath, queue): """Add files in a directory to a queue""" for root, _, files in os.walk(os.path.abspath(dirpath)): if not files: continue for filename in files: queue.put(os.path.join(root, filename))
python
def queue_files(dirpath, queue): """Add files in a directory to a queue""" for root, _, files in os.walk(os.path.abspath(dirpath)): if not files: continue for filename in files: queue.put(os.path.join(root, filename))
[ "def", "queue_files", "(", "dirpath", ",", "queue", ")", ":", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "os", ".", "path", ".", "abspath", "(", "dirpath", ")", ")", ":", "if", "not", "files", ":", "continue", "for", "fi...
Add files in a directory to a queue
[ "Add", "files", "in", "a", "directory", "to", "a", "queue" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L187-L193
akissa/sachannelupdate
sachannelupdate/base.py
get_cf_files
def get_cf_files(path, queue): """Get rule files in a directory and put them in a queue""" for root, _, files in os.walk(os.path.abspath(path)): if not files: continue for filename in files: fullname = os.path.join(root, filename) if os.path.isfile(fullname) a...
python
def get_cf_files(path, queue): """Get rule files in a directory and put them in a queue""" for root, _, files in os.walk(os.path.abspath(path)): if not files: continue for filename in files: fullname = os.path.join(root, filename) if os.path.isfile(fullname) a...
[ "def", "get_cf_files", "(", "path", ",", "queue", ")", ":", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", ":", "if", "not", "files", ":", "continue", "for", "filenam...
Get rule files in a directory and put them in a queue
[ "Get", "rule", "files", "in", "a", "directory", "and", "put", "them", "in", "a", "queue" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L196-L205
akissa/sachannelupdate
sachannelupdate/base.py
cleanup
def cleanup(dest, tardir, counterfile): """Remove existing rules""" thefiles = Queue() # dest directory files queue_files(dest, thefiles) # tar directory files queue_files(tardir, thefiles) while not thefiles.empty(): d_file = thefiles.get() info("Deleting file: %s" % d_file)...
python
def cleanup(dest, tardir, counterfile): """Remove existing rules""" thefiles = Queue() # dest directory files queue_files(dest, thefiles) # tar directory files queue_files(tardir, thefiles) while not thefiles.empty(): d_file = thefiles.get() info("Deleting file: %s" % d_file)...
[ "def", "cleanup", "(", "dest", ",", "tardir", ",", "counterfile", ")", ":", "thefiles", "=", "Queue", "(", ")", "# dest directory files", "queue_files", "(", "dest", ",", "thefiles", ")", "# tar directory files", "queue_files", "(", "tardir", ",", "thefiles", ...
Remove existing rules
[ "Remove", "existing", "rules" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L208-L221
akissa/sachannelupdate
sachannelupdate/base.py
check_required
def check_required(config): """Validate the input""" if config.get('domain_key') is None: raise CfgError("The domain_key option is required") if config.get('remote_loc') is None: raise CfgError("The remote_location option is required") if config.get('gpg_keyid') is None: raise Cf...
python
def check_required(config): """Validate the input""" if config.get('domain_key') is None: raise CfgError("The domain_key option is required") if config.get('remote_loc') is None: raise CfgError("The remote_location option is required") if config.get('gpg_keyid') is None: raise Cf...
[ "def", "check_required", "(", "config", ")", ":", "if", "config", ".", "get", "(", "'domain_key'", ")", "is", "None", ":", "raise", "CfgError", "(", "\"The domain_key option is required\"", ")", "if", "config", ".", "get", "(", "'remote_loc'", ")", "is", "No...
Validate the input
[ "Validate", "the", "input" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L224-L231
akissa/sachannelupdate
sachannelupdate/base.py
entry
def entry(config, delete_files=None): """Main function""" home_dir = config.get('home_dir', '/var/lib/sachannelupdate') dns_ver = config.get('spamassassin_version', '1.4.3') remote_loc = config.get('remote_location') rule_dir = os.path.join(home_dir, 'rules') dest = os.path.join(home_dir, 'deplo...
python
def entry(config, delete_files=None): """Main function""" home_dir = config.get('home_dir', '/var/lib/sachannelupdate') dns_ver = config.get('spamassassin_version', '1.4.3') remote_loc = config.get('remote_location') rule_dir = os.path.join(home_dir, 'rules') dest = os.path.join(home_dir, 'deplo...
[ "def", "entry", "(", "config", ",", "delete_files", "=", "None", ")", ":", "home_dir", "=", "config", ".", "get", "(", "'home_dir'", ",", "'/var/lib/sachannelupdate'", ")", "dns_ver", "=", "config", ".", "get", "(", "'spamassassin_version'", ",", "'1.4.3'", ...
Main function
[ "Main", "function" ]
train
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L234-L262
edeposit/edeposit.amqp.antivirus
src/edeposit/amqp/antivirus/wrappers/clamscan.py
_parse_result
def _parse_result(result): """ Parse ``clamscan`` output into same dictionary structured used by ``pyclamd``. Input example:: /home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND Output dict:: { "/home/bystrousak/Plocha/prace/test/eicar.com": ( ...
python
def _parse_result(result): """ Parse ``clamscan`` output into same dictionary structured used by ``pyclamd``. Input example:: /home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND Output dict:: { "/home/bystrousak/Plocha/prace/test/eicar.com": ( ...
[ "def", "_parse_result", "(", "result", ")", ":", "lines", "=", "filter", "(", "lambda", "x", ":", "x", ".", "strip", "(", ")", ",", "result", ".", "splitlines", "(", ")", ")", "# rm blank lines", "if", "not", "lines", ":", "return", "{", "}", "out", ...
Parse ``clamscan`` output into same dictionary structured used by ``pyclamd``. Input example:: /home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND Output dict:: { "/home/bystrousak/Plocha/prace/test/eicar.com": ( "FOUND", "Ei...
[ "Parse", "clamscan", "output", "into", "same", "dictionary", "structured", "used", "by", "pyclamd", "." ]
train
https://github.com/edeposit/edeposit.amqp.antivirus/blob/011b38bbe920819fab99a5891b1e70732321a598/src/edeposit/amqp/antivirus/wrappers/clamscan.py#L17-L50
edeposit/edeposit.amqp.antivirus
src/edeposit/amqp/antivirus/wrappers/clamscan.py
scan_file
def scan_file(path): """ Scan `path` for viruses using ``clamscan`` program. Args: path (str): Relative or absolute path of file/directory you need to scan. Returns: dict: ``{filename: ("FOUND", "virus type")}`` or blank dict. Raises: AssertionError: Wh...
python
def scan_file(path): """ Scan `path` for viruses using ``clamscan`` program. Args: path (str): Relative or absolute path of file/directory you need to scan. Returns: dict: ``{filename: ("FOUND", "virus type")}`` or blank dict. Raises: AssertionError: Wh...
[ "def", "scan_file", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "assert", "os", ".", "path", ".", "exists", "(", "path", ")", ",", "\"Unreachable file '%s'.\"", "%", "path", "result", "=", "sh", ".", "clam...
Scan `path` for viruses using ``clamscan`` program. Args: path (str): Relative or absolute path of file/directory you need to scan. Returns: dict: ``{filename: ("FOUND", "virus type")}`` or blank dict. Raises: AssertionError: When the internal file doesn't exis...
[ "Scan", "path", "for", "viruses", "using", "clamscan", "program", "." ]
train
https://github.com/edeposit/edeposit.amqp.antivirus/blob/011b38bbe920819fab99a5891b1e70732321a598/src/edeposit/amqp/antivirus/wrappers/clamscan.py#L53-L72
costastf/emaillib
emaillib/emaillib.py
SmtpServer.connect
def connect(self): """Initializes a connection to the smtp server :return: True on success, False otherwise """ connection_method = 'SMTP_SSL' if self.ssl else 'SMTP' self._logger.debug('Trying to connect via {}'.format(connection_method)) smtp = getattr(smtplib, connect...
python
def connect(self): """Initializes a connection to the smtp server :return: True on success, False otherwise """ connection_method = 'SMTP_SSL' if self.ssl else 'SMTP' self._logger.debug('Trying to connect via {}'.format(connection_method)) smtp = getattr(smtplib, connect...
[ "def", "connect", "(", "self", ")", ":", "connection_method", "=", "'SMTP_SSL'", "if", "self", ".", "ssl", "else", "'SMTP'", "self", ".", "_logger", ".", "debug", "(", "'Trying to connect via {}'", ".", "format", "(", "connection_method", ")", ")", "smtp", "...
Initializes a connection to the smtp server :return: True on success, False otherwise
[ "Initializes", "a", "connection", "to", "the", "smtp", "server" ]
train
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L80-L100
costastf/emaillib
emaillib/emaillib.py
SmtpServer.send
def send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'): """Sends the email :param sender: The server of the message :param recipients: Th...
python
def send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'): """Sends the email :param sender: The server of the message :param recipients: Th...
[ "def", "send", "(", "self", ",", "sender", ",", "recipients", ",", "cc", "=", "None", ",", "bcc", "=", "None", ",", "subject", "=", "''", ",", "body", "=", "''", ",", "attachments", "=", "None", ",", "content", "=", "'text'", ")", ":", "if", "not...
Sends the email :param sender: The server of the message :param recipients: The recipients (To:) of the message :param cc: The CC recipients of the message :param bcc: The BCC recipients of the message :param subject: The subject of the message :param body: The body of t...
[ "Sends", "the", "email" ]
train
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L102-L147
costastf/emaillib
emaillib/emaillib.py
SmtpServer.disconnect
def disconnect(self): """Disconnects from the remote smtp server :return: True on success, False otherwise """ if self.connected: try: self._smtp.close() self._connected = False result = True except Exception: # no...
python
def disconnect(self): """Disconnects from the remote smtp server :return: True on success, False otherwise """ if self.connected: try: self._smtp.close() self._connected = False result = True except Exception: # no...
[ "def", "disconnect", "(", "self", ")", ":", "if", "self", ".", "connected", ":", "try", ":", "self", ".", "_smtp", ".", "close", "(", ")", "self", ".", "_connected", "=", "False", "result", "=", "True", "except", "Exception", ":", "# noqa", "self", "...
Disconnects from the remote smtp server :return: True on success, False otherwise
[ "Disconnects", "from", "the", "remote", "smtp", "server" ]
train
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L149-L162
costastf/emaillib
emaillib/emaillib.py
EasySender.send
def send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'): """Sends the email by connecting and disconnecting after the send :param sender: The send...
python
def send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'): """Sends the email by connecting and disconnecting after the send :param sender: The send...
[ "def", "send", "(", "self", ",", "sender", ",", "recipients", ",", "cc", "=", "None", ",", "bcc", "=", "None", ",", "subject", "=", "''", ",", "body", "=", "''", ",", "attachments", "=", "None", ",", "content", "=", "'text'", ")", ":", "self", "....
Sends the email by connecting and disconnecting after the send :param sender: The sender of the message :param recipients: The recipients (To:) of the message :param cc: The CC recipients of the message :param bcc: The BCC recipients of the message :param subject: The subject of...
[ "Sends", "the", "email", "by", "connecting", "and", "disconnecting", "after", "the", "send" ]
train
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L182-L214
costastf/emaillib
emaillib/emaillib.py
Message._setup_message
def _setup_message(self): """Constructs the actual underlying message with provided values""" if self.content == 'html': self._message = MIMEMultipart('alternative') part = MIMEText(self.body, 'html', 'UTF-8') else: self._message = MIMEMultipart() ...
python
def _setup_message(self): """Constructs the actual underlying message with provided values""" if self.content == 'html': self._message = MIMEMultipart('alternative') part = MIMEText(self.body, 'html', 'UTF-8') else: self._message = MIMEMultipart() ...
[ "def", "_setup_message", "(", "self", ")", ":", "if", "self", ".", "content", "==", "'html'", ":", "self", ".", "_message", "=", "MIMEMultipart", "(", "'alternative'", ")", "part", "=", "MIMEText", "(", "self", ".", "body", ",", "'html'", ",", "'UTF-8'",...
Constructs the actual underlying message with provided values
[ "Constructs", "the", "actual", "underlying", "message", "with", "provided", "values" ]
train
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L250-L267
costastf/emaillib
emaillib/emaillib.py
Message._validate_simple
def _validate_simple(email): """Does a simple validation of an email by matching it to a regexps :param email: The email to check :return: The valid Email address :raises: ValueError if value is not a valid email """ name, address = parseaddr(email) if not re.ma...
python
def _validate_simple(email): """Does a simple validation of an email by matching it to a regexps :param email: The email to check :return: The valid Email address :raises: ValueError if value is not a valid email """ name, address = parseaddr(email) if not re.ma...
[ "def", "_validate_simple", "(", "email", ")", ":", "name", ",", "address", "=", "parseaddr", "(", "email", ")", "if", "not", "re", ".", "match", "(", "'[^@]+@[^@]+\\.[^@]+'", ",", "address", ")", ":", "raise", "ValueError", "(", "'Invalid email :{email}'", "...
Does a simple validation of an email by matching it to a regexps :param email: The email to check :return: The valid Email address :raises: ValueError if value is not a valid email
[ "Does", "a", "simple", "validation", "of", "an", "email", "by", "matching", "it", "to", "a", "regexps" ]
train
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L270-L281
radjkarl/appBase
appbase/mainWindowRessources/menuabout.py
MenuAbout.setModule
def setModule(self, mod): """ fill the about about label txt with the module attributes of the module """ txt = """<b>%s</b> - %s<br><br> Author: %s<br> Email: %s<br> Version: %s<br> License: %s<br> Url: <a href="%s">%s</a>""" % ( ...
python
def setModule(self, mod): """ fill the about about label txt with the module attributes of the module """ txt = """<b>%s</b> - %s<br><br> Author: %s<br> Email: %s<br> Version: %s<br> License: %s<br> Url: <a href="%s">%s</a>""" % ( ...
[ "def", "setModule", "(", "self", ",", "mod", ")", ":", "txt", "=", "\"\"\"<b>%s</b> - %s<br><br>\r\nAuthor: %s<br>\r\nEmail: %s<br>\r\nVersion: %s<br>\r\nLicense: %s<br>\r\nUrl: <a href=\"%s\">%s</a>\"\"\"", "%", "(", "mod", ".", "__name__", ","...
fill the about about label txt with the module attributes of the module
[ "fill", "the", "about", "about", "label", "txt", "with", "the", "module", "attributes", "of", "the", "module" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/mainWindowRessources/menuabout.py#L30-L48
radjkarl/appBase
appbase/mainWindowRessources/menuabout.py
MenuAbout.setInstitutionLogo
def setInstitutionLogo(self, pathList: tuple): """ takes one or more [logo].svg paths if logo should be clickable, set pathList = ( (my_path1.svg,www.something1.html), (my_path2.svg,www.something2.html), ...) """...
python
def setInstitutionLogo(self, pathList: tuple): """ takes one or more [logo].svg paths if logo should be clickable, set pathList = ( (my_path1.svg,www.something1.html), (my_path2.svg,www.something2.html), ...) """...
[ "def", "setInstitutionLogo", "(", "self", ",", "pathList", ":", "tuple", ")", ":", "for", "p", "in", "pathList", ":", "url", "=", "None", "if", "type", "(", "p", ")", "in", "(", "list", ",", "tuple", ")", ":", "p", ",", "url", "=", "p", "logo", ...
takes one or more [logo].svg paths if logo should be clickable, set pathList = ( (my_path1.svg,www.something1.html), (my_path2.svg,www.something2.html), ...)
[ "takes", "one", "or", "more", "[", "logo", "]", ".", "svg", "paths", "if", "logo", "should", "be", "clickable", "set", "pathList", "=", "(", "(", "my_path1", ".", "svg", "www", ".", "something1", ".", "html", ")", "(", "my_path2", ".", "svg", "www", ...
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/mainWindowRessources/menuabout.py#L50-L71
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/filters/dup_filter.py
save_cache
def save_cache(cache): """ Save cahce to the disk. Args: cache (set): Set with cached data. """ with open(settings.DUP_FILTER_FILE, "w") as f: f.write( json.dumps(list(cache)) )
python
def save_cache(cache): """ Save cahce to the disk. Args: cache (set): Set with cached data. """ with open(settings.DUP_FILTER_FILE, "w") as f: f.write( json.dumps(list(cache)) )
[ "def", "save_cache", "(", "cache", ")", ":", "with", "open", "(", "settings", ".", "DUP_FILTER_FILE", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "list", "(", "cache", ")", ")", ")" ]
Save cahce to the disk. Args: cache (set): Set with cached data.
[ "Save", "cahce", "to", "the", "disk", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/filters/dup_filter.py#L29-L39
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/filters/dup_filter.py
load_cache
def load_cache(): """ Load cache from the disk. Return: set: Deserialized data from disk. """ if not os.path.exists(settings.DUP_FILTER_FILE): return set() with open(settings.DUP_FILTER_FILE) as f: return set( json.loads(f.read()) )
python
def load_cache(): """ Load cache from the disk. Return: set: Deserialized data from disk. """ if not os.path.exists(settings.DUP_FILTER_FILE): return set() with open(settings.DUP_FILTER_FILE) as f: return set( json.loads(f.read()) )
[ "def", "load_cache", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "settings", ".", "DUP_FILTER_FILE", ")", ":", "return", "set", "(", ")", "with", "open", "(", "settings", ".", "DUP_FILTER_FILE", ")", "as", "f", ":", "return", "...
Load cache from the disk. Return: set: Deserialized data from disk.
[ "Load", "cache", "from", "the", "disk", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/filters/dup_filter.py#L42-L55
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/filters/dup_filter.py
filter_publication
def filter_publication(publication, cache=_CACHE): """ Deduplication function, which compares `publication` with samples stored in `cache`. If the match NOT is found, `publication` is returned, else None. Args: publication (obj): :class:`.Publication` instance. cache (obj): Cache which ...
python
def filter_publication(publication, cache=_CACHE): """ Deduplication function, which compares `publication` with samples stored in `cache`. If the match NOT is found, `publication` is returned, else None. Args: publication (obj): :class:`.Publication` instance. cache (obj): Cache which ...
[ "def", "filter_publication", "(", "publication", ",", "cache", "=", "_CACHE", ")", ":", "if", "cache", "is", "None", ":", "cache", "=", "load_cache", "(", ")", "if", "publication", ".", "_get_hash", "(", ")", "in", "cache", ":", "return", "None", "cache"...
Deduplication function, which compares `publication` with samples stored in `cache`. If the match NOT is found, `publication` is returned, else None. Args: publication (obj): :class:`.Publication` instance. cache (obj): Cache which is used for lookups. Returns: obj/None: Depends wh...
[ "Deduplication", "function", "which", "compares", "publication", "with", "samples", "stored", "in", "cache", ".", "If", "the", "match", "NOT", "is", "found", "publication", "is", "returned", "else", "None", "." ]
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/filters/dup_filter.py#L58-L80
dr4ke616/pinky
pinky/scripts/utils.py
handle_stop_command
def handle_stop_command(srv, pid): """ Kill the running service :param srv: `str` containing the service to kill passed in as underscore_case """ service = 'pinky_{}'.format(srv) twisted_pid = filepath.FilePath(pid) if not twisted_pid.exists(): print('error: {}.pid file c...
python
def handle_stop_command(srv, pid): """ Kill the running service :param srv: `str` containing the service to kill passed in as underscore_case """ service = 'pinky_{}'.format(srv) twisted_pid = filepath.FilePath(pid) if not twisted_pid.exists(): print('error: {}.pid file c...
[ "def", "handle_stop_command", "(", "srv", ",", "pid", ")", ":", "service", "=", "'pinky_{}'", ".", "format", "(", "srv", ")", "twisted_pid", "=", "filepath", ".", "FilePath", "(", "pid", ")", "if", "not", "twisted_pid", ".", "exists", "(", ")", ":", "p...
Kill the running service :param srv: `str` containing the service to kill passed in as underscore_case
[ "Kill", "the", "running", "service", ":", "param", "srv", ":", "str", "containing", "the", "service", "to", "kill", "passed", "in", "as", "underscore_case" ]
train
https://github.com/dr4ke616/pinky/blob/35c165f5a1d410be467621f3152df1dbf458622a/pinky/scripts/utils.py#L39-L58
minhhoit/yacms
yacms/core/fields.py
RichTextField.formfield
def formfield(self, **kwargs): """ Apply the widget class defined by the ``RICHTEXT_WIDGET_CLASS`` setting. """ default = kwargs.get("widget", None) or AdminTextareaWidget if default is AdminTextareaWidget: from yacms.conf import settings richtext_...
python
def formfield(self, **kwargs): """ Apply the widget class defined by the ``RICHTEXT_WIDGET_CLASS`` setting. """ default = kwargs.get("widget", None) or AdminTextareaWidget if default is AdminTextareaWidget: from yacms.conf import settings richtext_...
[ "def", "formfield", "(", "self", ",", "*", "*", "kwargs", ")", ":", "default", "=", "kwargs", ".", "get", "(", "\"widget\"", ",", "None", ")", "or", "AdminTextareaWidget", "if", "default", "is", "AdminTextareaWidget", ":", "from", "yacms", ".", "conf", "...
Apply the widget class defined by the ``RICHTEXT_WIDGET_CLASS`` setting.
[ "Apply", "the", "widget", "class", "defined", "by", "the", "RICHTEXT_WIDGET_CLASS", "setting", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/fields.py#L29-L47
Pringley/spyglass
spyglass/util.py
get
def get(url): """Query a web URL. Return a Response object with the following attributes: - text: the full text of the web page - soup: a BeautifulSoup object representing the web page """ text = urlopen(url).read() soup = BeautifulSoup(text) return Response(text=text, soup=soup)
python
def get(url): """Query a web URL. Return a Response object with the following attributes: - text: the full text of the web page - soup: a BeautifulSoup object representing the web page """ text = urlopen(url).read() soup = BeautifulSoup(text) return Response(text=text, soup=soup)
[ "def", "get", "(", "url", ")", ":", "text", "=", "urlopen", "(", "url", ")", ".", "read", "(", ")", "soup", "=", "BeautifulSoup", "(", "text", ")", "return", "Response", "(", "text", "=", "text", ",", "soup", "=", "soup", ")" ]
Query a web URL. Return a Response object with the following attributes: - text: the full text of the web page - soup: a BeautifulSoup object representing the web page
[ "Query", "a", "web", "URL", "." ]
train
https://github.com/Pringley/spyglass/blob/091d74f34837673af936daa9f462ad8216be9916/spyglass/util.py#L7-L17
bennylope/garland
garland.py
mock_decorator
def mock_decorator(*a, **k): """ An pass-through decorator that returns the underlying function. This is used as the default for replacing decorators. """ # This is a decorator without parameters, e.g. # # @login_required # def some_view(request): # ... # if a: #...
python
def mock_decorator(*a, **k): """ An pass-through decorator that returns the underlying function. This is used as the default for replacing decorators. """ # This is a decorator without parameters, e.g. # # @login_required # def some_view(request): # ... # if a: #...
[ "def", "mock_decorator", "(", "*", "a", ",", "*", "*", "k", ")", ":", "# This is a decorator without parameters, e.g.", "#", "# @login_required", "# def some_view(request):", "# ...", "#", "if", "a", ":", "# This could fail in the instance where a callable argument is pas...
An pass-through decorator that returns the underlying function. This is used as the default for replacing decorators.
[ "An", "pass", "-", "through", "decorator", "that", "returns", "the", "underlying", "function", "." ]
train
https://github.com/bennylope/garland/blob/3540d80043f096c16fa2cbc48609aee849f18995/garland.py#L21-L51
bennylope/garland
garland.py
tinsel
def tinsel(to_patch, module_name, decorator=mock_decorator): """ Decorator for simple in-place decorator mocking for tests Args: to_patch: the string path of the function to patch module_name: complete string path of the module to reload decorator (optional): replacement decorator. ...
python
def tinsel(to_patch, module_name, decorator=mock_decorator): """ Decorator for simple in-place decorator mocking for tests Args: to_patch: the string path of the function to patch module_name: complete string path of the module to reload decorator (optional): replacement decorator. ...
[ "def", "tinsel", "(", "to_patch", ",", "module_name", ",", "decorator", "=", "mock_decorator", ")", ":", "def", "fn_decorator", "(", "function", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "patch", "(", "to_...
Decorator for simple in-place decorator mocking for tests Args: to_patch: the string path of the function to patch module_name: complete string path of the module to reload decorator (optional): replacement decorator. By default a pass-through will be used. Returns: ...
[ "Decorator", "for", "simple", "in", "-", "place", "decorator", "mocking", "for", "tests" ]
train
https://github.com/bennylope/garland/blob/3540d80043f096c16fa2cbc48609aee849f18995/garland.py#L54-L78
akatrevorjay/uninhibited
uninhibited/async/__init__.py
EventFireIter.anext
async def anext(self): """Fetch the next value from the iterable.""" try: f = next(self._iter) except StopIteration as exc: raise StopAsyncIteration() from exc return await f
python
async def anext(self): """Fetch the next value from the iterable.""" try: f = next(self._iter) except StopIteration as exc: raise StopAsyncIteration() from exc return await f
[ "async", "def", "anext", "(", "self", ")", ":", "try", ":", "f", "=", "next", "(", "self", ".", "_iter", ")", "except", "StopIteration", "as", "exc", ":", "raise", "StopAsyncIteration", "(", ")", "from", "exc", "return", "await", "f" ]
Fetch the next value from the iterable.
[ "Fetch", "the", "next", "value", "from", "the", "iterable", "." ]
train
https://github.com/akatrevorjay/uninhibited/blob/f23079fe61cf831fa274d3c60bda8076c571d3f1/uninhibited/async/__init__.py#L27-L33
xtrementl/focus
focus/parser/lexer.py
SettingLexer._new_token
def _new_token(self, chars=None, line_no=None): """ Appends new token to token stream. `chars` List of token characters. Defaults to current token list. `line_no` Line number for token. Defaults to current line number. """ if not line...
python
def _new_token(self, chars=None, line_no=None): """ Appends new token to token stream. `chars` List of token characters. Defaults to current token list. `line_no` Line number for token. Defaults to current line number. """ if not line...
[ "def", "_new_token", "(", "self", ",", "chars", "=", "None", ",", "line_no", "=", "None", ")", ":", "if", "not", "line_no", ":", "line_no", "=", "self", ".", "_line_no", "if", "not", "chars", ":", "chars", "=", "self", ".", "_token_chars", "if", "cha...
Appends new token to token stream. `chars` List of token characters. Defaults to current token list. `line_no` Line number for token. Defaults to current line number.
[ "Appends", "new", "token", "to", "token", "stream", "." ]
train
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L65-L83
xtrementl/focus
focus/parser/lexer.py
SettingLexer._process_newline
def _process_newline(self, char): """ Process a newline character. """ state = self._state # inside string, just append char to token if state == self.ST_STRING: self._token_chars.append(char) else: # otherwise, add new token self...
python
def _process_newline(self, char): """ Process a newline character. """ state = self._state # inside string, just append char to token if state == self.ST_STRING: self._token_chars.append(char) else: # otherwise, add new token self...
[ "def", "_process_newline", "(", "self", ",", "char", ")", ":", "state", "=", "self", ".", "_state", "# inside string, just append char to token", "if", "state", "==", "self", ".", "ST_STRING", ":", "self", ".", "_token_chars", ".", "append", "(", "char", ")", ...
Process a newline character.
[ "Process", "a", "newline", "character", "." ]
train
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L85-L102
xtrementl/focus
focus/parser/lexer.py
SettingLexer._process_string
def _process_string(self, char): """ Process a character as part of a string token. """ if char in self.QUOTES: # end of quoted string: # 1) quote must match original quote # 2) not escaped quote (e.g. "hey there" vs "hey there\") # 3) a...
python
def _process_string(self, char): """ Process a character as part of a string token. """ if char in self.QUOTES: # end of quoted string: # 1) quote must match original quote # 2) not escaped quote (e.g. "hey there" vs "hey there\") # 3) a...
[ "def", "_process_string", "(", "self", ",", "char", ")", ":", "if", "char", "in", "self", ".", "QUOTES", ":", "# end of quoted string:", "# 1) quote must match original quote", "# 2) not escaped quote (e.g. \"hey there\" vs \"hey there\\\")", "# 3) actual escape char prior ...
Process a character as part of a string token.
[ "Process", "a", "character", "as", "part", "of", "a", "string", "token", "." ]
train
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L104-L132
xtrementl/focus
focus/parser/lexer.py
SettingLexer._process_tokens
def _process_tokens(self, char): """ Process a token character. """ if (char in self.WHITESPACE or char == self.COMMENT_START or char in self.QUOTES or char in self.TOKENS): add_token = True # escaped chars, keep going if char == self.SP...
python
def _process_tokens(self, char): """ Process a token character. """ if (char in self.WHITESPACE or char == self.COMMENT_START or char in self.QUOTES or char in self.TOKENS): add_token = True # escaped chars, keep going if char == self.SP...
[ "def", "_process_tokens", "(", "self", ",", "char", ")", ":", "if", "(", "char", "in", "self", ".", "WHITESPACE", "or", "char", "==", "self", ".", "COMMENT_START", "or", "char", "in", "self", ".", "QUOTES", "or", "char", "in", "self", ".", "TOKENS", ...
Process a token character.
[ "Process", "a", "token", "character", "." ]
train
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L134-L172
xtrementl/focus
focus/parser/lexer.py
SettingLexer._tokenize
def _tokenize(self, stream): """ Tokenizes data from the provided string. ``stream`` ``File``-like object. """ self._tokens = [] self._reset_token() self._state = self.ST_TOKEN for chunk in iter(lambda: stream.read(8192), ''): ...
python
def _tokenize(self, stream): """ Tokenizes data from the provided string. ``stream`` ``File``-like object. """ self._tokens = [] self._reset_token() self._state = self.ST_TOKEN for chunk in iter(lambda: stream.read(8192), ''): ...
[ "def", "_tokenize", "(", "self", ",", "stream", ")", ":", "self", ".", "_tokens", "=", "[", "]", "self", ".", "_reset_token", "(", ")", "self", ".", "_state", "=", "self", ".", "ST_TOKEN", "for", "chunk", "in", "iter", "(", "lambda", ":", "stream", ...
Tokenizes data from the provided string. ``stream`` ``File``-like object.
[ "Tokenizes", "data", "from", "the", "provided", "string", "." ]
train
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L174-L197
xtrementl/focus
focus/parser/lexer.py
SettingLexer.read
def read(self, filename): """ Reads the file specified and tokenizes the data for parsing. """ try: with open(filename, 'r') as _file: self._filename = filename self.readstream(_file) return True except IOError: se...
python
def read(self, filename): """ Reads the file specified and tokenizes the data for parsing. """ try: with open(filename, 'r') as _file: self._filename = filename self.readstream(_file) return True except IOError: se...
[ "def", "read", "(", "self", ",", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "_file", ":", "self", ".", "_filename", "=", "filename", "self", ".", "readstream", "(", "_file", ")", "return", "True", "excep...
Reads the file specified and tokenizes the data for parsing.
[ "Reads", "the", "file", "specified", "and", "tokenizes", "the", "data", "for", "parsing", "." ]
train
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L199-L211
xtrementl/focus
focus/parser/lexer.py
SettingLexer._escaped
def _escaped(self): """ Escape character is at end of accumulated token character list. """ chars = self._token_info['chars'] count = len(chars) # prev char is escape, keep going if count and chars[count - 1] == self.ESCAPE: chars.pop() # sw...
python
def _escaped(self): """ Escape character is at end of accumulated token character list. """ chars = self._token_info['chars'] count = len(chars) # prev char is escape, keep going if count and chars[count - 1] == self.ESCAPE: chars.pop() # sw...
[ "def", "_escaped", "(", "self", ")", ":", "chars", "=", "self", ".", "_token_info", "[", "'chars'", "]", "count", "=", "len", "(", "chars", ")", "# prev char is escape, keep going", "if", "count", "and", "chars", "[", "count", "-", "1", "]", "==", "self"...
Escape character is at end of accumulated token character list.
[ "Escape", "character", "is", "at", "end", "of", "accumulated", "token", "character", "list", "." ]
train
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L303-L316
4Kaylum/Brickfront
brickfront/client.py
Client.checkResponse
def checkResponse(request): ''' Returns if a request has an okay error code, otherwise raises InvalidRequest. ''' # Check the status code of the returned request if str(request.status_code)[0] not in ['2', '3']: w = str(request.text).split('\\r')[0][2:] r...
python
def checkResponse(request): ''' Returns if a request has an okay error code, otherwise raises InvalidRequest. ''' # Check the status code of the returned request if str(request.status_code)[0] not in ['2', '3']: w = str(request.text).split('\\r')[0][2:] r...
[ "def", "checkResponse", "(", "request", ")", ":", "# Check the status code of the returned request", "if", "str", "(", "request", ".", "status_code", ")", "[", "0", "]", "not", "in", "[", "'2'", ",", "'3'", "]", ":", "w", "=", "str", "(", "request", ".", ...
Returns if a request has an okay error code, otherwise raises InvalidRequest.
[ "Returns", "if", "a", "request", "has", "an", "okay", "error", "code", "otherwise", "raises", "InvalidRequest", "." ]
train
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L30-L39
4Kaylum/Brickfront
brickfront/client.py
Client.checkKey
def checkKey(self, key=None): ''' Checks that an API key is valid. :param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization. :returns: If the key is valid, this method will return ``True``. :rtype: `bool` :ra...
python
def checkKey(self, key=None): ''' Checks that an API key is valid. :param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization. :returns: If the key is valid, this method will return ``True``. :rtype: `bool` :ra...
[ "def", "checkKey", "(", "self", ",", "key", "=", "None", ")", ":", "# Get site", "url", "=", "Client", ".", "ENDPOINT", ".", "format", "(", "'checkKey'", ")", "if", "not", "key", ":", "key", "=", "self", ".", "apiKey", "params", "=", "{", "'apiKey'",...
Checks that an API key is valid. :param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization. :returns: If the key is valid, this method will return ``True``. :rtype: `bool` :raises: :class:`brickfront.errors.InvalidApiKey`
[ "Checks", "that", "an", "API", "key", "is", "valid", "." ]
train
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L42-L65
4Kaylum/Brickfront
brickfront/client.py
Client.login
def login(self, username, password): ''' Logs into Brickset as a user, returning a userhash, which can be used in other methods. The user hash is stored inside the client (:attr:`userHash`). :param str username: Your Brickset username. :param str password: Your Brickset password...
python
def login(self, username, password): ''' Logs into Brickset as a user, returning a userhash, which can be used in other methods. The user hash is stored inside the client (:attr:`userHash`). :param str username: Your Brickset username. :param str password: Your Brickset password...
[ "def", "login", "(", "self", ",", "username", ",", "password", ")", ":", "# Get the site", "url", "=", "Client", ".", "ENDPOINT", ".", "format", "(", "'login'", ")", "params", "=", "{", "'apiKey'", ":", "self", ".", "apiKey", ",", "'username'", ":", "u...
Logs into Brickset as a user, returning a userhash, which can be used in other methods. The user hash is stored inside the client (:attr:`userHash`). :param str username: Your Brickset username. :param str password: Your Brickset password. :returns: If the login is valid, this will retu...
[ "Logs", "into", "Brickset", "as", "a", "user", "returning", "a", "userhash", "which", "can", "be", "used", "in", "other", "methods", ".", "The", "user", "hash", "is", "stored", "inside", "the", "client", "(", ":", "attr", ":", "userHash", ")", "." ]
train
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L68-L96
4Kaylum/Brickfront
brickfront/client.py
Client.getSets
def getSets(self, **kwargs): ''' A way to get different sets from a query. All parameters are optional, but you should probably use some (so that you get results) :param str query: The thing you're searching for. :param str theme: The theme of the set. :param str subthem...
python
def getSets(self, **kwargs): ''' A way to get different sets from a query. All parameters are optional, but you should probably use some (so that you get results) :param str query: The thing you're searching for. :param str theme: The theme of the set. :param str subthem...
[ "def", "getSets", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Generate a dictionary to send as parameters", "params", "=", "{", "'apiKey'", ":", "self", ".", "apiKey", ",", "'userHash'", ":", "self", ".", "userHash", ",", "'query'", ":", "kwargs", "."...
A way to get different sets from a query. All parameters are optional, but you should probably use some (so that you get results) :param str query: The thing you're searching for. :param str theme: The theme of the set. :param str subtheme: The subtheme of the set. :param str se...
[ "A", "way", "to", "get", "different", "sets", "from", "a", "query", ".", "All", "parameters", "are", "optional", "but", "you", "should", "probably", "use", "some", "(", "so", "that", "you", "get", "results", ")" ]
train
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L99-L141
4Kaylum/Brickfront
brickfront/client.py
Client.getSet
def getSet(self, setID): ''' Gets the information of one specific build using its Brickset set ID. :param str setID: The ID of the build from Brickset. :returns: A single Build object. :rtype: :class:`brickfront.build.Build` :raises brickfront.errors.InvalidSetID: If no ...
python
def getSet(self, setID): ''' Gets the information of one specific build using its Brickset set ID. :param str setID: The ID of the build from Brickset. :returns: A single Build object. :rtype: :class:`brickfront.build.Build` :raises brickfront.errors.InvalidSetID: If no ...
[ "def", "getSet", "(", "self", ",", "setID", ")", ":", "params", "=", "{", "'apiKey'", ":", "self", ".", "apiKey", ",", "'userHash'", ":", "self", ".", "userHash", ",", "'setID'", ":", "setID", "}", "url", "=", "Client", ".", "ENDPOINT", ".", "format"...
Gets the information of one specific build using its Brickset set ID. :param str setID: The ID of the build from Brickset. :returns: A single Build object. :rtype: :class:`brickfront.build.Build` :raises brickfront.errors.InvalidSetID: If no sets exist by that ID.
[ "Gets", "the", "information", "of", "one", "specific", "build", "using", "its", "Brickset", "set", "ID", "." ]
train
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L144-L171
4Kaylum/Brickfront
brickfront/client.py
Client.getRecentlyUpdatedSets
def getRecentlyUpdatedSets(self, minutesAgo): ''' Gets the information of recently updated sets. :param int minutesAgo: The amount of time ago that the set was updated. :returns: A list of Build instances that were updated within the given time. :rtype: list .. warning::...
python
def getRecentlyUpdatedSets(self, minutesAgo): ''' Gets the information of recently updated sets. :param int minutesAgo: The amount of time ago that the set was updated. :returns: A list of Build instances that were updated within the given time. :rtype: list .. warning::...
[ "def", "getRecentlyUpdatedSets", "(", "self", ",", "minutesAgo", ")", ":", "params", "=", "{", "'apiKey'", ":", "self", ".", "apiKey", ",", "'minutesAgo'", ":", "minutesAgo", "}", "url", "=", "Client", ".", "ENDPOINT", ".", "format", "(", "'getRecentlyUpdate...
Gets the information of recently updated sets. :param int minutesAgo: The amount of time ago that the set was updated. :returns: A list of Build instances that were updated within the given time. :rtype: list .. warning:: An empty list will be returned if there are no sets in the given ...
[ "Gets", "the", "information", "of", "recently", "updated", "sets", "." ]
train
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L174-L194
4Kaylum/Brickfront
brickfront/client.py
Client.getAdditionalImages
def getAdditionalImages(self, setID): ''' Gets a list of URLs containing images of the set. :param str setID: The ID of the set you want to grab the images for. :returns: A list of URL strings. :rtype: list .. warning:: An empty list will be returned if there are no addi...
python
def getAdditionalImages(self, setID): ''' Gets a list of URLs containing images of the set. :param str setID: The ID of the set you want to grab the images for. :returns: A list of URL strings. :rtype: list .. warning:: An empty list will be returned if there are no addi...
[ "def", "getAdditionalImages", "(", "self", ",", "setID", ")", ":", "params", "=", "{", "'apiKey'", ":", "self", ".", "apiKey", ",", "'setID'", ":", "setID", "}", "url", "=", "Client", ".", "ENDPOINT", ".", "format", "(", "'getAdditionalImages'", ")", "re...
Gets a list of URLs containing images of the set. :param str setID: The ID of the set you want to grab the images for. :returns: A list of URL strings. :rtype: list .. warning:: An empty list will be returned if there are no additional images, or if the set ID is invalid.
[ "Gets", "a", "list", "of", "URLs", "containing", "images", "of", "the", "set", "." ]
train
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L197-L221