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 |
|---|---|---|---|---|---|---|---|---|---|---|
cyrus-/cypy | cypy/__init__.py | all_pairs | def all_pairs(seq1, seq2=None):
"""Yields all pairs drawn from ``seq1`` and ``seq2``.
If ``seq2`` is ``None``, ``seq2 = seq1``.
>>> stop_at.ed(all_pairs(xrange(100000), xrange(100000)), 8)
((0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7))
"""
if seq2 is None: seq2 = seq1... | python | def all_pairs(seq1, seq2=None):
"""Yields all pairs drawn from ``seq1`` and ``seq2``.
If ``seq2`` is ``None``, ``seq2 = seq1``.
>>> stop_at.ed(all_pairs(xrange(100000), xrange(100000)), 8)
((0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7))
"""
if seq2 is None: seq2 = seq1... | [
"def",
"all_pairs",
"(",
"seq1",
",",
"seq2",
"=",
"None",
")",
":",
"if",
"seq2",
"is",
"None",
":",
"seq2",
"=",
"seq1",
"for",
"item1",
"in",
"seq1",
":",
"for",
"item2",
"in",
"seq2",
":",
"yield",
"(",
"item1",
",",
"item2",
")"
] | Yields all pairs drawn from ``seq1`` and ``seq2``.
If ``seq2`` is ``None``, ``seq2 = seq1``.
>>> stop_at.ed(all_pairs(xrange(100000), xrange(100000)), 8)
((0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7)) | [
"Yields",
"all",
"pairs",
"drawn",
"from",
"seq1",
"and",
"seq2",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L515-L526 |
cyrus-/cypy | cypy/__init__.py | padded_to_same_length | def padded_to_same_length(seq1, seq2, item=0):
"""Return a pair of sequences of the same length by padding the shorter
sequence with ``item``.
The padded sequence is a tuple. The unpadded sequence is returned as-is.
"""
len1, len2 = len(seq1), len(seq2)
if len1 == len2:
return (seq1, s... | python | def padded_to_same_length(seq1, seq2, item=0):
"""Return a pair of sequences of the same length by padding the shorter
sequence with ``item``.
The padded sequence is a tuple. The unpadded sequence is returned as-is.
"""
len1, len2 = len(seq1), len(seq2)
if len1 == len2:
return (seq1, s... | [
"def",
"padded_to_same_length",
"(",
"seq1",
",",
"seq2",
",",
"item",
"=",
"0",
")",
":",
"len1",
",",
"len2",
"=",
"len",
"(",
"seq1",
")",
",",
"len",
"(",
"seq2",
")",
"if",
"len1",
"==",
"len2",
":",
"return",
"(",
"seq1",
",",
"seq2",
")",
... | Return a pair of sequences of the same length by padding the shorter
sequence with ``item``.
The padded sequence is a tuple. The unpadded sequence is returned as-is. | [
"Return",
"a",
"pair",
"of",
"sequences",
"of",
"the",
"same",
"length",
"by",
"padding",
"the",
"shorter",
"sequence",
"with",
"item",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L536-L548 |
cyrus-/cypy | cypy/__init__.py | is_int_like | def is_int_like(value):
"""Returns whether the value can be used as a standard integer.
>>> is_int_like(4)
True
>>> is_int_like(4.0)
False
>>> is_int_like("4")
False
>>> is_int_like("abc")
False
"""
try:
if isinstance(value, int): ret... | python | def is_int_like(value):
"""Returns whether the value can be used as a standard integer.
>>> is_int_like(4)
True
>>> is_int_like(4.0)
False
>>> is_int_like("4")
False
>>> is_int_like("abc")
False
"""
try:
if isinstance(value, int): ret... | [
"def",
"is_int_like",
"(",
"value",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"return",
"True",
"return",
"int",
"(",
"value",
")",
"==",
"value",
"and",
"str",
"(",
"value",
")",
".",
"isdigit",
"(",
")",
"excep... | Returns whether the value can be used as a standard integer.
>>> is_int_like(4)
True
>>> is_int_like(4.0)
False
>>> is_int_like("4")
False
>>> is_int_like("abc")
False | [
"Returns",
"whether",
"the",
"value",
"can",
"be",
"used",
"as",
"a",
"standard",
"integer",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L583-L600 |
cyrus-/cypy | cypy/__init__.py | is_float_like | def is_float_like(value):
"""Returns whether the value acts like a standard float.
>>> is_float_like(4.0)
True
>>> is_float_like(numpy.float32(4.0))
True
>>> is_float_like(numpy.int32(4.0))
False
>>> is_float_like(4)
False
"""
try:
if... | python | def is_float_like(value):
"""Returns whether the value acts like a standard float.
>>> is_float_like(4.0)
True
>>> is_float_like(numpy.float32(4.0))
True
>>> is_float_like(numpy.int32(4.0))
False
>>> is_float_like(4)
False
"""
try:
if... | [
"def",
"is_float_like",
"(",
"value",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"return",
"True",
"return",
"float",
"(",
"value",
")",
"==",
"value",
"and",
"not",
"str",
"(",
"value",
")",
".",
"isdigit",
"(",
... | Returns whether the value acts like a standard float.
>>> is_float_like(4.0)
True
>>> is_float_like(numpy.float32(4.0))
True
>>> is_float_like(numpy.int32(4.0))
False
>>> is_float_like(4)
False | [
"Returns",
"whether",
"the",
"value",
"acts",
"like",
"a",
"standard",
"float",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L602-L619 |
cyrus-/cypy | cypy/__init__.py | make_symmetric | def make_symmetric(dict):
"""Makes the given dictionary symmetric. Values are assumed to be unique."""
for key, value in list(dict.items()):
dict[value] = key
return dict | python | def make_symmetric(dict):
"""Makes the given dictionary symmetric. Values are assumed to be unique."""
for key, value in list(dict.items()):
dict[value] = key
return dict | [
"def",
"make_symmetric",
"(",
"dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"dict",
".",
"items",
"(",
")",
")",
":",
"dict",
"[",
"value",
"]",
"=",
"key",
"return",
"dict"
] | Makes the given dictionary symmetric. Values are assumed to be unique. | [
"Makes",
"the",
"given",
"dictionary",
"symmetric",
".",
"Values",
"are",
"assumed",
"to",
"be",
"unique",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L657-L661 |
cyrus-/cypy | cypy/__init__.py | get_fn | def get_fn(callable):
"""Returns the underlying function that will be called by the () operator.
* For regular functions, returns ``callable``
* For bound methods, returns ``callable.im_func``
* For unbound methods, returns ``callable.__func__``
* For classes, returns ``callable.__i... | python | def get_fn(callable):
"""Returns the underlying function that will be called by the () operator.
* For regular functions, returns ``callable``
* For bound methods, returns ``callable.im_func``
* For unbound methods, returns ``callable.__func__``
* For classes, returns ``callable.__i... | [
"def",
"get_fn",
"(",
"callable",
")",
":",
"if",
"_inspect",
".",
"isfunction",
"(",
"callable",
")",
":",
"return",
"callable",
"if",
"_inspect",
".",
"ismethod",
"(",
"callable",
")",
":",
"try",
":",
"return",
"callable",
".",
"__func__",
"except",
"... | Returns the underlying function that will be called by the () operator.
* For regular functions, returns ``callable``
* For bound methods, returns ``callable.im_func``
* For unbound methods, returns ``callable.__func__``
* For classes, returns ``callable.__init__.__func__``.
* F... | [
"Returns",
"the",
"underlying",
"function",
"that",
"will",
"be",
"called",
"by",
"the",
"()",
"operator",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L684-L705 |
cyrus-/cypy | cypy/__init__.py | get_fn_or_method | def get_fn_or_method(callable):
"""Returns the underlying function or method that will be called by the () operator.
* For regular functions and methods, returns ``callable``
* For classes, returns ``callable.__init__``
* For callable objects, returns ``callable.__call__``
"""
if _... | python | def get_fn_or_method(callable):
"""Returns the underlying function or method that will be called by the () operator.
* For regular functions and methods, returns ``callable``
* For classes, returns ``callable.__init__``
* For callable objects, returns ``callable.__call__``
"""
if _... | [
"def",
"get_fn_or_method",
"(",
"callable",
")",
":",
"if",
"_inspect",
".",
"isfunction",
"(",
"callable",
")",
"or",
"_inspect",
".",
"ismethod",
"(",
"callable",
")",
":",
"return",
"callable",
"if",
"_inspect",
".",
"isclass",
"(",
"callable",
")",
":"... | Returns the underlying function or method that will be called by the () operator.
* For regular functions and methods, returns ``callable``
* For classes, returns ``callable.__init__``
* For callable objects, returns ``callable.__call__`` | [
"Returns",
"the",
"underlying",
"function",
"or",
"method",
"that",
"will",
"be",
"called",
"by",
"the",
"()",
"operator",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L707-L719 |
cyrus-/cypy | cypy/__init__.py | fn_kwargs | def fn_kwargs(callable):
"""Returns a dict with the kwargs from the provided function.
Example
>>> def x(a, b=0, *args, **kwargs): pass
>>> func_kwargs(x) == { 'b': 0 }
"""
fn = get_fn(callable)
(args, _, _, defaults) = _inspect.getargspec(fn)
if defaults is None: return { }
... | python | def fn_kwargs(callable):
"""Returns a dict with the kwargs from the provided function.
Example
>>> def x(a, b=0, *args, **kwargs): pass
>>> func_kwargs(x) == { 'b': 0 }
"""
fn = get_fn(callable)
(args, _, _, defaults) = _inspect.getargspec(fn)
if defaults is None: return { }
... | [
"def",
"fn_kwargs",
"(",
"callable",
")",
":",
"fn",
"=",
"get_fn",
"(",
"callable",
")",
"(",
"args",
",",
"_",
",",
"_",
",",
"defaults",
")",
"=",
"_inspect",
".",
"getargspec",
"(",
"fn",
")",
"if",
"defaults",
"is",
"None",
":",
"return",
"{",... | Returns a dict with the kwargs from the provided function.
Example
>>> def x(a, b=0, *args, **kwargs): pass
>>> func_kwargs(x) == { 'b': 0 } | [
"Returns",
"a",
"dict",
"with",
"the",
"kwargs",
"from",
"the",
"provided",
"function",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L742-L754 |
cyrus-/cypy | cypy/__init__.py | fn_available_argcount | def fn_available_argcount(callable):
"""Returns the number of explicit non-keyword arguments that the callable
can be called with.
Bound methods are called with an implicit first argument, so this takes
that into account.
Excludes *args and **kwargs declarations.
"""
fn = get_fn_or_method(... | python | def fn_available_argcount(callable):
"""Returns the number of explicit non-keyword arguments that the callable
can be called with.
Bound methods are called with an implicit first argument, so this takes
that into account.
Excludes *args and **kwargs declarations.
"""
fn = get_fn_or_method(... | [
"def",
"fn_available_argcount",
"(",
"callable",
")",
":",
"fn",
"=",
"get_fn_or_method",
"(",
"callable",
")",
"if",
"_inspect",
".",
"isfunction",
"(",
"fn",
")",
":",
"return",
"fn",
".",
"__code__",
".",
"co_argcount",
"else",
":",
"# method",
"if",
"f... | Returns the number of explicit non-keyword arguments that the callable
can be called with.
Bound methods are called with an implicit first argument, so this takes
that into account.
Excludes *args and **kwargs declarations. | [
"Returns",
"the",
"number",
"of",
"explicit",
"non",
"-",
"keyword",
"arguments",
"that",
"the",
"callable",
"can",
"be",
"called",
"with",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L756-L772 |
cyrus-/cypy | cypy/__init__.py | fn_minimum_argcount | def fn_minimum_argcount(callable):
"""Returns the minimum number of arguments that must be provided for the call to succeed."""
fn = get_fn(callable)
available_argcount = fn_available_argcount(callable)
try:
return available_argcount - len(fn.__defaults__)
except TypeError:
return av... | python | def fn_minimum_argcount(callable):
"""Returns the minimum number of arguments that must be provided for the call to succeed."""
fn = get_fn(callable)
available_argcount = fn_available_argcount(callable)
try:
return available_argcount - len(fn.__defaults__)
except TypeError:
return av... | [
"def",
"fn_minimum_argcount",
"(",
"callable",
")",
":",
"fn",
"=",
"get_fn",
"(",
"callable",
")",
"available_argcount",
"=",
"fn_available_argcount",
"(",
"callable",
")",
"try",
":",
"return",
"available_argcount",
"-",
"len",
"(",
"fn",
".",
"__defaults__",
... | Returns the minimum number of arguments that must be provided for the call to succeed. | [
"Returns",
"the",
"minimum",
"number",
"of",
"arguments",
"that",
"must",
"be",
"provided",
"for",
"the",
"call",
"to",
"succeed",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L774-L781 |
cyrus-/cypy | cypy/__init__.py | fn_signature | def fn_signature(callable,
argument_transform=(lambda name: name),
default_transform=(lambda name, value: "%s=%s" %
(name, repr(value))),
vararg_transform=(lambda name: "*" + name),
kwargs_trans... | python | def fn_signature(callable,
argument_transform=(lambda name: name),
default_transform=(lambda name, value: "%s=%s" %
(name, repr(value))),
vararg_transform=(lambda name: "*" + name),
kwargs_trans... | [
"def",
"fn_signature",
"(",
"callable",
",",
"argument_transform",
"=",
"(",
"lambda",
"name",
":",
"name",
")",
",",
"default_transform",
"=",
"(",
"lambda",
"name",
",",
"value",
":",
"\"%s=%s\"",
"%",
"(",
"name",
",",
"repr",
"(",
"value",
")",
")",
... | Returns the signature of the provided callable as a tuple of strings. | [
"Returns",
"the",
"signature",
"of",
"the",
"provided",
"callable",
"as",
"a",
"tuple",
"of",
"strings",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L793-L819 |
cyrus-/cypy | cypy/__init__.py | fn_arg_hash_function | def fn_arg_hash_function(fn):
"""Creates a hash function which will return the same hashable value if
passed a set of *args and **kwargs which are equivalent from the
perspective of a function call.
That is, the order of keyword arguments, or the fact that an argument
without a default was c... | python | def fn_arg_hash_function(fn):
"""Creates a hash function which will return the same hashable value if
passed a set of *args and **kwargs which are equivalent from the
perspective of a function call.
That is, the order of keyword arguments, or the fact that an argument
without a default was c... | [
"def",
"fn_arg_hash_function",
"(",
"fn",
")",
":",
"fn",
"=",
"get_fn",
"(",
"fn",
")",
"n_explicit",
"=",
"fn_available_argcount",
"(",
"fn",
")",
"has_args",
"=",
"fn_has_args",
"(",
"fn",
")",
"has_kwargs",
"=",
"fn_has_kwargs",
"(",
"fn",
")",
"defaul... | Creates a hash function which will return the same hashable value if
passed a set of *args and **kwargs which are equivalent from the
perspective of a function call.
That is, the order of keyword arguments, or the fact that an argument
without a default was called as a kwarg, will not produce a ... | [
"Creates",
"a",
"hash",
"function",
"which",
"will",
"return",
"the",
"same",
"hashable",
"value",
"if",
"passed",
"a",
"set",
"of",
"*",
"args",
"and",
"**",
"kwargs",
"which",
"are",
"equivalent",
"from",
"the",
"perspective",
"of",
"a",
"function",
"cal... | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L822-L888 |
cyrus-/cypy | cypy/__init__.py | decorator | def decorator(d):
"""Creates a proper decorator.
If the default for the first (function) argument is None, creates a
version which be invoked as either @decorator or @decorator(kwargs...).
See examples below.
"""
defaults = d.__defaults__
if defaults and defaults[0] is None:
# Can ... | python | def decorator(d):
"""Creates a proper decorator.
If the default for the first (function) argument is None, creates a
version which be invoked as either @decorator or @decorator(kwargs...).
See examples below.
"""
defaults = d.__defaults__
if defaults and defaults[0] is None:
# Can ... | [
"def",
"decorator",
"(",
"d",
")",
":",
"defaults",
"=",
"d",
".",
"__defaults__",
"if",
"defaults",
"and",
"defaults",
"[",
"0",
"]",
"is",
"None",
":",
"# Can be applied as @decorator or @decorator(kwargs) because",
"# first argument is None",
"def",
"decorate",
"... | Creates a proper decorator.
If the default for the first (function) argument is None, creates a
version which be invoked as either @decorator or @decorator(kwargs...).
See examples below. | [
"Creates",
"a",
"proper",
"decorator",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L910-L936 |
cyrus-/cypy | cypy/__init__.py | memoize | def memoize(fn=None):
"""Caches the result of the provided function."""
cache = { }
arg_hash_fn = fn_arg_hash_function(fn)
def decorated(*args, **kwargs):
try:
hash_ = arg_hash_fn(*args, **kwargs)
except TypeError:
return fn(*args, **kwargs)
try:
... | python | def memoize(fn=None):
"""Caches the result of the provided function."""
cache = { }
arg_hash_fn = fn_arg_hash_function(fn)
def decorated(*args, **kwargs):
try:
hash_ = arg_hash_fn(*args, **kwargs)
except TypeError:
return fn(*args, **kwargs)
try:
... | [
"def",
"memoize",
"(",
"fn",
"=",
"None",
")",
":",
"cache",
"=",
"{",
"}",
"arg_hash_fn",
"=",
"fn_arg_hash_function",
"(",
"fn",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"hash_",
"=",
"arg_hash_fn",
... | Caches the result of the provided function. | [
"Caches",
"the",
"result",
"of",
"the",
"provided",
"function",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L940-L959 |
cyrus-/cypy | cypy/__init__.py | safe_setattr | def safe_setattr(obj, name, value):
"""Attempt to setattr but catch AttributeErrors."""
try:
setattr(obj, name, value)
return True
except AttributeError:
return False | python | def safe_setattr(obj, name, value):
"""Attempt to setattr but catch AttributeErrors."""
try:
setattr(obj, name, value)
return True
except AttributeError:
return False | [
"def",
"safe_setattr",
"(",
"obj",
",",
"name",
",",
"value",
")",
":",
"try",
":",
"setattr",
"(",
"obj",
",",
"name",
",",
"value",
")",
"return",
"True",
"except",
"AttributeError",
":",
"return",
"False"
] | Attempt to setattr but catch AttributeErrors. | [
"Attempt",
"to",
"setattr",
"but",
"catch",
"AttributeErrors",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L979-L985 |
cyrus-/cypy | cypy/__init__.py | method_call_if_def | def method_call_if_def(obj, attr_name, m_name, default, *args, **kwargs):
"""Calls the provided method if it is defined.
Returns default if not defined.
"""
try:
attr = getattr(obj, attr_name)
except AttributeError:
return default
else:
return getattr(attr, m_name)(*args... | python | def method_call_if_def(obj, attr_name, m_name, default, *args, **kwargs):
"""Calls the provided method if it is defined.
Returns default if not defined.
"""
try:
attr = getattr(obj, attr_name)
except AttributeError:
return default
else:
return getattr(attr, m_name)(*args... | [
"def",
"method_call_if_def",
"(",
"obj",
",",
"attr_name",
",",
"m_name",
",",
"default",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"attr",
"=",
"getattr",
"(",
"obj",
",",
"attr_name",
")",
"except",
"AttributeError",
":",
"retu... | Calls the provided method if it is defined.
Returns default if not defined. | [
"Calls",
"the",
"provided",
"method",
"if",
"it",
"is",
"defined",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L987-L997 |
cyrus-/cypy | cypy/__init__.py | call_on_if_def | def call_on_if_def(obj, attr_name, callable, default, *args, **kwargs):
"""Calls the provided callable on the provided attribute of ``obj`` if it is defined.
If not, returns default.
"""
try:
attr = getattr(obj, attr_name)
except AttributeError:
return default
else:
retu... | python | def call_on_if_def(obj, attr_name, callable, default, *args, **kwargs):
"""Calls the provided callable on the provided attribute of ``obj`` if it is defined.
If not, returns default.
"""
try:
attr = getattr(obj, attr_name)
except AttributeError:
return default
else:
retu... | [
"def",
"call_on_if_def",
"(",
"obj",
",",
"attr_name",
",",
"callable",
",",
"default",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"attr",
"=",
"getattr",
"(",
"obj",
",",
"attr_name",
")",
"except",
"AttributeError",
":",
"return... | Calls the provided callable on the provided attribute of ``obj`` if it is defined.
If not, returns default. | [
"Calls",
"the",
"provided",
"callable",
"on",
"the",
"provided",
"attribute",
"of",
"obj",
"if",
"it",
"is",
"defined",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L999-L1009 |
cyrus-/cypy | cypy/__init__.py | define_property | def define_property(obj, name, fget=None, fset=None, fdel=None, doc=None):
"""Defines a @property dynamically for an instance rather than a class."""
if hasattr(fget, '__get__'): # can pass a property declaration too
prop = fget
else:
prop = property(fget, fset, fdel, doc)
cls = obj.__c... | python | def define_property(obj, name, fget=None, fset=None, fdel=None, doc=None):
"""Defines a @property dynamically for an instance rather than a class."""
if hasattr(fget, '__get__'): # can pass a property declaration too
prop = fget
else:
prop = property(fget, fset, fdel, doc)
cls = obj.__c... | [
"def",
"define_property",
"(",
"obj",
",",
"name",
",",
"fget",
"=",
"None",
",",
"fset",
"=",
"None",
",",
"fdel",
"=",
"None",
",",
"doc",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"fget",
",",
"'__get__'",
")",
":",
"# can pass a property declara... | Defines a @property dynamically for an instance rather than a class. | [
"Defines",
"a"
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1019-L1029 |
cyrus-/cypy | cypy/__init__.py | define_properties | def define_properties(obj, props):
"""Defines multiple @properties dynamically for an instance rather than a class."""
cls = obj.__class__
dct = {
'__doc__': cls.__doc__
}
for name, defn in list(props.items()):
if is_callable(defn):
defn = property(defn)
elif not... | python | def define_properties(obj, props):
"""Defines multiple @properties dynamically for an instance rather than a class."""
cls = obj.__class__
dct = {
'__doc__': cls.__doc__
}
for name, defn in list(props.items()):
if is_callable(defn):
defn = property(defn)
elif not... | [
"def",
"define_properties",
"(",
"obj",
",",
"props",
")",
":",
"cls",
"=",
"obj",
".",
"__class__",
"dct",
"=",
"{",
"'__doc__'",
":",
"cls",
".",
"__doc__",
"}",
"for",
"name",
",",
"defn",
"in",
"list",
"(",
"props",
".",
"items",
"(",
")",
")",... | Defines multiple @properties dynamically for an instance rather than a class. | [
"Defines",
"multiple"
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1031-L1045 |
cyrus-/cypy | cypy/__init__.py | replaceable | def replaceable(decorator):
"""A descriptor modifier which allows a setattr to succeed even if __get__ is defined.
Formally, this turns a data descriptor into a non-data descriptor. Discards
the implementation of __set__ and __delete__ if it exists, so be wary when
not using with ``property``.
... | python | def replaceable(decorator):
"""A descriptor modifier which allows a setattr to succeed even if __get__ is defined.
Formally, this turns a data descriptor into a non-data descriptor. Discards
the implementation of __set__ and __delete__ if it exists, so be wary when
not using with ``property``.
... | [
"def",
"replaceable",
"(",
"decorator",
")",
":",
"def",
"decorate",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"parent",
"=",
"decorator",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"#doc = _add_msg(getattr(parent,... | A descriptor modifier which allows a setattr to succeed even if __get__ is defined.
Formally, this turns a data descriptor into a non-data descriptor. Discards
the implementation of __set__ and __delete__ if it exists, so be wary when
not using with ``property``. | [
"A",
"descriptor",
"modifier",
"which",
"allows",
"a",
"setattr",
"to",
"succeed",
"even",
"if",
"__get__",
"is",
"defined",
".",
"Formally",
"this",
"turns",
"a",
"data",
"descriptor",
"into",
"a",
"non",
"-",
"data",
"descriptor",
".",
"Discards",
"the",
... | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1123-L1135 |
cyrus-/cypy | cypy/__init__.py | lazy | def lazy(decorator):
"""A descriptor modifier which caches the result of __get__."""
def decorate(fn, *args, **kwargs):
name = fn.__name__
parent = decorator(fn, *args, **kwargs)
#doc = _add_msg(getattr(parent, '__doc__', None), '*@lazy*')
doc = getattr(parent, '__doc__', None)
... | python | def lazy(decorator):
"""A descriptor modifier which caches the result of __get__."""
def decorate(fn, *args, **kwargs):
name = fn.__name__
parent = decorator(fn, *args, **kwargs)
#doc = _add_msg(getattr(parent, '__doc__', None), '*@lazy*')
doc = getattr(parent, '__doc__', None)
... | [
"def",
"lazy",
"(",
"decorator",
")",
":",
"def",
"decorate",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"fn",
".",
"__name__",
"parent",
"=",
"decorator",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | A descriptor modifier which caches the result of __get__. | [
"A",
"descriptor",
"modifier",
"which",
"caches",
"the",
"result",
"of",
"__get__",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1141-L1152 |
cyrus-/cypy | cypy/__init__.py | setonce | def setonce(decorator):
"""A descriptor modifier which allows __set__ to be called at most once."""
def decorate(fn, *args, **kwargs):
parent = decorator(fn, *args, **kwargs)
#doc = _add_msg(getattr(parent, '__doc__', None), '*@setonce*')
doc = getattr(parent, '__doc__', None)
as... | python | def setonce(decorator):
"""A descriptor modifier which allows __set__ to be called at most once."""
def decorate(fn, *args, **kwargs):
parent = decorator(fn, *args, **kwargs)
#doc = _add_msg(getattr(parent, '__doc__', None), '*@setonce*')
doc = getattr(parent, '__doc__', None)
as... | [
"def",
"setonce",
"(",
"decorator",
")",
":",
"def",
"decorate",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"parent",
"=",
"decorator",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"#doc = _add_msg(getattr(parent, '__... | A descriptor modifier which allows __set__ to be called at most once. | [
"A",
"descriptor",
"modifier",
"which",
"allows",
"__set__",
"to",
"be",
"called",
"at",
"most",
"once",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1179-L1187 |
cyrus-/cypy | cypy/__init__.py | autoinit | def autoinit(fn):
"""Automates initialization so things are more composable.
* All specified kwargs in the class and all autoinit classes in
inheritance hierarchy will be setattr'd at the end of initialization,
with defaults derived from the inheritance hierarchy as well.
* If **kwargs is explicitl... | python | def autoinit(fn):
"""Automates initialization so things are more composable.
* All specified kwargs in the class and all autoinit classes in
inheritance hierarchy will be setattr'd at the end of initialization,
with defaults derived from the inheritance hierarchy as well.
* If **kwargs is explicitl... | [
"def",
"autoinit",
"(",
"fn",
")",
":",
"if",
"fn",
"is",
"None",
":",
"fn",
"=",
"_empty_init",
"if",
"fn_has_args",
"(",
"fn",
")",
":",
"raise",
"Error",
"(",
"\"*args support is not available in autoinit.\"",
")",
"# its pretty hard to support this, though doabl... | Automates initialization so things are more composable.
* All specified kwargs in the class and all autoinit classes in
inheritance hierarchy will be setattr'd at the end of initialization,
with defaults derived from the inheritance hierarchy as well.
* If **kwargs is explicitly specified, the __init__... | [
"Automates",
"initialization",
"so",
"things",
"are",
"more",
"composable",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1217-L1352 |
cyrus-/cypy | cypy/__init__.py | is_senior_subclass | def is_senior_subclass(obj, cls, testcls):
"""Determines whether the cls is the senior subclass of basecls for obj.
The most senior subclass is the first class in the mro which is a subclass
of testcls.
Use for inheritance schemes where a method should only be called once by the
most senior subcla... | python | def is_senior_subclass(obj, cls, testcls):
"""Determines whether the cls is the senior subclass of basecls for obj.
The most senior subclass is the first class in the mro which is a subclass
of testcls.
Use for inheritance schemes where a method should only be called once by the
most senior subcla... | [
"def",
"is_senior_subclass",
"(",
"obj",
",",
"cls",
",",
"testcls",
")",
":",
"for",
"base",
"in",
"obj",
".",
"__class__",
".",
"mro",
"(",
")",
":",
"if",
"base",
"is",
"cls",
":",
"return",
"True",
"else",
":",
"if",
"issubclass",
"(",
"base",
... | Determines whether the cls is the senior subclass of basecls for obj.
The most senior subclass is the first class in the mro which is a subclass
of testcls.
Use for inheritance schemes where a method should only be called once by the
most senior subclass.
Don't use if it is optional to call the b... | [
"Determines",
"whether",
"the",
"cls",
"is",
"the",
"senior",
"subclass",
"of",
"basecls",
"for",
"obj",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1403-L1426 |
cyrus-/cypy | cypy/__init__.py | _dummy_init | def _dummy_init(self, *args, **kwargs): #@UnusedVariable
"""Prevents __init__ from being called if returning a obj copy."""
cls = type(self)
old_init = cls._intern__old_init
if old_init is _NotDefined:
del cls.__init__
else:
cls.__init__ = old_init
del cls._intern__old_init | python | def _dummy_init(self, *args, **kwargs): #@UnusedVariable
"""Prevents __init__ from being called if returning a obj copy."""
cls = type(self)
old_init = cls._intern__old_init
if old_init is _NotDefined:
del cls.__init__
else:
cls.__init__ = old_init
del cls._intern__old_init | [
"def",
"_dummy_init",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#@UnusedVariable",
"cls",
"=",
"type",
"(",
"self",
")",
"old_init",
"=",
"cls",
".",
"_intern__old_init",
"if",
"old_init",
"is",
"_NotDefined",
":",
"del",
"cls",
... | Prevents __init__ from being called if returning a obj copy. | [
"Prevents",
"__init__",
"from",
"being",
"called",
"if",
"returning",
"a",
"obj",
"copy",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1560-L1568 |
cyrus-/cypy | cypy/__init__.py | string_escape | def string_escape(string, delimiter='"'):
"""Turns special characters into escape sequences in the provided string.
Supports both byte strings and unicode strings properly. Any other values
will produce None.
Example:
>>> string_escape("a line\t")
"a line\\t"
>>> string_escape(u"some fancy... | python | def string_escape(string, delimiter='"'):
"""Turns special characters into escape sequences in the provided string.
Supports both byte strings and unicode strings properly. Any other values
will produce None.
Example:
>>> string_escape("a line\t")
"a line\\t"
>>> string_escape(u"some fancy... | [
"def",
"string_escape",
"(",
"string",
",",
"delimiter",
"=",
"'\"'",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"escaped",
"=",
"string",
".",
"encode",
"(",
"\"string-escape\"",
")",
"elif",
"isinstance",
"(",
"string",
",",
"st... | Turns special characters into escape sequences in the provided string.
Supports both byte strings and unicode strings properly. Any other values
will produce None.
Example:
>>> string_escape("a line\t")
"a line\\t"
>>> string_escape(u"some fancy character: \\u9999")
u"\\u9999"
>>> stri... | [
"Turns",
"special",
"characters",
"into",
"escape",
"sequences",
"in",
"the",
"provided",
"string",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1579-L1599 |
cyrus-/cypy | cypy/__init__.py | re_line_and_indentation | def re_line_and_indentation(base_indentation,
modifiers=(True, True)):
"""Returns a re matching newline + base_indentation.
modifiers is a tuple, (include_first, include_final).
If include_first, matches indentation at the beginning of the string.
If include_final, matches ... | python | def re_line_and_indentation(base_indentation,
modifiers=(True, True)):
"""Returns a re matching newline + base_indentation.
modifiers is a tuple, (include_first, include_final).
If include_first, matches indentation at the beginning of the string.
If include_final, matches ... | [
"def",
"re_line_and_indentation",
"(",
"base_indentation",
",",
"modifiers",
"=",
"(",
"True",
",",
"True",
")",
")",
":",
"cache",
"=",
"re_line_and_indentation",
".",
"cache",
"[",
"modifiers",
"]",
"compiled",
"=",
"cache",
".",
"get",
"(",
"base_indentatio... | Returns a re matching newline + base_indentation.
modifiers is a tuple, (include_first, include_final).
If include_first, matches indentation at the beginning of the string.
If include_final, matches indentation at the end of the string.
Cached. | [
"Returns",
"a",
"re",
"matching",
"newline",
"+",
"base_indentation",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1629-L1646 |
cyrus-/cypy | cypy/__init__.py | get_base_indentation | def get_base_indentation(code, include_start=False):
"""Heuristically extracts the base indentation from the provided code.
Finds the smallest indentation following a newline not at the end of the
string.
"""
new_line_indentation = re_new_line_indentation[include_start].finditer(code)
new_line_... | python | def get_base_indentation(code, include_start=False):
"""Heuristically extracts the base indentation from the provided code.
Finds the smallest indentation following a newline not at the end of the
string.
"""
new_line_indentation = re_new_line_indentation[include_start].finditer(code)
new_line_... | [
"def",
"get_base_indentation",
"(",
"code",
",",
"include_start",
"=",
"False",
")",
":",
"new_line_indentation",
"=",
"re_new_line_indentation",
"[",
"include_start",
"]",
".",
"finditer",
"(",
"code",
")",
"new_line_indentation",
"=",
"tuple",
"(",
"m",
".",
"... | Heuristically extracts the base indentation from the provided code.
Finds the smallest indentation following a newline not at the end of the
string. | [
"Heuristically",
"extracts",
"the",
"base",
"indentation",
"from",
"the",
"provided",
"code",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1661-L1672 |
cyrus-/cypy | cypy/__init__.py | fix_indentation | def fix_indentation(code, base_indentation=None, correct_indentation="",
modifiers=(True, True)):
"""Replaces base_indentation at beginning of lines with correct_indentation.
If base_indentation is None, tries to find it using get_base_indentation.
modifiers are passed to re_line_and_in... | python | def fix_indentation(code, base_indentation=None, correct_indentation="",
modifiers=(True, True)):
"""Replaces base_indentation at beginning of lines with correct_indentation.
If base_indentation is None, tries to find it using get_base_indentation.
modifiers are passed to re_line_and_in... | [
"def",
"fix_indentation",
"(",
"code",
",",
"base_indentation",
"=",
"None",
",",
"correct_indentation",
"=",
"\"\"",
",",
"modifiers",
"=",
"(",
"True",
",",
"True",
")",
")",
":",
"if",
"base_indentation",
"is",
"None",
":",
"base_indentation",
"=",
"get_b... | Replaces base_indentation at beginning of lines with correct_indentation.
If base_indentation is None, tries to find it using get_base_indentation.
modifiers are passed to re_line_and_indentation. See there for doc. | [
"Replaces",
"base_indentation",
"at",
"beginning",
"of",
"lines",
"with",
"correct_indentation",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1683-L1693 |
cyrus-/cypy | cypy/__init__.py | intern.intern | def intern(cls_):
"""Transforms the provided class into an interned class.
That is, initializing the class multiple times with the same arguments
(even if in a different order if using keyword arguments) should
always produce the same object, and __init__ should only be called... | python | def intern(cls_):
"""Transforms the provided class into an interned class.
That is, initializing the class multiple times with the same arguments
(even if in a different order if using keyword arguments) should
always produce the same object, and __init__ should only be called... | [
"def",
"intern",
"(",
"cls_",
")",
":",
"cls_",
".",
"__pool",
"=",
"{",
"}",
"__init__",
"=",
"cls_",
".",
"__init__",
"try",
":",
"__init__",
".",
"__func__",
".",
"__hash_function",
"except",
"AttributeError",
":",
"try",
":",
"__init__",
".",
"__func... | Transforms the provided class into an interned class.
That is, initializing the class multiple times with the same arguments
(even if in a different order if using keyword arguments) should
always produce the same object, and __init__ should only be called the
first time for ... | [
"Transforms",
"the",
"provided",
"class",
"into",
"an",
"interned",
"class",
".",
"That",
"is",
"initializing",
"the",
"class",
"multiple",
"times",
"with",
"the",
"same",
"arguments",
"(",
"even",
"if",
"in",
"a",
"different",
"order",
"if",
"using",
"keywo... | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L1432-L1558 |
cyrus-/cypy | cypy/__init__.py | Naming.name | def name(self):
"""The unique name of this object, relative to the parent."""
basename = self.basename
if basename is None:
return None
parent = self.Naming_parent
if parent is None:
return basename
else:
return parent.gene... | python | def name(self):
"""The unique name of this object, relative to the parent."""
basename = self.basename
if basename is None:
return None
parent = self.Naming_parent
if parent is None:
return basename
else:
return parent.gene... | [
"def",
"name",
"(",
"self",
")",
":",
"basename",
"=",
"self",
".",
"basename",
"if",
"basename",
"is",
"None",
":",
"return",
"None",
"parent",
"=",
"self",
".",
"Naming_parent",
"if",
"parent",
"is",
"None",
":",
"return",
"basename",
"else",
":",
"r... | The unique name of this object, relative to the parent. | [
"The",
"unique",
"name",
"of",
"this",
"object",
"relative",
"to",
"the",
"parent",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2060-L2070 |
cyrus-/cypy | cypy/__init__.py | Naming.generate_unique_name | def generate_unique_name(self, basename):
"""Generates a unique name for a child given a base name."""
counts = self.__counts
try:
count = counts[basename]
counts[basename] += 1
except KeyError:
count = 0
counts[basename] = 1
... | python | def generate_unique_name(self, basename):
"""Generates a unique name for a child given a base name."""
counts = self.__counts
try:
count = counts[basename]
counts[basename] += 1
except KeyError:
count = 0
counts[basename] = 1
... | [
"def",
"generate_unique_name",
"(",
"self",
",",
"basename",
")",
":",
"counts",
"=",
"self",
".",
"__counts",
"try",
":",
"count",
"=",
"counts",
"[",
"basename",
"]",
"counts",
"[",
"basename",
"]",
"+=",
"1",
"except",
"KeyError",
":",
"count",
"=",
... | Generates a unique name for a child given a base name. | [
"Generates",
"a",
"unique",
"name",
"for",
"a",
"child",
"given",
"a",
"base",
"name",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2089-L2113 |
cyrus-/cypy | cypy/__init__.py | UpTree.add_to_parent | def add_to_parent(self):
"""Adds this node to the parent's ``children`` collection if it exists."""
parent = self.parent
if parent is not None:
try:
children = parent.children
except AttributeError: pass
else:
include(children, ... | python | def add_to_parent(self):
"""Adds this node to the parent's ``children`` collection if it exists."""
parent = self.parent
if parent is not None:
try:
children = parent.children
except AttributeError: pass
else:
include(children, ... | [
"def",
"add_to_parent",
"(",
"self",
")",
":",
"parent",
"=",
"self",
".",
"parent",
"if",
"parent",
"is",
"not",
"None",
":",
"try",
":",
"children",
"=",
"parent",
".",
"children",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"include",
"(",
... | Adds this node to the parent's ``children`` collection if it exists. | [
"Adds",
"this",
"node",
"to",
"the",
"parent",
"s",
"children",
"collection",
"if",
"it",
"exists",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2171-L2179 |
cyrus-/cypy | cypy/__init__.py | UpTree.remove_from_parent | def remove_from_parent(self):
"""Removes this node from the parent's ``children`` collection if it exists."""
parent = self.parent
if parent is not None:
try:
children = parent.children
except AttributeError: pass
else:
remove_u... | python | def remove_from_parent(self):
"""Removes this node from the parent's ``children`` collection if it exists."""
parent = self.parent
if parent is not None:
try:
children = parent.children
except AttributeError: pass
else:
remove_u... | [
"def",
"remove_from_parent",
"(",
"self",
")",
":",
"parent",
"=",
"self",
".",
"parent",
"if",
"parent",
"is",
"not",
"None",
":",
"try",
":",
"children",
"=",
"parent",
".",
"children",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"remove_upto_o... | Removes this node from the parent's ``children`` collection if it exists. | [
"Removes",
"this",
"node",
"from",
"the",
"parent",
"s",
"children",
"collection",
"if",
"it",
"exists",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2181-L2189 |
cyrus-/cypy | cypy/__init__.py | UpTree.iter_up | def iter_up(self, include_self=True):
"""Iterates up the tree to the root."""
if include_self: yield self
parent = self.parent
while parent is not None:
yield parent
try:
parent = parent.parent
except AttributeError:
ret... | python | def iter_up(self, include_self=True):
"""Iterates up the tree to the root."""
if include_self: yield self
parent = self.parent
while parent is not None:
yield parent
try:
parent = parent.parent
except AttributeError:
ret... | [
"def",
"iter_up",
"(",
"self",
",",
"include_self",
"=",
"True",
")",
":",
"if",
"include_self",
":",
"yield",
"self",
"parent",
"=",
"self",
".",
"parent",
"while",
"parent",
"is",
"not",
"None",
":",
"yield",
"parent",
"try",
":",
"parent",
"=",
"par... | Iterates up the tree to the root. | [
"Iterates",
"up",
"the",
"tree",
"to",
"the",
"root",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2191-L2200 |
cyrus-/cypy | cypy/__init__.py | UpTree.getrec | def getrec(self, name, include_self=True, *default):
"""Look up an attribute in the path to the root."""
for node in self.iter_up(include_self):
try:
return getattr(node, name)
except AttributeError: pass
if default:
return default... | python | def getrec(self, name, include_self=True, *default):
"""Look up an attribute in the path to the root."""
for node in self.iter_up(include_self):
try:
return getattr(node, name)
except AttributeError: pass
if default:
return default... | [
"def",
"getrec",
"(",
"self",
",",
"name",
",",
"include_self",
"=",
"True",
",",
"*",
"default",
")",
":",
"for",
"node",
"in",
"self",
".",
"iter_up",
"(",
"include_self",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"node",
",",
"name",
")",
... | Look up an attribute in the path to the root. | [
"Look",
"up",
"an",
"attribute",
"in",
"the",
"path",
"to",
"the",
"root",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2209-L2219 |
cyrus-/cypy | cypy/__init__.py | DownTree.trigger_hook | def trigger_hook(self, name, *args, **kwargs):
"""Recursively call a method named ``name`` with the provided args and
keyword args if defined."""
method = getattr(self, name, None)
if is_callable(method):
method(*args, **kwargs)
try:
children ... | python | def trigger_hook(self, name, *args, **kwargs):
"""Recursively call a method named ``name`` with the provided args and
keyword args if defined."""
method = getattr(self, name, None)
if is_callable(method):
method(*args, **kwargs)
try:
children ... | [
"def",
"trigger_hook",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"name",
",",
"None",
")",
"if",
"is_callable",
"(",
"method",
")",
":",
"method",
"(",
"*",
"args",
... | Recursively call a method named ``name`` with the provided args and
keyword args if defined. | [
"Recursively",
"call",
"a",
"method",
"named",
"name",
"with",
"the",
"provided",
"args",
"and",
"keyword",
"args",
"if",
"defined",
"."
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2236-L2256 |
cyrus-/cypy | cypy/__init__.py | DownTree.trigger_staged_hook | def trigger_staged_hook(self, name, *args, **kwargs):
"""Calls a three-staged hook:
1. ``"pre_"+name``
2. ``"_on_"+name``
3. ``"post_"+name``
"""
self.trigger_hook("pre_" + name, *args, **kwargs)
self.trigger_hook("on_" + name, *args, **kwargs)
... | python | def trigger_staged_hook(self, name, *args, **kwargs):
"""Calls a three-staged hook:
1. ``"pre_"+name``
2. ``"_on_"+name``
3. ``"post_"+name``
"""
self.trigger_hook("pre_" + name, *args, **kwargs)
self.trigger_hook("on_" + name, *args, **kwargs)
... | [
"def",
"trigger_staged_hook",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"trigger_hook",
"(",
"\"pre_\"",
"+",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"trigger_hook",
"(",
... | Calls a three-staged hook:
1. ``"pre_"+name``
2. ``"_on_"+name``
3. ``"post_"+name`` | [
"Calls",
"a",
"three",
"-",
"staged",
"hook",
":",
"1",
".",
"pre_",
"+",
"name",
"2",
".",
"_on_",
"+",
"name",
"3",
".",
"post_",
"+",
"name"
] | train | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/__init__.py#L2258-L2268 |
kolypto/py-asynctools | asynctools/threading/Parallel.py | Parallel._spawn_thread | def _spawn_thread(self, target):
""" Create a thread """
t = Thread(target=target)
t.daemon = True
t.start()
return t | python | def _spawn_thread(self, target):
""" Create a thread """
t = Thread(target=target)
t.daemon = True
t.start()
return t | [
"def",
"_spawn_thread",
"(",
"self",
",",
"target",
")",
":",
"t",
"=",
"Thread",
"(",
"target",
"=",
"target",
")",
"t",
".",
"daemon",
"=",
"True",
"t",
".",
"start",
"(",
")",
"return",
"t"
] | Create a thread | [
"Create",
"a",
"thread"
] | train | https://github.com/kolypto/py-asynctools/blob/04ff42d13b54d200d8cc88b3639937b63278e57c/asynctools/threading/Parallel.py#L22-L27 |
kolypto/py-asynctools | asynctools/threading/Parallel.py | Parallel._thread | def _thread(self):
""" Thread entry point: does the job once, stored results, and dies. """
# Get
args, kwargs = self._jobs.get()
# Stop thread when (None, None) comes in
if args is None and kwargs is None:
return None # Wrappers should exit as well
# Work
... | python | def _thread(self):
""" Thread entry point: does the job once, stored results, and dies. """
# Get
args, kwargs = self._jobs.get()
# Stop thread when (None, None) comes in
if args is None and kwargs is None:
return None # Wrappers should exit as well
# Work
... | [
"def",
"_thread",
"(",
"self",
")",
":",
"# Get",
"args",
",",
"kwargs",
"=",
"self",
".",
"_jobs",
".",
"get",
"(",
")",
"# Stop thread when (None, None) comes in",
"if",
"args",
"is",
"None",
"and",
"kwargs",
"is",
"None",
":",
"return",
"None",
"# Wrapp... | Thread entry point: does the job once, stored results, and dies. | [
"Thread",
"entry",
"point",
":",
"does",
"the",
"job",
"once",
"stored",
"results",
"and",
"dies",
"."
] | train | https://github.com/kolypto/py-asynctools/blob/04ff42d13b54d200d8cc88b3639937b63278e57c/asynctools/threading/Parallel.py#L36-L55 |
kolypto/py-asynctools | asynctools/threading/Parallel.py | Parallel.first | def first(self, timeout=None):
""" Wait for the first successful result to become available
:param timeout: Wait timeout, sec
:type timeout: float|int|None
:return: result, or None if all threads have failed
:rtype: *
"""
while True:
with self._jobfini... | python | def first(self, timeout=None):
""" Wait for the first successful result to become available
:param timeout: Wait timeout, sec
:type timeout: float|int|None
:return: result, or None if all threads have failed
:rtype: *
"""
while True:
with self._jobfini... | [
"def",
"first",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"while",
"True",
":",
"with",
"self",
".",
"_jobfinished",
":",
"if",
"self",
".",
"_results",
"or",
"not",
"self",
".",
"_jobs",
".",
"unfinished_tasks",
":",
"break",
"self",
".",
... | Wait for the first successful result to become available
:param timeout: Wait timeout, sec
:type timeout: float|int|None
:return: result, or None if all threads have failed
:rtype: * | [
"Wait",
"for",
"the",
"first",
"successful",
"result",
"to",
"become",
"available",
":",
"param",
"timeout",
":",
"Wait",
"timeout",
"sec",
":",
"type",
"timeout",
":",
"float|int|None",
":",
"return",
":",
"result",
"or",
"None",
"if",
"all",
"threads",
"... | train | https://github.com/kolypto/py-asynctools/blob/04ff42d13b54d200d8cc88b3639937b63278e57c/asynctools/threading/Parallel.py#L69-L81 |
kolypto/py-asynctools | asynctools/threading/Parallel.py | Parallel.join | def join(self):
""" Wait for all current tasks to be finished """
self._jobs.join()
try:
return self._results, self._errors
finally:
self._clear() | python | def join(self):
""" Wait for all current tasks to be finished """
self._jobs.join()
try:
return self._results, self._errors
finally:
self._clear() | [
"def",
"join",
"(",
"self",
")",
":",
"self",
".",
"_jobs",
".",
"join",
"(",
")",
"try",
":",
"return",
"self",
".",
"_results",
",",
"self",
".",
"_errors",
"finally",
":",
"self",
".",
"_clear",
"(",
")"
] | Wait for all current tasks to be finished | [
"Wait",
"for",
"all",
"current",
"tasks",
"to",
"be",
"finished"
] | train | https://github.com/kolypto/py-asynctools/blob/04ff42d13b54d200d8cc88b3639937b63278e57c/asynctools/threading/Parallel.py#L83-L89 |
glyph/secretly | secretly/_impl.py | call | def call(exe, *argv):
"""
Run a command, returning its output, or None if it fails.
"""
exes = which(exe)
if not exes:
returnValue(None)
stdout, stderr, value = yield getProcessOutputAndValue(
exes[0], argv, env=os.environ.copy()
)
if value:
returnValue(None)
... | python | def call(exe, *argv):
"""
Run a command, returning its output, or None if it fails.
"""
exes = which(exe)
if not exes:
returnValue(None)
stdout, stderr, value = yield getProcessOutputAndValue(
exes[0], argv, env=os.environ.copy()
)
if value:
returnValue(None)
... | [
"def",
"call",
"(",
"exe",
",",
"*",
"argv",
")",
":",
"exes",
"=",
"which",
"(",
"exe",
")",
"if",
"not",
"exes",
":",
"returnValue",
"(",
"None",
")",
"stdout",
",",
"stderr",
",",
"value",
"=",
"yield",
"getProcessOutputAndValue",
"(",
"exes",
"["... | Run a command, returning its output, or None if it fails. | [
"Run",
"a",
"command",
"returning",
"its",
"output",
"or",
"None",
"if",
"it",
"fails",
"."
] | train | https://github.com/glyph/secretly/blob/2f172750f37f91939008fa169e8e81ea41e06902/secretly/_impl.py#L189-L201 |
glyph/secretly | secretly/_impl.py | choosePinentry | def choosePinentry():
"""
Choose a C{pinentry} that can prompt you for a secret.
@return: An argv list suitable for passing to L{ProcessEndpoint}
@raises: L{RuntimeError} if no C{pinentry} is available.
@see:
U{https://www.gnupg.org/documentation/manuals/gnupg/Common-Problems.html}
""... | python | def choosePinentry():
"""
Choose a C{pinentry} that can prompt you for a secret.
@return: An argv list suitable for passing to L{ProcessEndpoint}
@raises: L{RuntimeError} if no C{pinentry} is available.
@see:
U{https://www.gnupg.org/documentation/manuals/gnupg/Common-Problems.html}
""... | [
"def",
"choosePinentry",
"(",
")",
":",
"pinentries",
"=",
"[",
"]",
"if",
"'PINENTRY'",
"in",
"os",
".",
"environ",
":",
"pinentries",
".",
"append",
"(",
"Pinentry",
"(",
"os",
".",
"environ",
"[",
"'PINENTRY'",
"]",
")",
")",
"else",
":",
"mgrd",
... | Choose a C{pinentry} that can prompt you for a secret.
@return: An argv list suitable for passing to L{ProcessEndpoint}
@raises: L{RuntimeError} if no C{pinentry} is available.
@see:
U{https://www.gnupg.org/documentation/manuals/gnupg/Common-Problems.html} | [
"Choose",
"a",
"C",
"{",
"pinentry",
"}",
"that",
"can",
"prompt",
"you",
"for",
"a",
"secret",
"."
] | train | https://github.com/glyph/secretly/blob/2f172750f37f91939008fa169e8e81ea41e06902/secretly/_impl.py#L204-L245 |
glyph/secretly | secretly/_impl.py | secretly | def secretly(reactor, action, system=None, username=None,
prompt="Password:"):
"""
Call the given C{action} with a secret value.
@return: a L{Deferred} that fires with C{action}'s result, or
L{NoSecretError} if no secret can be retrieved.
"""
if system is None:
system =... | python | def secretly(reactor, action, system=None, username=None,
prompt="Password:"):
"""
Call the given C{action} with a secret value.
@return: a L{Deferred} that fires with C{action}'s result, or
L{NoSecretError} if no secret can be retrieved.
"""
if system is None:
system =... | [
"def",
"secretly",
"(",
"reactor",
",",
"action",
",",
"system",
"=",
"None",
",",
"username",
"=",
"None",
",",
"prompt",
"=",
"\"Password:\"",
")",
":",
"if",
"system",
"is",
"None",
":",
"system",
"=",
"action",
".",
"__module__",
"if",
"system",
"=... | Call the given C{action} with a secret value.
@return: a L{Deferred} that fires with C{action}'s result, or
L{NoSecretError} if no secret can be retrieved. | [
"Call",
"the",
"given",
"C",
"{",
"action",
"}",
"with",
"a",
"secret",
"value",
"."
] | train | https://github.com/glyph/secretly/blob/2f172750f37f91939008fa169e8e81ea41e06902/secretly/_impl.py#L249-L275 |
glyph/secretly | secretly/_impl.py | SimpleAssuan.issueCommand | def issueCommand(self, command, *args):
"""
Issue the given Assuan command and return a Deferred that will fire
with the response.
"""
result = Deferred()
self._dq.append(result)
self.sendLine(b" ".join([command] + list(args)))
return result | python | def issueCommand(self, command, *args):
"""
Issue the given Assuan command and return a Deferred that will fire
with the response.
"""
result = Deferred()
self._dq.append(result)
self.sendLine(b" ".join([command] + list(args)))
return result | [
"def",
"issueCommand",
"(",
"self",
",",
"command",
",",
"*",
"args",
")",
":",
"result",
"=",
"Deferred",
"(",
")",
"self",
".",
"_dq",
".",
"append",
"(",
"result",
")",
"self",
".",
"sendLine",
"(",
"b\" \"",
".",
"join",
"(",
"[",
"command",
"]... | Issue the given Assuan command and return a Deferred that will fire
with the response. | [
"Issue",
"the",
"given",
"Assuan",
"command",
"and",
"return",
"a",
"Deferred",
"that",
"will",
"fire",
"with",
"the",
"response",
"."
] | train | https://github.com/glyph/secretly/blob/2f172750f37f91939008fa169e8e81ea41e06902/secretly/_impl.py#L59-L67 |
glyph/secretly | secretly/_impl.py | SimpleAssuan._currentResponse | def _currentResponse(self, debugInfo):
"""
Pull the current response off the queue.
"""
bd = b''.join(self._bufferedData)
self._bufferedData = []
return AssuanResponse(bd, debugInfo) | python | def _currentResponse(self, debugInfo):
"""
Pull the current response off the queue.
"""
bd = b''.join(self._bufferedData)
self._bufferedData = []
return AssuanResponse(bd, debugInfo) | [
"def",
"_currentResponse",
"(",
"self",
",",
"debugInfo",
")",
":",
"bd",
"=",
"b''",
".",
"join",
"(",
"self",
".",
"_bufferedData",
")",
"self",
".",
"_bufferedData",
"=",
"[",
"]",
"return",
"AssuanResponse",
"(",
"bd",
",",
"debugInfo",
")"
] | Pull the current response off the queue. | [
"Pull",
"the",
"current",
"response",
"off",
"the",
"queue",
"."
] | train | https://github.com/glyph/secretly/blob/2f172750f37f91939008fa169e8e81ea41e06902/secretly/_impl.py#L70-L76 |
glyph/secretly | secretly/_impl.py | SimpleAssuan.lineReceived | def lineReceived(self, line):
"""
A line was received.
"""
if line.startswith(b"#"): # ignore it
return
if line.startswith(b"OK"):
# if no command issued, then just 'ready'
if self._ready:
self._dq.pop(0).callback(self._currentR... | python | def lineReceived(self, line):
"""
A line was received.
"""
if line.startswith(b"#"): # ignore it
return
if line.startswith(b"OK"):
# if no command issued, then just 'ready'
if self._ready:
self._dq.pop(0).callback(self._currentR... | [
"def",
"lineReceived",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"b\"#\"",
")",
":",
"# ignore it",
"return",
"if",
"line",
".",
"startswith",
"(",
"b\"OK\"",
")",
":",
"# if no command issued, then just 'ready'",
"if",
"self",
... | A line was received. | [
"A",
"line",
"was",
"received",
"."
] | train | https://github.com/glyph/secretly/blob/2f172750f37f91939008fa169e8e81ea41e06902/secretly/_impl.py#L79-L96 |
jaraco/jaraco.stream | jaraco/stream/gzip.py | read_chunks | def read_chunks(stream, block_size=2**10):
"""
Given a byte stream with reader, yield chunks of block_size
until the stream is consusmed.
"""
while True:
chunk = stream.read(block_size)
if not chunk:
break
yield chunk | python | def read_chunks(stream, block_size=2**10):
"""
Given a byte stream with reader, yield chunks of block_size
until the stream is consusmed.
"""
while True:
chunk = stream.read(block_size)
if not chunk:
break
yield chunk | [
"def",
"read_chunks",
"(",
"stream",
",",
"block_size",
"=",
"2",
"**",
"10",
")",
":",
"while",
"True",
":",
"chunk",
"=",
"stream",
".",
"read",
"(",
"block_size",
")",
"if",
"not",
"chunk",
":",
"break",
"yield",
"chunk"
] | Given a byte stream with reader, yield chunks of block_size
until the stream is consusmed. | [
"Given",
"a",
"byte",
"stream",
"with",
"reader",
"yield",
"chunks",
"of",
"block_size",
"until",
"the",
"stream",
"is",
"consusmed",
"."
] | train | https://github.com/jaraco/jaraco.stream/blob/960d6950b083e64c97d93e15443d486b52046a44/jaraco/stream/gzip.py#L16-L25 |
jaraco/jaraco.stream | jaraco/stream/gzip.py | _load_stream_py3 | def _load_stream_py3(dc, chunks):
"""
Given a decompression stream and chunks, yield chunks of
decompressed data until the compression window ends.
"""
while not dc.eof:
res = dc.decompress(dc.unconsumed_tail + next(chunks))
yield res | python | def _load_stream_py3(dc, chunks):
"""
Given a decompression stream and chunks, yield chunks of
decompressed data until the compression window ends.
"""
while not dc.eof:
res = dc.decompress(dc.unconsumed_tail + next(chunks))
yield res | [
"def",
"_load_stream_py3",
"(",
"dc",
",",
"chunks",
")",
":",
"while",
"not",
"dc",
".",
"eof",
":",
"res",
"=",
"dc",
".",
"decompress",
"(",
"dc",
".",
"unconsumed_tail",
"+",
"next",
"(",
"chunks",
")",
")",
"yield",
"res"
] | Given a decompression stream and chunks, yield chunks of
decompressed data until the compression window ends. | [
"Given",
"a",
"decompression",
"stream",
"and",
"chunks",
"yield",
"chunks",
"of",
"decompressed",
"data",
"until",
"the",
"compression",
"window",
"ends",
"."
] | train | https://github.com/jaraco/jaraco.stream/blob/960d6950b083e64c97d93e15443d486b52046a44/jaraco/stream/gzip.py#L28-L35 |
jaraco/jaraco.stream | jaraco/stream/gzip.py | load_streams | def load_streams(chunks):
"""
Given a gzipped stream of data, yield streams of decompressed data.
"""
chunks = peekable(chunks)
while chunks:
if six.PY3:
dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16)
else:
dc = zlib.decompressobj(zlib.MAX_WBITS | 16)
... | python | def load_streams(chunks):
"""
Given a gzipped stream of data, yield streams of decompressed data.
"""
chunks = peekable(chunks)
while chunks:
if six.PY3:
dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16)
else:
dc = zlib.decompressobj(zlib.MAX_WBITS | 16)
... | [
"def",
"load_streams",
"(",
"chunks",
")",
":",
"chunks",
"=",
"peekable",
"(",
"chunks",
")",
"while",
"chunks",
":",
"if",
"six",
".",
"PY3",
":",
"dc",
"=",
"zlib",
".",
"decompressobj",
"(",
"wbits",
"=",
"zlib",
".",
"MAX_WBITS",
"|",
"16",
")",... | Given a gzipped stream of data, yield streams of decompressed data. | [
"Given",
"a",
"gzipped",
"stream",
"of",
"data",
"yield",
"streams",
"of",
"decompressed",
"data",
"."
] | train | https://github.com/jaraco/jaraco.stream/blob/960d6950b083e64c97d93e15443d486b52046a44/jaraco/stream/gzip.py#L50-L62 |
jaraco/jaraco.stream | jaraco/stream/gzip.py | lines_from_stream | def lines_from_stream(chunks):
"""
Given data in chunks, yield lines of text
"""
buf = buffer.DecodingLineBuffer()
for chunk in chunks:
buf.feed(chunk)
# when Python 3, yield from buf
for _ in buf:
yield _ | python | def lines_from_stream(chunks):
"""
Given data in chunks, yield lines of text
"""
buf = buffer.DecodingLineBuffer()
for chunk in chunks:
buf.feed(chunk)
# when Python 3, yield from buf
for _ in buf:
yield _ | [
"def",
"lines_from_stream",
"(",
"chunks",
")",
":",
"buf",
"=",
"buffer",
".",
"DecodingLineBuffer",
"(",
")",
"for",
"chunk",
"in",
"chunks",
":",
"buf",
".",
"feed",
"(",
"chunk",
")",
"# when Python 3, yield from buf",
"for",
"_",
"in",
"buf",
":",
"yi... | Given data in chunks, yield lines of text | [
"Given",
"data",
"in",
"chunks",
"yield",
"lines",
"of",
"text"
] | train | https://github.com/jaraco/jaraco.stream/blob/960d6950b083e64c97d93e15443d486b52046a44/jaraco/stream/gzip.py#L65-L74 |
TestInABox/stackInABox | stackinabox/util/requests_mock/core.py | session_registration | def session_registration(uri, session):
"""Requests-mock registration with a specific Session.
:param uri: base URI to match against
:param session: Python requests' Session object
:returns: n/a
"""
# log the URI that is used to access the Stack-In-A-Box services
logger.debug('Registering ... | python | def session_registration(uri, session):
"""Requests-mock registration with a specific Session.
:param uri: base URI to match against
:param session: Python requests' Session object
:returns: n/a
"""
# log the URI that is used to access the Stack-In-A-Box services
logger.debug('Registering ... | [
"def",
"session_registration",
"(",
"uri",
",",
"session",
")",
":",
"# log the URI that is used to access the Stack-In-A-Box services",
"logger",
".",
"debug",
"(",
"'Registering Stack-In-A-Box at {0} under Python Requests-Mock'",
".",
"format",
"(",
"uri",
")",
")",
"logger... | Requests-mock registration with a specific Session.
:param uri: base URI to match against
:param session: Python requests' Session object
:returns: n/a | [
"Requests",
"-",
"mock",
"registration",
"with",
"a",
"specific",
"Session",
"."
] | train | https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L161-L184 |
TestInABox/stackInABox | stackinabox/util/requests_mock/core.py | requests_request | def requests_request(method, url, **kwargs):
"""Requests-mock requests.request wrapper."""
session = local_sessions.session
response = session.request(method=method, url=url, **kwargs)
session.close()
return response | python | def requests_request(method, url, **kwargs):
"""Requests-mock requests.request wrapper."""
session = local_sessions.session
response = session.request(method=method, url=url, **kwargs)
session.close()
return response | [
"def",
"requests_request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"local_sessions",
".",
"session",
"response",
"=",
"session",
".",
"request",
"(",
"method",
"=",
"method",
",",
"url",
"=",
"url",
",",
"*",
"*",
... | Requests-mock requests.request wrapper. | [
"Requests",
"-",
"mock",
"requests",
".",
"request",
"wrapper",
"."
] | train | https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L200-L205 |
TestInABox/stackInABox | stackinabox/util/requests_mock/core.py | requests_post | def requests_post(url, data=None, json=None, **kwargs):
"""Requests-mock requests.post wrapper."""
return requests_request('post', url, data=data, json=json, **kwargs) | python | def requests_post(url, data=None, json=None, **kwargs):
"""Requests-mock requests.post wrapper."""
return requests_request('post', url, data=data, json=json, **kwargs) | [
"def",
"requests_post",
"(",
"url",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"requests_request",
"(",
"'post'",
",",
"url",
",",
"data",
"=",
"data",
",",
"json",
"=",
"json",
",",
"*",
"*",
... | Requests-mock requests.post wrapper. | [
"Requests",
"-",
"mock",
"requests",
".",
"post",
"wrapper",
"."
] | train | https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L226-L228 |
TestInABox/stackInABox | stackinabox/util/requests_mock/core.py | RequestMockCallable.get_reason_for_status | def get_reason_for_status(status_code):
"""Lookup the HTTP reason text for a given status code.
:param status_code: int - HTTP status code
:returns: string - HTTP reason text
"""
if status_code in requests.status_codes.codes:
return requests.status_codes._codes[sta... | python | def get_reason_for_status(status_code):
"""Lookup the HTTP reason text for a given status code.
:param status_code: int - HTTP status code
:returns: string - HTTP reason text
"""
if status_code in requests.status_codes.codes:
return requests.status_codes._codes[sta... | [
"def",
"get_reason_for_status",
"(",
"status_code",
")",
":",
"if",
"status_code",
"in",
"requests",
".",
"status_codes",
".",
"codes",
":",
"return",
"requests",
".",
"status_codes",
".",
"_codes",
"[",
"status_code",
"]",
"[",
"0",
"]",
".",
"replace",
"("... | Lookup the HTTP reason text for a given status code.
:param status_code: int - HTTP status code
:returns: string - HTTP reason text | [
"Lookup",
"the",
"HTTP",
"reason",
"text",
"for",
"a",
"given",
"status",
"code",
"."
] | train | https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L63-L75 |
TestInABox/stackInABox | stackinabox/util/requests_mock/core.py | RequestMockCallable.split_status | def split_status(status):
"""Split a HTTP Status and Reason code string into a tuple.
:param status string containing the status and reason text or
the integer of the status code
:returns: tuple - (int, string) containing the integer status code
... | python | def split_status(status):
"""Split a HTTP Status and Reason code string into a tuple.
:param status string containing the status and reason text or
the integer of the status code
:returns: tuple - (int, string) containing the integer status code
... | [
"def",
"split_status",
"(",
"status",
")",
":",
"# If the status is an integer, then lookup the reason text",
"if",
"isinstance",
"(",
"status",
",",
"int",
")",
":",
"return",
"(",
"status",
",",
"RequestMockCallable",
".",
"get_reason_for_status",
"(",
"status",
")"... | Split a HTTP Status and Reason code string into a tuple.
:param status string containing the status and reason text or
the integer of the status code
:returns: tuple - (int, string) containing the integer status code
and reason text string | [
"Split",
"a",
"HTTP",
"Status",
"and",
"Reason",
"code",
"string",
"into",
"a",
"tuple",
"."
] | train | https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L78-L101 |
TestInABox/stackInABox | stackinabox/util/requests_mock/core.py | RequestMockCallable.handle | def handle(self, request, uri):
"""Request handler interface.
:param request: Python requests Request object
:param uri: URI of the request
"""
# Convert the call over to Stack-In-A-Box
method = request.method
headers = CaseInsensitiveDict()
request_head... | python | def handle(self, request, uri):
"""Request handler interface.
:param request: Python requests Request object
:param uri: URI of the request
"""
# Convert the call over to Stack-In-A-Box
method = request.method
headers = CaseInsensitiveDict()
request_head... | [
"def",
"handle",
"(",
"self",
",",
"request",
",",
"uri",
")",
":",
"# Convert the call over to Stack-In-A-Box",
"method",
"=",
"request",
".",
"method",
"headers",
"=",
"CaseInsensitiveDict",
"(",
")",
"request_headers",
"=",
"CaseInsensitiveDict",
"(",
")",
"req... | Request handler interface.
:param request: Python requests Request object
:param uri: URI of the request | [
"Request",
"handler",
"interface",
"."
] | train | https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/util/requests_mock/core.py#L103-L158 |
changecoin/changetip-python | changetip/bots/base.py | BaseBot.send_tip | def send_tip(self, sender, receiver, message, context_uid, meta):
""" Send a request to the ChangeTip API, to be delivered immediately. """
assert self.channel is not None, "channel must be defined"
# Add extra data to meta
meta["mention_bot"] = self.mention_bot()
data = json.d... | python | def send_tip(self, sender, receiver, message, context_uid, meta):
""" Send a request to the ChangeTip API, to be delivered immediately. """
assert self.channel is not None, "channel must be defined"
# Add extra data to meta
meta["mention_bot"] = self.mention_bot()
data = json.d... | [
"def",
"send_tip",
"(",
"self",
",",
"sender",
",",
"receiver",
",",
"message",
",",
"context_uid",
",",
"meta",
")",
":",
"assert",
"self",
".",
"channel",
"is",
"not",
"None",
",",
"\"channel must be defined\"",
"# Add extra data to meta",
"meta",
"[",
"\"me... | Send a request to the ChangeTip API, to be delivered immediately. | [
"Send",
"a",
"request",
"to",
"the",
"ChangeTip",
"API",
"to",
"be",
"delivered",
"immediately",
"."
] | train | https://github.com/changecoin/changetip-python/blob/daa6e2f41712eb58d16c537af34f9f0a1b74a14e/changetip/bots/base.py#L49-L70 |
changecoin/changetip-python | changetip/bots/base.py | BaseBot.get_mentions | def get_mentions(self, message):
""" Remove duplicates in a case-insensitive way while preserving the original order
Return all mentions in lower case *without* their prefixes. (So return ['clyde'], not ['@clyde'])
>>> BaseBot().get_mentions("This is a @user")
['user']
>>> Ba... | python | def get_mentions(self, message):
""" Remove duplicates in a case-insensitive way while preserving the original order
Return all mentions in lower case *without* their prefixes. (So return ['clyde'], not ['@clyde'])
>>> BaseBot().get_mentions("This is a @user")
['user']
>>> Ba... | [
"def",
"get_mentions",
"(",
"self",
",",
"message",
")",
":",
"mentions",
"=",
"re",
".",
"findall",
"(",
"re",
".",
"escape",
"(",
"self",
".",
"prefix",
")",
"+",
"'([\\w-]+)'",
",",
"message",
")",
"mentions_set",
"=",
"set",
"(",
"[",
"m",
".",
... | Remove duplicates in a case-insensitive way while preserving the original order
Return all mentions in lower case *without* their prefixes. (So return ['clyde'], not ['@clyde'])
>>> BaseBot().get_mentions("This is a @user")
['user']
>>> BaseBot().get_mentions("This is empty")
... | [
"Remove",
"duplicates",
"in",
"a",
"case",
"-",
"insensitive",
"way",
"while",
"preserving",
"the",
"original",
"order",
"Return",
"all",
"mentions",
"in",
"lower",
"case",
"*",
"without",
"*",
"their",
"prefixes",
".",
"(",
"So",
"return",
"[",
"clyde",
"... | train | https://github.com/changecoin/changetip-python/blob/daa6e2f41712eb58d16c537af34f9f0a1b74a14e/changetip/bots/base.py#L105-L129 |
bear/ninka | ninka/micropub.py | discoverEndpoint | def discoverEndpoint(domain, endpoint, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the given endpoint for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain:... | python | def discoverEndpoint(domain, endpoint, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the given endpoint for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain:... | [
"def",
"discoverEndpoint",
"(",
"domain",
",",
"endpoint",
",",
"content",
"=",
"None",
",",
"look_in",
"=",
"{",
"'name'",
":",
"'link'",
"}",
",",
"test_urls",
"=",
"True",
",",
"validateCerts",
"=",
"True",
")",
":",
"if",
"test_urls",
":",
"ronkyuu",... | Find the given endpoint for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the URL of the domain to handle
:param endpoint: list of endpoints to look for
:param content: the content to be s... | [
"Find",
"the",
"given",
"endpoint",
"for",
"the",
"given",
"domain",
".",
"Only",
"scan",
"html",
"element",
"matching",
"all",
"criteria",
"in",
"look_in",
"."
] | train | https://github.com/bear/ninka/blob/4d13a48d2b8857496f7fc470b0c379486351c89b/ninka/micropub.py#L31-L89 |
bear/ninka | ninka/micropub.py | discoverMicropubEndpoints | def discoverMicropubEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the micropub for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the UR... | python | def discoverMicropubEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the micropub for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the UR... | [
"def",
"discoverMicropubEndpoints",
"(",
"domain",
",",
"content",
"=",
"None",
",",
"look_in",
"=",
"{",
"'name'",
":",
"'link'",
"}",
",",
"test_urls",
"=",
"True",
",",
"validateCerts",
"=",
"True",
")",
":",
"return",
"discoverEndpoint",
"(",
"domain",
... | Find the micropub for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the URL of the domain to handle
:param content: the content to be scanned for the endpoint
:param look_in: dictionary wi... | [
"Find",
"the",
"micropub",
"for",
"the",
"given",
"domain",
".",
"Only",
"scan",
"html",
"element",
"matching",
"all",
"criteria",
"in",
"look_in",
"."
] | train | https://github.com/bear/ninka/blob/4d13a48d2b8857496f7fc470b0c379486351c89b/ninka/micropub.py#L91-L104 |
bear/ninka | ninka/micropub.py | discoverTokenEndpoints | def discoverTokenEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the token for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the URL of t... | python | def discoverTokenEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the token for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the URL of t... | [
"def",
"discoverTokenEndpoints",
"(",
"domain",
",",
"content",
"=",
"None",
",",
"look_in",
"=",
"{",
"'name'",
":",
"'link'",
"}",
",",
"test_urls",
"=",
"True",
",",
"validateCerts",
"=",
"True",
")",
":",
"return",
"discoverEndpoint",
"(",
"domain",
",... | Find the token for the given domain.
Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
:param domain: the URL of the domain to handle
:param content: the content to be scanned for the endpoint
:param look_in: dictionary with ... | [
"Find",
"the",
"token",
"for",
"the",
"given",
"domain",
".",
"Only",
"scan",
"html",
"element",
"matching",
"all",
"criteria",
"in",
"look_in",
"."
] | train | https://github.com/bear/ninka/blob/4d13a48d2b8857496f7fc470b0c379486351c89b/ninka/micropub.py#L106-L119 |
siemens/django-dingos | dingos/core/http_helpers.py | get_query_string | def get_query_string(request, new_params=None, remove=None):
"""
Given the request, return the query string.
Parameters can be added or removed as necessary.
Code snippet taken from Django admin app (views/main.py)
(c) Copyright Django Software Foundation and individual contributors.
Redist... | python | def get_query_string(request, new_params=None, remove=None):
"""
Given the request, return the query string.
Parameters can be added or removed as necessary.
Code snippet taken from Django admin app (views/main.py)
(c) Copyright Django Software Foundation and individual contributors.
Redist... | [
"def",
"get_query_string",
"(",
"request",
",",
"new_params",
"=",
"None",
",",
"remove",
"=",
"None",
")",
":",
"if",
"new_params",
"is",
"None",
":",
"new_params",
"=",
"{",
"}",
"if",
"remove",
"is",
"None",
":",
"remove",
"=",
"[",
"]",
"p",
"=",... | Given the request, return the query string.
Parameters can be added or removed as necessary.
Code snippet taken from Django admin app (views/main.py)
(c) Copyright Django Software Foundation and individual contributors.
Redistribution and use in source and binary forms, with or without modification... | [
"Given",
"the",
"request",
"return",
"the",
"query",
"string",
"."
] | train | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/http_helpers.py#L22-L71 |
koriakin/binflakes | binflakes/sexpr/nodes.py | _unwrap | def _unwrap(value, location=None):
"""A helper function for Node subclass constructors -- if ``value``
is a Node instance, extracts raw Python value and location from it,
and returns them as a tuple. Otherwise, ensures that ``value`` is
of a type representable by S-expressions and returns it along with... | python | def _unwrap(value, location=None):
"""A helper function for Node subclass constructors -- if ``value``
is a Node instance, extracts raw Python value and location from it,
and returns them as a tuple. Otherwise, ensures that ``value`` is
of a type representable by S-expressions and returns it along with... | [
"def",
"_unwrap",
"(",
"value",
",",
"location",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Node",
")",
"and",
"location",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"'explicit location should only be given for bare values'",
")",
... | A helper function for Node subclass constructors -- if ``value``
is a Node instance, extracts raw Python value and location from it,
and returns them as a tuple. Otherwise, ensures that ``value`` is
of a type representable by S-expressions and returns it along with
explicitly-passed location, if any. | [
"A",
"helper",
"function",
"for",
"Node",
"subclass",
"constructors",
"--",
"if",
"value",
"is",
"a",
"Node",
"instance",
"extracts",
"raw",
"Python",
"value",
"and",
"location",
"from",
"it",
"and",
"returns",
"them",
"as",
"a",
"tuple",
".",
"Otherwise",
... | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/sexpr/nodes.py#L19-L43 |
koriakin/binflakes | binflakes/sexpr/nodes.py | form_node | def form_node(cls):
"""A class decorator to finalize fully derived FormNode subclasses."""
assert issubclass(cls, FormNode)
res = attrs(init=False, slots=True)(cls)
res._args = []
res._required_args = 0
res._rest_arg = None
state = _FormArgMode.REQUIRED
for field in fields(res):
... | python | def form_node(cls):
"""A class decorator to finalize fully derived FormNode subclasses."""
assert issubclass(cls, FormNode)
res = attrs(init=False, slots=True)(cls)
res._args = []
res._required_args = 0
res._rest_arg = None
state = _FormArgMode.REQUIRED
for field in fields(res):
... | [
"def",
"form_node",
"(",
"cls",
")",
":",
"assert",
"issubclass",
"(",
"cls",
",",
"FormNode",
")",
"res",
"=",
"attrs",
"(",
"init",
"=",
"False",
",",
"slots",
"=",
"True",
")",
"(",
"cls",
")",
"res",
".",
"_args",
"=",
"[",
"]",
"res",
".",
... | A class decorator to finalize fully derived FormNode subclasses. | [
"A",
"class",
"decorator",
"to",
"finalize",
"fully",
"derived",
"FormNode",
"subclasses",
"."
] | train | https://github.com/koriakin/binflakes/blob/f059cecadf1c605802a713c62375b5bd5606d53f/binflakes/sexpr/nodes.py#L222-L247 |
host-anshu/simpleInterceptor | interceptor.py | intercept | def intercept(aspects):
"""Decorate class to intercept its matching methods and apply advices on them.
Advices are the cross-cutting concerns that need to be separated out from the business logic.
This decorator applies such advices to the decorated class.
:arg aspects: mapping of joint-points to dict... | python | def intercept(aspects):
"""Decorate class to intercept its matching methods and apply advices on them.
Advices are the cross-cutting concerns that need to be separated out from the business logic.
This decorator applies such advices to the decorated class.
:arg aspects: mapping of joint-points to dict... | [
"def",
"intercept",
"(",
"aspects",
")",
":",
"if",
"not",
"isinstance",
"(",
"aspects",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"Aspects must be a dictionary of joint-points and advices\"",
")",
"def",
"get_matching_advices",
"(",
"name",
")",
":",
"\... | Decorate class to intercept its matching methods and apply advices on them.
Advices are the cross-cutting concerns that need to be separated out from the business logic.
This decorator applies such advices to the decorated class.
:arg aspects: mapping of joint-points to dictionary of advices. joint-points... | [
"Decorate",
"class",
"to",
"intercept",
"its",
"matching",
"methods",
"and",
"apply",
"advices",
"on",
"them",
"."
] | train | https://github.com/host-anshu/simpleInterceptor/blob/71238fed57c62b5f77ce32d0c9b98acad73ab6a8/interceptor.py#L9-L95 |
mikeboers/sitetools | sitetools/environ.py | freeze | def freeze(environ, names, label=None):
"""Flag the given names to reset to their current value in the next Python.
:param dict environ: The environment that will be passed to the next Python.
:param names: A list of variable names that should be reset to their current
value (as in ``environ``)... | python | def freeze(environ, names, label=None):
"""Flag the given names to reset to their current value in the next Python.
:param dict environ: The environment that will be passed to the next Python.
:param names: A list of variable names that should be reset to their current
value (as in ``environ``)... | [
"def",
"freeze",
"(",
"environ",
",",
"names",
",",
"label",
"=",
"None",
")",
":",
"diff",
"=",
"_get_diff",
"(",
"environ",
",",
"label",
")",
"for",
"name",
"in",
"names",
":",
"diff",
"[",
"name",
"]",
"=",
"environ",
".",
"get",
"(",
"name",
... | Flag the given names to reset to their current value in the next Python.
:param dict environ: The environment that will be passed to the next Python.
:param names: A list of variable names that should be reset to their current
value (as in ``environ``) when the next sub-Python starts.
:param st... | [
"Flag",
"the",
"given",
"names",
"to",
"reset",
"to",
"their",
"current",
"value",
"in",
"the",
"next",
"Python",
".",
":",
"param",
"dict",
"environ",
":",
"The",
"environment",
"that",
"will",
"be",
"passed",
"to",
"the",
"next",
"Python",
".",
":",
... | train | https://github.com/mikeboers/sitetools/blob/1ec4eea6902b4a276f868a711b783dd965c123b7/sitetools/environ.py#L62-L97 |
mikeboers/sitetools | sitetools/environ.py | _get_diff | def _get_diff(environ, label, pop=False):
"""Get previously frozen key-value pairs.
:param str label: The name for the frozen environment.
:param bool pop: Destroy the freeze after use; only allow application once.
:returns: ``dict`` of frozen values.
"""
if pop:
blob = environ.pop(_va... | python | def _get_diff(environ, label, pop=False):
"""Get previously frozen key-value pairs.
:param str label: The name for the frozen environment.
:param bool pop: Destroy the freeze after use; only allow application once.
:returns: ``dict`` of frozen values.
"""
if pop:
blob = environ.pop(_va... | [
"def",
"_get_diff",
"(",
"environ",
",",
"label",
",",
"pop",
"=",
"False",
")",
":",
"if",
"pop",
":",
"blob",
"=",
"environ",
".",
"pop",
"(",
"_variable_name",
"(",
"label",
")",
",",
"None",
")",
"else",
":",
"blob",
"=",
"environ",
".",
"get",... | Get previously frozen key-value pairs.
:param str label: The name for the frozen environment.
:param bool pop: Destroy the freeze after use; only allow application once.
:returns: ``dict`` of frozen values. | [
"Get",
"previously",
"frozen",
"key",
"-",
"value",
"pairs",
"."
] | train | https://github.com/mikeboers/sitetools/blob/1ec4eea6902b4a276f868a711b783dd965c123b7/sitetools/environ.py#L100-L113 |
mikeboers/sitetools | sitetools/environ.py | _apply_diff | def _apply_diff(environ, diff):
"""Apply a frozen environment.
:param dict diff: key-value pairs to apply to the environment.
:returns: A dict of the key-value pairs that are being changed.
"""
original = {}
if diff:
for k, v in diff.iteritems():
if v is None:
... | python | def _apply_diff(environ, diff):
"""Apply a frozen environment.
:param dict diff: key-value pairs to apply to the environment.
:returns: A dict of the key-value pairs that are being changed.
"""
original = {}
if diff:
for k, v in diff.iteritems():
if v is None:
... | [
"def",
"_apply_diff",
"(",
"environ",
",",
"diff",
")",
":",
"original",
"=",
"{",
"}",
"if",
"diff",
":",
"for",
"k",
",",
"v",
"in",
"diff",
".",
"iteritems",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"log",
".",
"log",
"(",
"5",
",",
"'... | Apply a frozen environment.
:param dict diff: key-value pairs to apply to the environment.
:returns: A dict of the key-value pairs that are being changed. | [
"Apply",
"a",
"frozen",
"environment",
"."
] | train | https://github.com/mikeboers/sitetools/blob/1ec4eea6902b4a276f868a711b783dd965c123b7/sitetools/environ.py#L116-L147 |
mikeboers/sitetools | sitetools/environ.py | unfreeze | def unfreeze(label, pop=False, environ=None):
"""Reset the environment to its state before it was frozen by :func:`freeze`.
:param str label: The name for the frozen environment.
:param bool pop: Destroy the freeze after use; only allow unfreeze once.
:param dict environ: The environment to work on; de... | python | def unfreeze(label, pop=False, environ=None):
"""Reset the environment to its state before it was frozen by :func:`freeze`.
:param str label: The name for the frozen environment.
:param bool pop: Destroy the freeze after use; only allow unfreeze once.
:param dict environ: The environment to work on; de... | [
"def",
"unfreeze",
"(",
"label",
",",
"pop",
"=",
"False",
",",
"environ",
"=",
"None",
")",
":",
"environ",
"=",
"os",
".",
"environ",
"if",
"environ",
"is",
"None",
"else",
"environ",
"diff",
"=",
"_get_diff",
"(",
"environ",
",",
"label",
",",
"po... | Reset the environment to its state before it was frozen by :func:`freeze`.
:param str label: The name for the frozen environment.
:param bool pop: Destroy the freeze after use; only allow unfreeze once.
:param dict environ: The environment to work on; defaults to ``os.environ``.
:returns: A context man... | [
"Reset",
"the",
"environment",
"to",
"its",
"state",
"before",
"it",
"was",
"frozen",
"by",
":",
"func",
":",
"freeze",
"."
] | train | https://github.com/mikeboers/sitetools/blob/1ec4eea6902b4a276f868a711b783dd965c123b7/sitetools/environ.py#L150-L172 |
gnullByte/dotcolors | dotcolors/core.py | get_current | def get_current():
"""return current Xresources color theme"""
global current
if exists( SETTINGSFILE ):
f = open( SETTINGSFILE ).read()
current = re.findall('config[^\s]+.+', f)[1].split('/')[-1]
return current
else:
return "** Not Set **" | python | def get_current():
"""return current Xresources color theme"""
global current
if exists( SETTINGSFILE ):
f = open( SETTINGSFILE ).read()
current = re.findall('config[^\s]+.+', f)[1].split('/')[-1]
return current
else:
return "** Not Set **" | [
"def",
"get_current",
"(",
")",
":",
"global",
"current",
"if",
"exists",
"(",
"SETTINGSFILE",
")",
":",
"f",
"=",
"open",
"(",
"SETTINGSFILE",
")",
".",
"read",
"(",
")",
"current",
"=",
"re",
".",
"findall",
"(",
"'config[^\\s]+.+'",
",",
"f",
")",
... | return current Xresources color theme | [
"return",
"current",
"Xresources",
"color",
"theme"
] | train | https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/core.py#L33-L41 |
gnullByte/dotcolors | dotcolors/core.py | get_colors | def get_colors():
"""return list of available Xresources color themes"""
if exists( THEMEDIR ):
contents = os.listdir( THEMEDIR )
themes = [theme for theme in contents if '.' not in theme]
if len(themes) > 0:
themes.sort()
return themes
else:
... | python | def get_colors():
"""return list of available Xresources color themes"""
if exists( THEMEDIR ):
contents = os.listdir( THEMEDIR )
themes = [theme for theme in contents if '.' not in theme]
if len(themes) > 0:
themes.sort()
return themes
else:
... | [
"def",
"get_colors",
"(",
")",
":",
"if",
"exists",
"(",
"THEMEDIR",
")",
":",
"contents",
"=",
"os",
".",
"listdir",
"(",
"THEMEDIR",
")",
"themes",
"=",
"[",
"theme",
"for",
"theme",
"in",
"contents",
"if",
"'.'",
"not",
"in",
"theme",
"]",
"if",
... | return list of available Xresources color themes | [
"return",
"list",
"of",
"available",
"Xresources",
"color",
"themes"
] | train | https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/core.py#L43-L61 |
gnullByte/dotcolors | dotcolors/core.py | menu_pages | def menu_pages(colors, page=1, print_keys=True, per_page=15):
"""return menu items by page from list: colors"""
c = os.system('clear')
length = len(colors)
last_page = length / per_page
if (last_page * per_page) < length:
last_page += 1
page_display = "page (%d/%d)" % (page, last_page)... | python | def menu_pages(colors, page=1, print_keys=True, per_page=15):
"""return menu items by page from list: colors"""
c = os.system('clear')
length = len(colors)
last_page = length / per_page
if (last_page * per_page) < length:
last_page += 1
page_display = "page (%d/%d)" % (page, last_page)... | [
"def",
"menu_pages",
"(",
"colors",
",",
"page",
"=",
"1",
",",
"print_keys",
"=",
"True",
",",
"per_page",
"=",
"15",
")",
":",
"c",
"=",
"os",
".",
"system",
"(",
"'clear'",
")",
"length",
"=",
"len",
"(",
"colors",
")",
"last_page",
"=",
"length... | return menu items by page from list: colors | [
"return",
"menu",
"items",
"by",
"page",
"from",
"list",
":",
"colors"
] | train | https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/core.py#L64-L96 |
gnullByte/dotcolors | dotcolors/core.py | getch_selection | def getch_selection(colors, per_page=15):
"""prompt for selection, validate input, return selection"""
global transparency, prefix, current
get_transparency()
page = 1
length = len(colors)
last_page = length / per_page
if (last_page * per_page) < length:
last_page += 1
get... | python | def getch_selection(colors, per_page=15):
"""prompt for selection, validate input, return selection"""
global transparency, prefix, current
get_transparency()
page = 1
length = len(colors)
last_page = length / per_page
if (last_page * per_page) < length:
last_page += 1
get... | [
"def",
"getch_selection",
"(",
"colors",
",",
"per_page",
"=",
"15",
")",
":",
"global",
"transparency",
",",
"prefix",
",",
"current",
"get_transparency",
"(",
")",
"page",
"=",
"1",
"length",
"=",
"len",
"(",
"colors",
")",
"last_page",
"=",
"length",
... | prompt for selection, validate input, return selection | [
"prompt",
"for",
"selection",
"validate",
"input",
"return",
"selection"
] | train | https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/core.py#L99-L164 |
gnullByte/dotcolors | dotcolors/core.py | format_theme | def format_theme(selection):
"""removes any non-color related lines from theme file"""
global themefile
text = open(THEMEDIR + '/' + selection).read()
if '!dotcolors' in text[:10]:
themefile = text
return
lines = ['!dotcolors auto formatted\n']
for line in text.split('\n'):
... | python | def format_theme(selection):
"""removes any non-color related lines from theme file"""
global themefile
text = open(THEMEDIR + '/' + selection).read()
if '!dotcolors' in text[:10]:
themefile = text
return
lines = ['!dotcolors auto formatted\n']
for line in text.split('\n'):
... | [
"def",
"format_theme",
"(",
"selection",
")",
":",
"global",
"themefile",
"text",
"=",
"open",
"(",
"THEMEDIR",
"+",
"'/'",
"+",
"selection",
")",
".",
"read",
"(",
")",
"if",
"'!dotcolors'",
"in",
"text",
"[",
":",
"10",
"]",
":",
"themefile",
"=",
... | removes any non-color related lines from theme file | [
"removes",
"any",
"non",
"-",
"color",
"related",
"lines",
"from",
"theme",
"file"
] | train | https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/core.py#L167-L222 |
gnullByte/dotcolors | dotcolors/core.py | write_transparency | def write_transparency(selection):
"""writes transparency as rgba to ~/.Xresources"""
global themefile, transparency, prefix
if themefile == "":
return
lines = themefile.split('\n')
for line in lines:
if 'background' in line.lower():
try:
background = l... | python | def write_transparency(selection):
"""writes transparency as rgba to ~/.Xresources"""
global themefile, transparency, prefix
if themefile == "":
return
lines = themefile.split('\n')
for line in lines:
if 'background' in line.lower():
try:
background = l... | [
"def",
"write_transparency",
"(",
"selection",
")",
":",
"global",
"themefile",
",",
"transparency",
",",
"prefix",
"if",
"themefile",
"==",
"\"\"",
":",
"return",
"lines",
"=",
"themefile",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":... | writes transparency as rgba to ~/.Xresources | [
"writes",
"transparency",
"as",
"rgba",
"to",
"~",
"/",
".",
"Xresources"
] | train | https://github.com/gnullByte/dotcolors/blob/4b09ff9862b88b3125fe9cd86aa054694ed3e46e/dotcolors/core.py#L238-L288 |
voicecom/pgtool | pgtool/util.py | pretty_size | def pretty_size(value):
"""Convert a number of bytes into a human-readable string.
Output is 2...5 characters. Values >= 1000 always produce output in form: x.xxxU, xx.xxU, xxxU, xxxxU.
"""
exp = int(math.log(value, 1024)) if value > 0 else 0
unit = 'bkMGTPEZY'[exp]
if exp == 0:
return ... | python | def pretty_size(value):
"""Convert a number of bytes into a human-readable string.
Output is 2...5 characters. Values >= 1000 always produce output in form: x.xxxU, xx.xxU, xxxU, xxxxU.
"""
exp = int(math.log(value, 1024)) if value > 0 else 0
unit = 'bkMGTPEZY'[exp]
if exp == 0:
return ... | [
"def",
"pretty_size",
"(",
"value",
")",
":",
"exp",
"=",
"int",
"(",
"math",
".",
"log",
"(",
"value",
",",
"1024",
")",
")",
"if",
"value",
">",
"0",
"else",
"0",
"unit",
"=",
"'bkMGTPEZY'",
"[",
"exp",
"]",
"if",
"exp",
"==",
"0",
":",
"retu... | Convert a number of bytes into a human-readable string.
Output is 2...5 characters. Values >= 1000 always produce output in form: x.xxxU, xx.xxU, xxxU, xxxxU. | [
"Convert",
"a",
"number",
"of",
"bytes",
"into",
"a",
"human",
"-",
"readable",
"string",
"."
] | train | https://github.com/voicecom/pgtool/blob/36b8682bfca614d784fe58451e0cbc41315bc72e/pgtool/util.py#L8-L20 |
neelkamath/hclib | hclib.py | HackChat._on_open | def _on_open(self, _):
"""Joins the hack.chat channel and starts pinging."""
nick = self._format_nick(self._nick, self._pwd)
data = {"cmd": "join", "channel": self._channel, "nick": nick}
self._send_packet(data)
self._thread = True
threading.Thread(target=self._ping).star... | python | def _on_open(self, _):
"""Joins the hack.chat channel and starts pinging."""
nick = self._format_nick(self._nick, self._pwd)
data = {"cmd": "join", "channel": self._channel, "nick": nick}
self._send_packet(data)
self._thread = True
threading.Thread(target=self._ping).star... | [
"def",
"_on_open",
"(",
"self",
",",
"_",
")",
":",
"nick",
"=",
"self",
".",
"_format_nick",
"(",
"self",
".",
"_nick",
",",
"self",
".",
"_pwd",
")",
"data",
"=",
"{",
"\"cmd\"",
":",
"\"join\"",
",",
"\"channel\"",
":",
"self",
".",
"_channel",
... | Joins the hack.chat channel and starts pinging. | [
"Joins",
"the",
"hack",
".",
"chat",
"channel",
"and",
"starts",
"pinging",
"."
] | train | https://github.com/neelkamath/hclib/blob/8678e7abe619796af85f219e280417cfa9a703f2/hclib.py#L117-L123 |
neelkamath/hclib | hclib.py | HackChat._on_message | def _on_message(self, _, msg):
"""Sends and receives data to the callback function."""
result = json.loads(msg)
if result["cmd"] == "chat":
data = {"type": "message", "nick": result["nick"],
"text": result["text"]}
if "trip" in result:
... | python | def _on_message(self, _, msg):
"""Sends and receives data to the callback function."""
result = json.loads(msg)
if result["cmd"] == "chat":
data = {"type": "message", "nick": result["nick"],
"text": result["text"]}
if "trip" in result:
... | [
"def",
"_on_message",
"(",
"self",
",",
"_",
",",
"msg",
")",
":",
"result",
"=",
"json",
".",
"loads",
"(",
"msg",
")",
"if",
"result",
"[",
"\"cmd\"",
"]",
"==",
"\"chat\"",
":",
"data",
"=",
"{",
"\"type\"",
":",
"\"message\"",
",",
"\"nick\"",
... | Sends and receives data to the callback function. | [
"Sends",
"and",
"receives",
"data",
"to",
"the",
"callback",
"function",
"."
] | train | https://github.com/neelkamath/hclib/blob/8678e7abe619796af85f219e280417cfa9a703f2/hclib.py#L147-L198 |
neelkamath/hclib | hclib.py | HackChat.join | def join(self, new_channel, nick, pwd=None):
"""Joins a new channel.
Keyword arguments:
new_channel: <str>; the channel to connect to
nick: <str>; the nickname to use
pwd: <str>; the (optional) password to use
"""
self._send_packet({"cmd": "join", "channel": new_... | python | def join(self, new_channel, nick, pwd=None):
"""Joins a new channel.
Keyword arguments:
new_channel: <str>; the channel to connect to
nick: <str>; the nickname to use
pwd: <str>; the (optional) password to use
"""
self._send_packet({"cmd": "join", "channel": new_... | [
"def",
"join",
"(",
"self",
",",
"new_channel",
",",
"nick",
",",
"pwd",
"=",
"None",
")",
":",
"self",
".",
"_send_packet",
"(",
"{",
"\"cmd\"",
":",
"\"join\"",
",",
"\"channel\"",
":",
"new_channel",
",",
"\"nick\"",
":",
"self",
".",
"_format_nick",
... | Joins a new channel.
Keyword arguments:
new_channel: <str>; the channel to connect to
nick: <str>; the nickname to use
pwd: <str>; the (optional) password to use | [
"Joins",
"a",
"new",
"channel",
"."
] | train | https://github.com/neelkamath/hclib/blob/8678e7abe619796af85f219e280417cfa9a703f2/hclib.py#L333-L342 |
neelkamath/hclib | hclib.py | HackChat.get_help | def get_help(self, is_category, item):
"""Sends documentation on <item> to <callback>.
This can be used for programmatically accessing documentation.
Keyword arguments:
is_category -- <bool>; Set this to <True> if <item> is for
getting documentation on a permissi... | python | def get_help(self, is_category, item):
"""Sends documentation on <item> to <callback>.
This can be used for programmatically accessing documentation.
Keyword arguments:
is_category -- <bool>; Set this to <True> if <item> is for
getting documentation on a permissi... | [
"def",
"get_help",
"(",
"self",
",",
"is_category",
",",
"item",
")",
":",
"data",
"=",
"{",
"\"cmd\"",
":",
"\"help\"",
"}",
"if",
"is_category",
":",
"data",
"[",
"\"category\"",
"]",
"=",
"item",
"else",
":",
"data",
"[",
"\"command\"",
"]",
"=",
... | Sends documentation on <item> to <callback>.
This can be used for programmatically accessing documentation.
Keyword arguments:
is_category -- <bool>; Set this to <True> if <item> is for
getting documentation on a permission level and
<False> if <it... | [
"Sends",
"documentation",
"on",
"<item",
">",
"to",
"<callback",
">",
"."
] | train | https://github.com/neelkamath/hclib/blob/8678e7abe619796af85f219e280417cfa9a703f2/hclib.py#L352-L374 |
wooga/play-deliver | playdeliver/image.py | upload | def upload(client, source_dir):
"""
Upload images to play store.
The function will iterate through source_dir and upload all matching
image_types found in folder herachy.
"""
print('')
print('upload images')
print('-------------')
base_image_folders = [
os.path.join(source_d... | python | def upload(client, source_dir):
"""
Upload images to play store.
The function will iterate through source_dir and upload all matching
image_types found in folder herachy.
"""
print('')
print('upload images')
print('-------------')
base_image_folders = [
os.path.join(source_d... | [
"def",
"upload",
"(",
"client",
",",
"source_dir",
")",
":",
"print",
"(",
"''",
")",
"print",
"(",
"'upload images'",
")",
"print",
"(",
"'-------------'",
")",
"base_image_folders",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"source_dir",
",",
"'im... | Upload images to play store.
The function will iterate through source_dir and upload all matching
image_types found in folder herachy. | [
"Upload",
"images",
"to",
"play",
"store",
"."
] | train | https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L23-L43 |
wooga/play-deliver | playdeliver/image.py | delete_and_upload_images | def delete_and_upload_images(client, image_type, language, base_dir):
"""
Delete and upload images with given image_type and language.
Function will stage delete and stage upload all
found images in matching folders.
"""
print('{0} {1}'.format(image_type, language))
files_in_dir = os.listdi... | python | def delete_and_upload_images(client, image_type, language, base_dir):
"""
Delete and upload images with given image_type and language.
Function will stage delete and stage upload all
found images in matching folders.
"""
print('{0} {1}'.format(image_type, language))
files_in_dir = os.listdi... | [
"def",
"delete_and_upload_images",
"(",
"client",
",",
"image_type",
",",
"language",
",",
"base_dir",
")",
":",
"print",
"(",
"'{0} {1}'",
".",
"format",
"(",
"image_type",
",",
"language",
")",
")",
"files_in_dir",
"=",
"os",
".",
"listdir",
"(",
"os",
"... | Delete and upload images with given image_type and language.
Function will stage delete and stage upload all
found images in matching folders. | [
"Delete",
"and",
"upload",
"images",
"with",
"given",
"image_type",
"and",
"language",
"."
] | train | https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L46-L69 |
wooga/play-deliver | playdeliver/image.py | download | def download(client, target_dir):
"""Download images from play store into folder herachy."""
print('download image previews')
print(
"Warning! Downloaded images are only previews!"
"They may be to small for upload.")
tree = {}
listings = client.list('listings')
languages = map(la... | python | def download(client, target_dir):
"""Download images from play store into folder herachy."""
print('download image previews')
print(
"Warning! Downloaded images are only previews!"
"They may be to small for upload.")
tree = {}
listings = client.list('listings')
languages = map(la... | [
"def",
"download",
"(",
"client",
",",
"target_dir",
")",
":",
"print",
"(",
"'download image previews'",
")",
"print",
"(",
"\"Warning! Downloaded images are only previews!\"",
"\"They may be to small for upload.\"",
")",
"tree",
"=",
"{",
"}",
"listings",
"=",
"client... | Download images from play store into folder herachy. | [
"Download",
"images",
"from",
"play",
"store",
"into",
"folder",
"herachy",
"."
] | train | https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L72-L118 |
wooga/play-deliver | playdeliver/image.py | load_and_save_image | def load_and_save_image(url, destination):
"""Download image from given url and saves it to destination."""
from urllib2 import Request, urlopen, URLError, HTTPError
# create the url and the request
req = Request(url)
# Open the url
try:
f = urlopen(req)
print "downloading " + u... | python | def load_and_save_image(url, destination):
"""Download image from given url and saves it to destination."""
from urllib2 import Request, urlopen, URLError, HTTPError
# create the url and the request
req = Request(url)
# Open the url
try:
f = urlopen(req)
print "downloading " + u... | [
"def",
"load_and_save_image",
"(",
"url",
",",
"destination",
")",
":",
"from",
"urllib2",
"import",
"Request",
",",
"urlopen",
",",
"URLError",
",",
"HTTPError",
"# create the url and the request",
"req",
"=",
"Request",
"(",
"url",
")",
"# Open the url",
"try",
... | Download image from given url and saves it to destination. | [
"Download",
"image",
"from",
"given",
"url",
"and",
"saves",
"it",
"to",
"destination",
"."
] | train | https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L121-L154 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/main.py | get_qapp | def get_qapp():
"""Return an instance of QApplication. Creates one if neccessary.
:returns: a QApplication instance
:rtype: QApplication
:raises: None
"""
global app
app = QtGui.QApplication.instance()
if app is None:
app = QtGui.QApplication([], QtGui.QApplication.GuiClient)
... | python | def get_qapp():
"""Return an instance of QApplication. Creates one if neccessary.
:returns: a QApplication instance
:rtype: QApplication
:raises: None
"""
global app
app = QtGui.QApplication.instance()
if app is None:
app = QtGui.QApplication([], QtGui.QApplication.GuiClient)
... | [
"def",
"get_qapp",
"(",
")",
":",
"global",
"app",
"app",
"=",
"QtGui",
".",
"QApplication",
".",
"instance",
"(",
")",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"QtGui",
".",
"QApplication",
"(",
"[",
"]",
",",
"QtGui",
".",
"QApplication",
".",
... | Return an instance of QApplication. Creates one if neccessary.
:returns: a QApplication instance
:rtype: QApplication
:raises: None | [
"Return",
"an",
"instance",
"of",
"QApplication",
".",
"Creates",
"one",
"if",
"neccessary",
"."
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L30-L41 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/main.py | load_all_resources | def load_all_resources():
"""Load all resources inside this package
When compiling qt resources, the compiled python file will register the resource
on import.
.. Warning:: This will simply import all modules inside this package
"""
pkgname = resources.__name__
for importer, mod_name, _ in... | python | def load_all_resources():
"""Load all resources inside this package
When compiling qt resources, the compiled python file will register the resource
on import.
.. Warning:: This will simply import all modules inside this package
"""
pkgname = resources.__name__
for importer, mod_name, _ in... | [
"def",
"load_all_resources",
"(",
")",
":",
"pkgname",
"=",
"resources",
".",
"__name__",
"for",
"importer",
",",
"mod_name",
",",
"_",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"resources",
".",
"__path__",
")",
":",
"full_mod_name",
"=",
"'%s.%s'",
"%",
... | Load all resources inside this package
When compiling qt resources, the compiled python file will register the resource
on import.
.. Warning:: This will simply import all modules inside this package | [
"Load",
"all",
"resources",
"inside",
"this",
"package"
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L44-L58 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/main.py | set_main_style | def set_main_style(widget):
"""Load the main.qss and apply it to the application
:param widget: The widget to apply the stylesheet to.
Can also be a QApplication. ``setStylesheet`` is called on the widget.
:type widget: :class:`QtGui.QWidget`
:returns: None
:rtype: None
:rais... | python | def set_main_style(widget):
"""Load the main.qss and apply it to the application
:param widget: The widget to apply the stylesheet to.
Can also be a QApplication. ``setStylesheet`` is called on the widget.
:type widget: :class:`QtGui.QWidget`
:returns: None
:rtype: None
:rais... | [
"def",
"set_main_style",
"(",
"widget",
")",
":",
"load_all_resources",
"(",
")",
"with",
"open",
"(",
"MAIN_STYLESHEET",
",",
"'r'",
")",
"as",
"qss",
":",
"sheet",
"=",
"qss",
".",
"read",
"(",
")",
"widget",
".",
"setStyleSheet",
"(",
"sheet",
")"
] | Load the main.qss and apply it to the application
:param widget: The widget to apply the stylesheet to.
Can also be a QApplication. ``setStylesheet`` is called on the widget.
:type widget: :class:`QtGui.QWidget`
:returns: None
:rtype: None
:raises: None | [
"Load",
"the",
"main",
".",
"qss",
"and",
"apply",
"it",
"to",
"the",
"application"
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L61-L74 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/main.py | wrap | def wrap(ptr, base=None):
"""Wrap the given pointer with shiboken and return the appropriate QObject
:returns: if ptr is not None returns a QObject that is cast to the appropriate class
:rtype: QObject | None
:raises: None
"""
if ptr is None:
return None
ptr = long(ptr) # Ensure typ... | python | def wrap(ptr, base=None):
"""Wrap the given pointer with shiboken and return the appropriate QObject
:returns: if ptr is not None returns a QObject that is cast to the appropriate class
:rtype: QObject | None
:raises: None
"""
if ptr is None:
return None
ptr = long(ptr) # Ensure typ... | [
"def",
"wrap",
"(",
"ptr",
",",
"base",
"=",
"None",
")",
":",
"if",
"ptr",
"is",
"None",
":",
"return",
"None",
"ptr",
"=",
"long",
"(",
"ptr",
")",
"# Ensure type",
"if",
"base",
"is",
"None",
":",
"qObj",
"=",
"shiboken",
".",
"wrapInstance",
"(... | Wrap the given pointer with shiboken and return the appropriate QObject
:returns: if ptr is not None returns a QObject that is cast to the appropriate class
:rtype: QObject | None
:raises: None | [
"Wrap",
"the",
"given",
"pointer",
"with",
"shiboken",
"and",
"return",
"the",
"appropriate",
"QObject"
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L89-L110 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/main.py | dt_to_qdatetime | def dt_to_qdatetime(dt):
"""Convert a python datetime.datetime object to QDateTime
:param dt: the datetime object
:type dt: :class:`datetime.datetime`
:returns: the QDateTime conversion
:rtype: :class:`QtCore.QDateTime`
:raises: None
"""
return QtCore.QDateTime(QtCore.QDate(dt.year, dt.... | python | def dt_to_qdatetime(dt):
"""Convert a python datetime.datetime object to QDateTime
:param dt: the datetime object
:type dt: :class:`datetime.datetime`
:returns: the QDateTime conversion
:rtype: :class:`QtCore.QDateTime`
:raises: None
"""
return QtCore.QDateTime(QtCore.QDate(dt.year, dt.... | [
"def",
"dt_to_qdatetime",
"(",
"dt",
")",
":",
"return",
"QtCore",
".",
"QDateTime",
"(",
"QtCore",
".",
"QDate",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
")",
",",
"QtCore",
".",
"QTime",
"(",
"dt",
".",
"hour",
",... | Convert a python datetime.datetime object to QDateTime
:param dt: the datetime object
:type dt: :class:`datetime.datetime`
:returns: the QDateTime conversion
:rtype: :class:`QtCore.QDateTime`
:raises: None | [
"Convert",
"a",
"python",
"datetime",
".",
"datetime",
"object",
"to",
"QDateTime"
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L113-L123 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/main.py | get_icon | def get_icon(name, aspix=False, asicon=False):
"""Return the real file path to the given icon name
If aspix is True return as QtGui.QPixmap, if asicon is True return as QtGui.QIcon.
:param name: the name of the icon
:type name: str
:param aspix: If True, return a QtGui.QPixmap.
:type aspix: boo... | python | def get_icon(name, aspix=False, asicon=False):
"""Return the real file path to the given icon name
If aspix is True return as QtGui.QPixmap, if asicon is True return as QtGui.QIcon.
:param name: the name of the icon
:type name: str
:param aspix: If True, return a QtGui.QPixmap.
:type aspix: boo... | [
"def",
"get_icon",
"(",
"name",
",",
"aspix",
"=",
"False",
",",
"asicon",
"=",
"False",
")",
":",
"datapath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ICON_PATH",
",",
"name",
")",
"icon",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"'jukeb... | Return the real file path to the given icon name
If aspix is True return as QtGui.QPixmap, if asicon is True return as QtGui.QIcon.
:param name: the name of the icon
:type name: str
:param aspix: If True, return a QtGui.QPixmap.
:type aspix: bool
:param asicon: If True, return a QtGui.QIcon.
... | [
"Return",
"the",
"real",
"file",
"path",
"to",
"the",
"given",
"icon",
"name",
"If",
"aspix",
"is",
"True",
"return",
"as",
"QtGui",
".",
"QPixmap",
"if",
"asicon",
"is",
"True",
"return",
"as",
"QtGui",
".",
"QIcon",
"."
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L126-L148 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/main.py | JB_Gui.allinstances | def allinstances(cls):
"""Return all instances that inherit from JB_Gui
:returns: all instances that inherit from JB_Gui
:rtype: list
:raises: None
"""
JB_Gui._allinstances = weakref.WeakSet([i for i in cls._allinstances if shiboken.isValid(i)])
return list(cls._... | python | def allinstances(cls):
"""Return all instances that inherit from JB_Gui
:returns: all instances that inherit from JB_Gui
:rtype: list
:raises: None
"""
JB_Gui._allinstances = weakref.WeakSet([i for i in cls._allinstances if shiboken.isValid(i)])
return list(cls._... | [
"def",
"allinstances",
"(",
"cls",
")",
":",
"JB_Gui",
".",
"_allinstances",
"=",
"weakref",
".",
"WeakSet",
"(",
"[",
"i",
"for",
"i",
"in",
"cls",
".",
"_allinstances",
"if",
"shiboken",
".",
"isValid",
"(",
"i",
")",
"]",
")",
"return",
"list",
"(... | Return all instances that inherit from JB_Gui
:returns: all instances that inherit from JB_Gui
:rtype: list
:raises: None | [
"Return",
"all",
"instances",
"that",
"inherit",
"from",
"JB_Gui"
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L178-L186 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/main.py | JB_Gui.classinstances | def classinstances(cls):
"""Return all instances of the current class
JB_Gui will not return the instances of subclasses
A subclass will only return the instances that have the same
type as the subclass. So it won\'t return instances of further subclasses.
:returns: all instnac... | python | def classinstances(cls):
"""Return all instances of the current class
JB_Gui will not return the instances of subclasses
A subclass will only return the instances that have the same
type as the subclass. So it won\'t return instances of further subclasses.
:returns: all instnac... | [
"def",
"classinstances",
"(",
"cls",
")",
":",
"l",
"=",
"[",
"i",
"for",
"i",
"in",
"cls",
".",
"allinstances",
"(",
")",
"if",
"type",
"(",
"i",
")",
"==",
"cls",
"]",
"return",
"l"
] | Return all instances of the current class
JB_Gui will not return the instances of subclasses
A subclass will only return the instances that have the same
type as the subclass. So it won\'t return instances of further subclasses.
:returns: all instnaces of the current class
:rty... | [
"Return",
"all",
"instances",
"of",
"the",
"current",
"class"
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L189-L201 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/main.py | JB_Gui.instances | def instances(cls):
"""Return all instances of this class and subclasses
:returns: all instances of the current class and subclasses
:rtype: list
:raises: None
"""
l = [i for i in cls.allinstances() if isinstance(i, cls)]
return l | python | def instances(cls):
"""Return all instances of this class and subclasses
:returns: all instances of the current class and subclasses
:rtype: list
:raises: None
"""
l = [i for i in cls.allinstances() if isinstance(i, cls)]
return l | [
"def",
"instances",
"(",
"cls",
")",
":",
"l",
"=",
"[",
"i",
"for",
"i",
"in",
"cls",
".",
"allinstances",
"(",
")",
"if",
"isinstance",
"(",
"i",
",",
"cls",
")",
"]",
"return",
"l"
] | Return all instances of this class and subclasses
:returns: all instances of the current class and subclasses
:rtype: list
:raises: None | [
"Return",
"all",
"instances",
"of",
"this",
"class",
"and",
"subclasses"
] | train | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/main.py#L204-L212 |
etcher-be/elib_miz | elib_miz/validator.py | Validator.validate | def validate(self, value, param_name, exc=None, logger=None):
"""
:param value: value to validate
:param param_name: name of the value (for logging purpose)
:param exc: exception to raise (default is "ValidatorError")
:param logger: logger to use (default will be "Validator.logge... | python | def validate(self, value, param_name, exc=None, logger=None):
"""
:param value: value to validate
:param param_name: name of the value (for logging purpose)
:param exc: exception to raise (default is "ValidatorError")
:param logger: logger to use (default will be "Validator.logge... | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"param_name",
",",
"exc",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"if",
"exc",
"is",
"not",
"None",
":",
"self",
".",
"exc",
"=",
"exc",
"if",
"logger",
"is",
"not",
"None",
":",
"self... | :param value: value to validate
:param param_name: name of the value (for logging purpose)
:param exc: exception to raise (default is "ValidatorError")
:param logger: logger to use (default will be "Validator.logger") | [
":",
"param",
"value",
":",
"value",
"to",
"validate",
":",
"param",
"param_name",
":",
"name",
"of",
"the",
"value",
"(",
"for",
"logging",
"purpose",
")",
":",
"param",
"exc",
":",
"exception",
"to",
"raise",
"(",
"default",
"is",
"ValidatorError",
")"... | train | https://github.com/etcher-be/elib_miz/blob/f28db58fadb2cd9341e0ae4d65101c0cc7d8f3d7/elib_miz/validator.py#L35-L74 |
etcher-be/elib_miz | elib_miz/validator.py | Validator.error | def error(self, error_msg):
"""
Outputs error message on own logger. Also raises exceptions if need be.
Args:
error_msg: message to output
"""
if self.logger is not None:
self.logger.error(error_msg)
if self.exc is not None:
raise se... | python | def error(self, error_msg):
"""
Outputs error message on own logger. Also raises exceptions if need be.
Args:
error_msg: message to output
"""
if self.logger is not None:
self.logger.error(error_msg)
if self.exc is not None:
raise se... | [
"def",
"error",
"(",
"self",
",",
"error_msg",
")",
":",
"if",
"self",
".",
"logger",
"is",
"not",
"None",
":",
"self",
".",
"logger",
".",
"error",
"(",
"error_msg",
")",
"if",
"self",
".",
"exc",
"is",
"not",
"None",
":",
"raise",
"self",
".",
... | Outputs error message on own logger. Also raises exceptions if need be.
Args:
error_msg: message to output | [
"Outputs",
"error",
"message",
"on",
"own",
"logger",
".",
"Also",
"raises",
"exceptions",
"if",
"need",
"be",
"."
] | train | https://github.com/etcher-be/elib_miz/blob/f28db58fadb2cd9341e0ae4d65101c0cc7d8f3d7/elib_miz/validator.py#L76-L88 |
pbrisk/mathtoolspy | mathtoolspy/solver/minimize_algorithm_1dim_golden.py | minimize_algorithm_1dim_golden | def minimize_algorithm_1dim_golden(function, a, b, c, tolerance=DOUBLE_TOL):
'''
Given a function f, and given a bracketing triplet of abscissas ax, bx, cx
(such that bx is between ax and cx, and f(bx) is less than both f(ax) and f(cx)),
this routine performs a golden section search for the minimum, iso... | python | def minimize_algorithm_1dim_golden(function, a, b, c, tolerance=DOUBLE_TOL):
'''
Given a function f, and given a bracketing triplet of abscissas ax, bx, cx
(such that bx is between ax and cx, and f(bx) is less than both f(ax) and f(cx)),
this routine performs a golden section search for the minimum, iso... | [
"def",
"minimize_algorithm_1dim_golden",
"(",
"function",
",",
"a",
",",
"b",
",",
"c",
",",
"tolerance",
"=",
"DOUBLE_TOL",
")",
":",
"x0",
"=",
"a",
"x3",
"=",
"c",
"if",
"abs",
"(",
"c",
"-",
"b",
")",
">",
"abs",
"(",
"b",
"-",
"a",
")",
":... | Given a function f, and given a bracketing triplet of abscissas ax, bx, cx
(such that bx is between ax and cx, and f(bx) is less than both f(ax) and f(cx)),
this routine performs a golden section search for the minimum, isolating it to
a fractional precision of about tol. The abscissa of the minimum is retu... | [
"Given",
"a",
"function",
"f",
"and",
"given",
"a",
"bracketing",
"triplet",
"of",
"abscissas",
"ax",
"bx",
"cx",
"(",
"such",
"that",
"bx",
"is",
"between",
"ax",
"and",
"cx",
"and",
"f",
"(",
"bx",
")",
"is",
"less",
"than",
"both",
"f",
"(",
"ax... | train | https://github.com/pbrisk/mathtoolspy/blob/d0d35b45d20f346ba8a755e53ed0aa182fab43dd/mathtoolspy/solver/minimize_algorithm_1dim_golden.py#L18-L68 |
flo-compbio/goparser | goparser/parser.py | GOParser.get_term_by_name | def get_term_by_name(self, name):
"""Get the GO term with the given GO term name.
If the given name is not associated with any GO term, the function will
search for it among synonyms.
Parameters
----------
name: str
The name of the GO term.
Returns
... | python | def get_term_by_name(self, name):
"""Get the GO term with the given GO term name.
If the given name is not associated with any GO term, the function will
search for it among synonyms.
Parameters
----------
name: str
The name of the GO term.
Returns
... | [
"def",
"get_term_by_name",
"(",
"self",
",",
"name",
")",
":",
"term",
"=",
"None",
"func_name",
"=",
"'get_term_by_name'",
"try",
":",
"term",
"=",
"self",
".",
"terms",
"[",
"self",
".",
"_name2id",
"[",
"name",
"]",
"]",
"except",
"KeyError",
":",
"... | Get the GO term with the given GO term name.
If the given name is not associated with any GO term, the function will
search for it among synonyms.
Parameters
----------
name: str
The name of the GO term.
Returns
-------
GOTerm
Th... | [
"Get",
"the",
"GO",
"term",
"with",
"the",
"given",
"GO",
"term",
"name",
"."
] | train | https://github.com/flo-compbio/goparser/blob/5e27d7d04a26a70a1d9dc113357041abff72be3f/goparser/parser.py#L246-L286 |
flo-compbio/goparser | goparser/parser.py | GOParser.clear_data | def clear_data(self):
"""Clear both ontology and annotation data.
Parameters
----------
Returns
-------
None
"""
self.clear_annotation_data()
self.terms = {}
self._alt_id = {}
self._syn2id = {}
self._name2id = {}
s... | python | def clear_data(self):
"""Clear both ontology and annotation data.
Parameters
----------
Returns
-------
None
"""
self.clear_annotation_data()
self.terms = {}
self._alt_id = {}
self._syn2id = {}
self._name2id = {}
s... | [
"def",
"clear_data",
"(",
"self",
")",
":",
"self",
".",
"clear_annotation_data",
"(",
")",
"self",
".",
"terms",
"=",
"{",
"}",
"self",
".",
"_alt_id",
"=",
"{",
"}",
"self",
".",
"_syn2id",
"=",
"{",
"}",
"self",
".",
"_name2id",
"=",
"{",
"}",
... | Clear both ontology and annotation data.
Parameters
----------
Returns
-------
None | [
"Clear",
"both",
"ontology",
"and",
"annotation",
"data",
"."
] | train | https://github.com/flo-compbio/goparser/blob/5e27d7d04a26a70a1d9dc113357041abff72be3f/goparser/parser.py#L288-L303 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.