repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
nuagenetworks/bambou | bambou/nurest_push_center.py | NURESTPushCenter.remove_delegate | def remove_delegate(self, callback):
""" Unregisters a registered delegate function or a method.
Args:
callback(function): method to trigger when push center receives events
"""
if callback not in self._delegate_methods:
return
self._delegate_me... | python | def remove_delegate(self, callback):
""" Unregisters a registered delegate function or a method.
Args:
callback(function): method to trigger when push center receives events
"""
if callback not in self._delegate_methods:
return
self._delegate_me... | [
"def",
"remove_delegate",
"(",
"self",
",",
"callback",
")",
":",
"if",
"callback",
"not",
"in",
"self",
".",
"_delegate_methods",
":",
"return",
"self",
".",
"_delegate_methods",
".",
"remove",
"(",
"callback",
")"
] | Unregisters a registered delegate function or a method.
Args:
callback(function): method to trigger when push center receives events | [
"Unregisters",
"a",
"registered",
"delegate",
"function",
"or",
"a",
"method",
"."
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L254-L264 | train |
nuagenetworks/bambou | bambou/config.py | BambouConfig._read_config | def _read_config(cls):
""" Reads the configuration file if any
"""
cls._config_parser = configparser.ConfigParser()
cls._config_parser.read(cls._default_attribute_values_configuration_file_path) | python | def _read_config(cls):
""" Reads the configuration file if any
"""
cls._config_parser = configparser.ConfigParser()
cls._config_parser.read(cls._default_attribute_values_configuration_file_path) | [
"def",
"_read_config",
"(",
"cls",
")",
":",
"cls",
".",
"_config_parser",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"cls",
".",
"_config_parser",
".",
"read",
"(",
"cls",
".",
"_default_attribute_values_configuration_file_path",
")"
] | Reads the configuration file if any | [
"Reads",
"the",
"configuration",
"file",
"if",
"any"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/config.py#L108-L113 | train |
nuagenetworks/bambou | bambou/config.py | BambouConfig.get_default_attribute_value | def get_default_attribute_value(cls, object_class, property_name, attr_type=str):
""" Gets the default value of a given property for a given object.
These properties can be set in a config INI file looking like
.. code-block:: ini
[NUEntity]
default_beh... | python | def get_default_attribute_value(cls, object_class, property_name, attr_type=str):
""" Gets the default value of a given property for a given object.
These properties can be set in a config INI file looking like
.. code-block:: ini
[NUEntity]
default_beh... | [
"def",
"get_default_attribute_value",
"(",
"cls",
",",
"object_class",
",",
"property_name",
",",
"attr_type",
"=",
"str",
")",
":",
"if",
"not",
"cls",
".",
"_default_attribute_values_configuration_file_path",
":",
"return",
"None",
"if",
"not",
"cls",
".",
"_con... | Gets the default value of a given property for a given object.
These properties can be set in a config INI file looking like
.. code-block:: ini
[NUEntity]
default_behavior = THIS
speed = 1000
[NUOtherEntity]
att... | [
"Gets",
"the",
"default",
"value",
"of",
"a",
"given",
"property",
"for",
"a",
"given",
"object",
"."
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/config.py#L116-L157 | train |
opennode/waldur-core | waldur_core/core/filters.py | SummaryFilter.filter | def filter(self, request, queryset, view):
""" Filter each resource separately using its own filter """
summary_queryset = queryset
filtered_querysets = []
for queryset in summary_queryset.querysets:
filter_class = self._get_filter(queryset)
queryset = filter_clas... | python | def filter(self, request, queryset, view):
""" Filter each resource separately using its own filter """
summary_queryset = queryset
filtered_querysets = []
for queryset in summary_queryset.querysets:
filter_class = self._get_filter(queryset)
queryset = filter_clas... | [
"def",
"filter",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"summary_queryset",
"=",
"queryset",
"filtered_querysets",
"=",
"[",
"]",
"for",
"queryset",
"in",
"summary_queryset",
".",
"querysets",
":",
"filter_class",
"=",
"self",
"... | Filter each resource separately using its own filter | [
"Filter",
"each",
"resource",
"separately",
"using",
"its",
"own",
"filter"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/filters.py#L275-L285 | train |
stepank/pyws | src/pyws/functions/args/types/__init__.py | TypeFactory | def TypeFactory(type_):
"""
This function creates a standard form type from a simplified form.
>>> from datetime import date, datetime
>>> from pyws.functions.args import TypeFactory
>>> from pyws.functions.args import String, Integer, Float, Date, DateTime
>>> TypeFactory(str) == String
Tr... | python | def TypeFactory(type_):
"""
This function creates a standard form type from a simplified form.
>>> from datetime import date, datetime
>>> from pyws.functions.args import TypeFactory
>>> from pyws.functions.args import String, Integer, Float, Date, DateTime
>>> TypeFactory(str) == String
Tr... | [
"def",
"TypeFactory",
"(",
"type_",
")",
":",
"if",
"isinstance",
"(",
"type_",
",",
"type",
")",
"and",
"issubclass",
"(",
"type_",
",",
"Type",
")",
":",
"return",
"type_",
"for",
"x",
"in",
"__types__",
":",
"if",
"x",
".",
"represents",
"(",
"typ... | This function creates a standard form type from a simplified form.
>>> from datetime import date, datetime
>>> from pyws.functions.args import TypeFactory
>>> from pyws.functions.args import String, Integer, Float, Date, DateTime
>>> TypeFactory(str) == String
True
>>> TypeFactory(float) == Flo... | [
"This",
"function",
"creates",
"a",
"standard",
"form",
"type",
"from",
"a",
"simplified",
"form",
"."
] | ff39133aabeb56bbb08d66286ac0cc8731eda7dd | https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/args/types/__init__.py#L21-L70 | train |
opennode/waldur-core | waldur_core/structure/images.py | dummy_image | def dummy_image(filetype='gif'):
""" Generate empty image in temporary file for testing """
# 1x1px Transparent GIF
GIF = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
tmp_file = tempfile.NamedTemporaryFile(suffix='.%s' % filetype)
tmp_file.write(base64.b64decode(GIF))
return open(t... | python | def dummy_image(filetype='gif'):
""" Generate empty image in temporary file for testing """
# 1x1px Transparent GIF
GIF = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
tmp_file = tempfile.NamedTemporaryFile(suffix='.%s' % filetype)
tmp_file.write(base64.b64decode(GIF))
return open(t... | [
"def",
"dummy_image",
"(",
"filetype",
"=",
"'gif'",
")",
":",
"# 1x1px Transparent GIF",
"GIF",
"=",
"'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'",
"tmp_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.%s'",
"%",
"filetype",
")",... | Generate empty image in temporary file for testing | [
"Generate",
"empty",
"image",
"in",
"temporary",
"file",
"for",
"testing"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/images.py#L14-L20 | train |
quora/qcore | qcore/microtime.py | utime_delta | def utime_delta(days=0, hours=0, minutes=0, seconds=0):
"""Gets time delta in microseconds.
Note: Do NOT use this function without keyword arguments.
It will become much-much harder to add extra time ranges later if positional arguments are used.
"""
return (days * DAY) + (hours * HOUR) + (minutes... | python | def utime_delta(days=0, hours=0, minutes=0, seconds=0):
"""Gets time delta in microseconds.
Note: Do NOT use this function without keyword arguments.
It will become much-much harder to add extra time ranges later if positional arguments are used.
"""
return (days * DAY) + (hours * HOUR) + (minutes... | [
"def",
"utime_delta",
"(",
"days",
"=",
"0",
",",
"hours",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"seconds",
"=",
"0",
")",
":",
"return",
"(",
"days",
"*",
"DAY",
")",
"+",
"(",
"hours",
"*",
"HOUR",
")",
"+",
"(",
"minutes",
"*",
"MINUTE",
... | Gets time delta in microseconds.
Note: Do NOT use this function without keyword arguments.
It will become much-much harder to add extra time ranges later if positional arguments are used. | [
"Gets",
"time",
"delta",
"in",
"microseconds",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/microtime.py#L74-L81 | train |
quora/qcore | qcore/microtime.py | execute_with_timeout | def execute_with_timeout(
fn,
args=None,
kwargs=None,
timeout=None,
fail_if_no_timer=True,
signal_type=_default_signal_type,
timer_type=_default_timer_type,
timeout_exception_cls=TimeoutError,
):
"""
Executes specified function with timeout. Uses SIGALRM to interrupt it.
:ty... | python | def execute_with_timeout(
fn,
args=None,
kwargs=None,
timeout=None,
fail_if_no_timer=True,
signal_type=_default_signal_type,
timer_type=_default_timer_type,
timeout_exception_cls=TimeoutError,
):
"""
Executes specified function with timeout. Uses SIGALRM to interrupt it.
:ty... | [
"def",
"execute_with_timeout",
"(",
"fn",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"fail_if_no_timer",
"=",
"True",
",",
"signal_type",
"=",
"_default_signal_type",
",",
"timer_type",
"=",
"_default_timer_type",
"... | Executes specified function with timeout. Uses SIGALRM to interrupt it.
:type fn: function
:param fn: function to execute
:type args: tuple
:param args: function args
:type kwargs: dict
:param kwargs: function kwargs
:type timeout: float
:param timeout: timeout, seconds; 0 or None me... | [
"Executes",
"specified",
"function",
"with",
"timeout",
".",
"Uses",
"SIGALRM",
"to",
"interrupt",
"it",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/microtime.py#L132-L202 | train |
quora/qcore | qcore/inspection.py | get_original_fn | def get_original_fn(fn):
"""Gets the very original function of a decorated one."""
fn_type = type(fn)
if fn_type is classmethod or fn_type is staticmethod:
return get_original_fn(fn.__func__)
if hasattr(fn, "original_fn"):
return fn.original_fn
if hasattr(fn, "fn"):
fn.origi... | python | def get_original_fn(fn):
"""Gets the very original function of a decorated one."""
fn_type = type(fn)
if fn_type is classmethod or fn_type is staticmethod:
return get_original_fn(fn.__func__)
if hasattr(fn, "original_fn"):
return fn.original_fn
if hasattr(fn, "fn"):
fn.origi... | [
"def",
"get_original_fn",
"(",
"fn",
")",
":",
"fn_type",
"=",
"type",
"(",
"fn",
")",
"if",
"fn_type",
"is",
"classmethod",
"or",
"fn_type",
"is",
"staticmethod",
":",
"return",
"get_original_fn",
"(",
"fn",
".",
"__func__",
")",
"if",
"hasattr",
"(",
"... | Gets the very original function of a decorated one. | [
"Gets",
"the",
"very",
"original",
"function",
"of",
"a",
"decorated",
"one",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L27-L38 | train |
quora/qcore | qcore/inspection.py | get_full_name | def get_full_name(src):
"""Gets full class or function name."""
if hasattr(src, "_full_name_"):
return src._full_name_
if hasattr(src, "is_decorator"):
# Our own decorator or binder
if hasattr(src, "decorator"):
# Our own binder
_full_name_ = str(src.decorato... | python | def get_full_name(src):
"""Gets full class or function name."""
if hasattr(src, "_full_name_"):
return src._full_name_
if hasattr(src, "is_decorator"):
# Our own decorator or binder
if hasattr(src, "decorator"):
# Our own binder
_full_name_ = str(src.decorato... | [
"def",
"get_full_name",
"(",
"src",
")",
":",
"if",
"hasattr",
"(",
"src",
",",
"\"_full_name_\"",
")",
":",
"return",
"src",
".",
"_full_name_",
"if",
"hasattr",
"(",
"src",
",",
"\"is_decorator\"",
")",
":",
"# Our own decorator or binder",
"if",
"hasattr",
... | Gets full class or function name. | [
"Gets",
"full",
"class",
"or",
"function",
"name",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L41-L82 | train |
quora/qcore | qcore/inspection.py | get_function_call_str | def get_function_call_str(fn, args, kwargs):
"""Converts method call (function and its arguments) to a str(...)-like string."""
def str_converter(v):
try:
return str(v)
except Exception:
try:
return repr(v)
except Exception:
re... | python | def get_function_call_str(fn, args, kwargs):
"""Converts method call (function and its arguments) to a str(...)-like string."""
def str_converter(v):
try:
return str(v)
except Exception:
try:
return repr(v)
except Exception:
re... | [
"def",
"get_function_call_str",
"(",
"fn",
",",
"args",
",",
"kwargs",
")",
":",
"def",
"str_converter",
"(",
"v",
")",
":",
"try",
":",
"return",
"str",
"(",
"v",
")",
"except",
"Exception",
":",
"try",
":",
"return",
"repr",
"(",
"v",
")",
"except"... | Converts method call (function and its arguments) to a str(...)-like string. | [
"Converts",
"method",
"call",
"(",
"function",
"and",
"its",
"arguments",
")",
"to",
"a",
"str",
"(",
"...",
")",
"-",
"like",
"string",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L85-L112 | train |
quora/qcore | qcore/inspection.py | get_function_call_repr | def get_function_call_repr(fn, args, kwargs):
"""Converts method call (function and its arguments) to a repr(...)-like string."""
result = get_full_name(fn) + "("
first = True
for v in args:
if first:
first = False
else:
result += ","
result += repr(v)
... | python | def get_function_call_repr(fn, args, kwargs):
"""Converts method call (function and its arguments) to a repr(...)-like string."""
result = get_full_name(fn) + "("
first = True
for v in args:
if first:
first = False
else:
result += ","
result += repr(v)
... | [
"def",
"get_function_call_repr",
"(",
"fn",
",",
"args",
",",
"kwargs",
")",
":",
"result",
"=",
"get_full_name",
"(",
"fn",
")",
"+",
"\"(\"",
"first",
"=",
"True",
"for",
"v",
"in",
"args",
":",
"if",
"first",
":",
"first",
"=",
"False",
"else",
":... | Converts method call (function and its arguments) to a repr(...)-like string. | [
"Converts",
"method",
"call",
"(",
"function",
"and",
"its",
"arguments",
")",
"to",
"a",
"repr",
"(",
"...",
")",
"-",
"like",
"string",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L115-L133 | train |
quora/qcore | qcore/inspection.py | getargspec | def getargspec(func):
"""Variation of inspect.getargspec that works for more functions.
This function works for Cythonized, non-cpdef functions, which expose argspec information but
are not accepted by getargspec. It also works for Python 3 functions that use annotations, which
are simply ignored. Howe... | python | def getargspec(func):
"""Variation of inspect.getargspec that works for more functions.
This function works for Cythonized, non-cpdef functions, which expose argspec information but
are not accepted by getargspec. It also works for Python 3 functions that use annotations, which
are simply ignored. Howe... | [
"def",
"getargspec",
"(",
"func",
")",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"func",
"=",
"func",
".",
"__func__",
"# Cythonized functions have a .__code__, but don't pass inspect.isfunction()",
"try",
":",
"code",
"=",
"func",
".",
"__code... | Variation of inspect.getargspec that works for more functions.
This function works for Cythonized, non-cpdef functions, which expose argspec information but
are not accepted by getargspec. It also works for Python 3 functions that use annotations, which
are simply ignored. However, keyword-only arguments a... | [
"Variation",
"of",
"inspect",
".",
"getargspec",
"that",
"works",
"for",
"more",
"functions",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L136-L154 | train |
quora/qcore | qcore/inspection.py | is_cython_or_generator | def is_cython_or_generator(fn):
"""Returns whether this function is either a generator function or a Cythonized function."""
if hasattr(fn, "__func__"):
fn = fn.__func__ # Class method, static method
if inspect.isgeneratorfunction(fn):
return True
name = type(fn).__name__
return (
... | python | def is_cython_or_generator(fn):
"""Returns whether this function is either a generator function or a Cythonized function."""
if hasattr(fn, "__func__"):
fn = fn.__func__ # Class method, static method
if inspect.isgeneratorfunction(fn):
return True
name = type(fn).__name__
return (
... | [
"def",
"is_cython_or_generator",
"(",
"fn",
")",
":",
"if",
"hasattr",
"(",
"fn",
",",
"\"__func__\"",
")",
":",
"fn",
"=",
"fn",
".",
"__func__",
"# Class method, static method",
"if",
"inspect",
".",
"isgeneratorfunction",
"(",
"fn",
")",
":",
"return",
"T... | Returns whether this function is either a generator function or a Cythonized function. | [
"Returns",
"whether",
"this",
"function",
"is",
"either",
"a",
"generator",
"function",
"or",
"a",
"Cythonized",
"function",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L157-L169 | train |
quora/qcore | qcore/inspection.py | is_cython_function | def is_cython_function(fn):
"""Checks if a function is compiled w/Cython."""
if hasattr(fn, "__func__"):
fn = fn.__func__ # Class method, static method
name = type(fn).__name__
return (
name == "method_descriptor"
or name == "cython_function_or_method"
or name == "builti... | python | def is_cython_function(fn):
"""Checks if a function is compiled w/Cython."""
if hasattr(fn, "__func__"):
fn = fn.__func__ # Class method, static method
name = type(fn).__name__
return (
name == "method_descriptor"
or name == "cython_function_or_method"
or name == "builti... | [
"def",
"is_cython_function",
"(",
"fn",
")",
":",
"if",
"hasattr",
"(",
"fn",
",",
"\"__func__\"",
")",
":",
"fn",
"=",
"fn",
".",
"__func__",
"# Class method, static method",
"name",
"=",
"type",
"(",
"fn",
")",
".",
"__name__",
"return",
"(",
"name",
"... | Checks if a function is compiled w/Cython. | [
"Checks",
"if",
"a",
"function",
"is",
"compiled",
"w",
"/",
"Cython",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L172-L181 | train |
quora/qcore | qcore/inspection.py | is_classmethod | def is_classmethod(fn):
"""Returns whether f is a classmethod."""
# This is True for bound methods
if not inspect.ismethod(fn):
return False
if not hasattr(fn, "__self__"):
return False
im_self = fn.__self__
# This is None for instance methods on classes, but True
# for insta... | python | def is_classmethod(fn):
"""Returns whether f is a classmethod."""
# This is True for bound methods
if not inspect.ismethod(fn):
return False
if not hasattr(fn, "__self__"):
return False
im_self = fn.__self__
# This is None for instance methods on classes, but True
# for insta... | [
"def",
"is_classmethod",
"(",
"fn",
")",
":",
"# This is True for bound methods",
"if",
"not",
"inspect",
".",
"ismethod",
"(",
"fn",
")",
":",
"return",
"False",
"if",
"not",
"hasattr",
"(",
"fn",
",",
"\"__self__\"",
")",
":",
"return",
"False",
"im_self",... | Returns whether f is a classmethod. | [
"Returns",
"whether",
"f",
"is",
"a",
"classmethod",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L189-L202 | train |
quora/qcore | qcore/inspection.py | wraps | def wraps(
wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES
):
"""Cython-compatible functools.wraps implementation."""
if not is_cython_function(wrapped):
return functools.wraps(wrapped, assigned, updated)
else:
return lambda wrapper: wrapper | python | def wraps(
wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES
):
"""Cython-compatible functools.wraps implementation."""
if not is_cython_function(wrapped):
return functools.wraps(wrapped, assigned, updated)
else:
return lambda wrapper: wrapper | [
"def",
"wraps",
"(",
"wrapped",
",",
"assigned",
"=",
"functools",
".",
"WRAPPER_ASSIGNMENTS",
",",
"updated",
"=",
"functools",
".",
"WRAPPER_UPDATES",
")",
":",
"if",
"not",
"is_cython_function",
"(",
"wrapped",
")",
":",
"return",
"functools",
".",
"wraps",... | Cython-compatible functools.wraps implementation. | [
"Cython",
"-",
"compatible",
"functools",
".",
"wraps",
"implementation",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L205-L212 | train |
quora/qcore | qcore/inspection.py | get_subclass_tree | def get_subclass_tree(cls, ensure_unique=True):
"""Returns all subclasses (direct and recursive) of cls."""
subclasses = []
# cls.__subclasses__() fails on classes inheriting from type
for subcls in type.__subclasses__(cls):
subclasses.append(subcls)
subclasses.extend(get_subclass_tree(s... | python | def get_subclass_tree(cls, ensure_unique=True):
"""Returns all subclasses (direct and recursive) of cls."""
subclasses = []
# cls.__subclasses__() fails on classes inheriting from type
for subcls in type.__subclasses__(cls):
subclasses.append(subcls)
subclasses.extend(get_subclass_tree(s... | [
"def",
"get_subclass_tree",
"(",
"cls",
",",
"ensure_unique",
"=",
"True",
")",
":",
"subclasses",
"=",
"[",
"]",
"# cls.__subclasses__() fails on classes inheriting from type",
"for",
"subcls",
"in",
"type",
".",
"__subclasses__",
"(",
"cls",
")",
":",
"subclasses"... | Returns all subclasses (direct and recursive) of cls. | [
"Returns",
"all",
"subclasses",
"(",
"direct",
"and",
"recursive",
")",
"of",
"cls",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L215-L222 | train |
stepank/pyws | src/pyws/functions/args/types/complex.py | DictOf | def DictOf(name, *fields):
"""
This function creates a dict type with the specified name and fields.
>>> from pyws.functions.args import DictOf, Field
>>> dct = DictOf(
... 'HelloWorldDict', Field('hello', str), Field('hello', int))
>>> issubclass(dct, Dict)
True
>>> dct.__name__
... | python | def DictOf(name, *fields):
"""
This function creates a dict type with the specified name and fields.
>>> from pyws.functions.args import DictOf, Field
>>> dct = DictOf(
... 'HelloWorldDict', Field('hello', str), Field('hello', int))
>>> issubclass(dct, Dict)
True
>>> dct.__name__
... | [
"def",
"DictOf",
"(",
"name",
",",
"*",
"fields",
")",
":",
"ret",
"=",
"type",
"(",
"name",
",",
"(",
"Dict",
",",
")",
",",
"{",
"'fields'",
":",
"[",
"]",
"}",
")",
"#noinspection PyUnresolvedReferences",
"ret",
".",
"add_fields",
"(",
"*",
"field... | This function creates a dict type with the specified name and fields.
>>> from pyws.functions.args import DictOf, Field
>>> dct = DictOf(
... 'HelloWorldDict', Field('hello', str), Field('hello', int))
>>> issubclass(dct, Dict)
True
>>> dct.__name__
'HelloWorldDict'
>>> len(dct.fiel... | [
"This",
"function",
"creates",
"a",
"dict",
"type",
"with",
"the",
"specified",
"name",
"and",
"fields",
"."
] | ff39133aabeb56bbb08d66286ac0cc8731eda7dd | https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/args/types/complex.py#L88-L105 | train |
stepank/pyws | src/pyws/functions/args/types/complex.py | ListOf | def ListOf(element_type, element_none_value=None):
"""
This function creates a list type with element type ``element_type`` and an
empty element value ``element_none_value``.
>>> from pyws.functions.args import Integer, ListOf
>>> lst = ListOf(int)
>>> issubclass(lst, List)
True
>>> lst... | python | def ListOf(element_type, element_none_value=None):
"""
This function creates a list type with element type ``element_type`` and an
empty element value ``element_none_value``.
>>> from pyws.functions.args import Integer, ListOf
>>> lst = ListOf(int)
>>> issubclass(lst, List)
True
>>> lst... | [
"def",
"ListOf",
"(",
"element_type",
",",
"element_none_value",
"=",
"None",
")",
":",
"from",
"pyws",
".",
"functions",
".",
"args",
".",
"types",
"import",
"TypeFactory",
"element_type",
"=",
"TypeFactory",
"(",
"element_type",
")",
"return",
"type",
"(",
... | This function creates a list type with element type ``element_type`` and an
empty element value ``element_none_value``.
>>> from pyws.functions.args import Integer, ListOf
>>> lst = ListOf(int)
>>> issubclass(lst, List)
True
>>> lst.__name__
'IntegerList'
>>> lst.element_type == Integer... | [
"This",
"function",
"creates",
"a",
"list",
"type",
"with",
"element",
"type",
"element_type",
"and",
"an",
"empty",
"element",
"value",
"element_none_value",
"."
] | ff39133aabeb56bbb08d66286ac0cc8731eda7dd | https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/args/types/complex.py#L108-L126 | train |
opennode/waldur-core | waldur_core/structure/metadata.py | ActionsMetadata.get_actions | def get_actions(self, request, view):
"""
Return metadata for resource-specific actions,
such as start, stop, unlink
"""
metadata = OrderedDict()
actions = self.get_resource_actions(view)
resource = view.get_object()
for action_name, action in actions.ite... | python | def get_actions(self, request, view):
"""
Return metadata for resource-specific actions,
such as start, stop, unlink
"""
metadata = OrderedDict()
actions = self.get_resource_actions(view)
resource = view.get_object()
for action_name, action in actions.ite... | [
"def",
"get_actions",
"(",
"self",
",",
"request",
",",
"view",
")",
":",
"metadata",
"=",
"OrderedDict",
"(",
")",
"actions",
"=",
"self",
".",
"get_resource_actions",
"(",
"view",
")",
"resource",
"=",
"view",
".",
"get_object",
"(",
")",
"for",
"actio... | Return metadata for resource-specific actions,
such as start, stop, unlink | [
"Return",
"metadata",
"for",
"resource",
"-",
"specific",
"actions",
"such",
"as",
"start",
"stop",
"unlink"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L96-L125 | train |
opennode/waldur-core | waldur_core/structure/metadata.py | ActionsMetadata.get_action_fields | def get_action_fields(self, view, action_name, resource):
"""
Get fields exposed by action's serializer
"""
serializer = view.get_serializer(resource)
fields = OrderedDict()
if not isinstance(serializer, view.serializer_class) or action_name == 'update':
field... | python | def get_action_fields(self, view, action_name, resource):
"""
Get fields exposed by action's serializer
"""
serializer = view.get_serializer(resource)
fields = OrderedDict()
if not isinstance(serializer, view.serializer_class) or action_name == 'update':
field... | [
"def",
"get_action_fields",
"(",
"self",
",",
"view",
",",
"action_name",
",",
"resource",
")",
":",
"serializer",
"=",
"view",
".",
"get_serializer",
"(",
"resource",
")",
"fields",
"=",
"OrderedDict",
"(",
")",
"if",
"not",
"isinstance",
"(",
"serializer",... | Get fields exposed by action's serializer | [
"Get",
"fields",
"exposed",
"by",
"action",
"s",
"serializer"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L150-L158 | train |
opennode/waldur-core | waldur_core/structure/metadata.py | ActionsMetadata.get_serializer_info | def get_serializer_info(self, serializer):
"""
Given an instance of a serializer, return a dictionary of metadata
about its fields.
"""
if hasattr(serializer, 'child'):
# If this is a `ListSerializer` then we want to examine the
# underlying child serializ... | python | def get_serializer_info(self, serializer):
"""
Given an instance of a serializer, return a dictionary of metadata
about its fields.
"""
if hasattr(serializer, 'child'):
# If this is a `ListSerializer` then we want to examine the
# underlying child serializ... | [
"def",
"get_serializer_info",
"(",
"self",
",",
"serializer",
")",
":",
"if",
"hasattr",
"(",
"serializer",
",",
"'child'",
")",
":",
"# If this is a `ListSerializer` then we want to examine the",
"# underlying child serializer instance instead.",
"serializer",
"=",
"serializ... | Given an instance of a serializer, return a dictionary of metadata
about its fields. | [
"Given",
"an",
"instance",
"of",
"a",
"serializer",
"return",
"a",
"dictionary",
"of",
"metadata",
"about",
"its",
"fields",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L160-L169 | train |
opennode/waldur-core | waldur_core/structure/metadata.py | ActionsMetadata.get_fields | def get_fields(self, serializer_fields):
"""
Get fields metadata skipping empty fields
"""
fields = OrderedDict()
for field_name, field in serializer_fields.items():
# Skip tags field in action because it is needed only for resource creation
# See also: WA... | python | def get_fields(self, serializer_fields):
"""
Get fields metadata skipping empty fields
"""
fields = OrderedDict()
for field_name, field in serializer_fields.items():
# Skip tags field in action because it is needed only for resource creation
# See also: WA... | [
"def",
"get_fields",
"(",
"self",
",",
"serializer_fields",
")",
":",
"fields",
"=",
"OrderedDict",
"(",
")",
"for",
"field_name",
",",
"field",
"in",
"serializer_fields",
".",
"items",
"(",
")",
":",
"# Skip tags field in action because it is needed only for resource... | Get fields metadata skipping empty fields | [
"Get",
"fields",
"metadata",
"skipping",
"empty",
"fields"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L171-L184 | train |
opennode/waldur-core | waldur_core/structure/metadata.py | ActionsMetadata.get_field_info | def get_field_info(self, field, field_name):
"""
Given an instance of a serializer field, return a dictionary
of metadata about it.
"""
field_info = OrderedDict()
field_info['type'] = self.label_lookup[field]
field_info['required'] = getattr(field, 'required', Fal... | python | def get_field_info(self, field, field_name):
"""
Given an instance of a serializer field, return a dictionary
of metadata about it.
"""
field_info = OrderedDict()
field_info['type'] = self.label_lookup[field]
field_info['required'] = getattr(field, 'required', Fal... | [
"def",
"get_field_info",
"(",
"self",
",",
"field",
",",
"field_name",
")",
":",
"field_info",
"=",
"OrderedDict",
"(",
")",
"field_info",
"[",
"'type'",
"]",
"=",
"self",
".",
"label_lookup",
"[",
"field",
"]",
"field_info",
"[",
"'required'",
"]",
"=",
... | Given an instance of a serializer field, return a dictionary
of metadata about it. | [
"Given",
"an",
"instance",
"of",
"a",
"serializer",
"field",
"return",
"a",
"dictionary",
"of",
"metadata",
"about",
"it",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L186-L230 | train |
zeromake/aiosqlite3 | aiosqlite3/connection.py | connect | def connect(
database: str,
loop: asyncio.BaseEventLoop = None,
executor: concurrent.futures.Executor = None,
timeout: int = 5,
echo: bool = False,
isolation_level: str = '',
check_same_thread: bool = False,
**kwargs: dict
):
"""
把async方法执行后的对象创建为a... | python | def connect(
database: str,
loop: asyncio.BaseEventLoop = None,
executor: concurrent.futures.Executor = None,
timeout: int = 5,
echo: bool = False,
isolation_level: str = '',
check_same_thread: bool = False,
**kwargs: dict
):
"""
把async方法执行后的对象创建为a... | [
"def",
"connect",
"(",
"database",
":",
"str",
",",
"loop",
":",
"asyncio",
".",
"BaseEventLoop",
"=",
"None",
",",
"executor",
":",
"concurrent",
".",
"futures",
".",
"Executor",
"=",
"None",
",",
"timeout",
":",
"int",
"=",
"5",
",",
"echo",
":",
"... | 把async方法执行后的对象创建为async上下文模式 | [
"把async方法执行后的对象创建为async上下文模式"
] | 1a74a062507e2df8f833a70885e69dca0ab3e7e7 | https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/connection.py#L443-L466 | train |
opennode/waldur-core | waldur_core/cost_tracking/tasks.py | recalculate_estimate | def recalculate_estimate(recalculate_total=False):
""" Recalculate price of consumables that were used by resource until now.
Regular task. It is too expensive to calculate consumed price on each
request, so we store cached price each hour.
If recalculate_total is True - task also recalcula... | python | def recalculate_estimate(recalculate_total=False):
""" Recalculate price of consumables that were used by resource until now.
Regular task. It is too expensive to calculate consumed price on each
request, so we store cached price each hour.
If recalculate_total is True - task also recalcula... | [
"def",
"recalculate_estimate",
"(",
"recalculate_total",
"=",
"False",
")",
":",
"# Celery does not import server.urls and does not discover cost tracking modules.",
"# So they should be discovered implicitly.",
"CostTrackingRegister",
".",
"autodiscover",
"(",
")",
"# Step 1. Recalcul... | Recalculate price of consumables that were used by resource until now.
Regular task. It is too expensive to calculate consumed price on each
request, so we store cached price each hour.
If recalculate_total is True - task also recalculates total estimate
for current month. | [
"Recalculate",
"price",
"of",
"consumables",
"that",
"were",
"used",
"by",
"resource",
"until",
"now",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/tasks.py#L8-L29 | train |
deathbeds/importnb | src/importnb/loader.py | ImportLibMixin.get_data | def get_data(self, path):
"""Needs to return the string source for the module."""
return LineCacheNotebookDecoder(
code=self.code, raw=self.raw, markdown=self.markdown
).decode(self.decode(), self.path) | python | def get_data(self, path):
"""Needs to return the string source for the module."""
return LineCacheNotebookDecoder(
code=self.code, raw=self.raw, markdown=self.markdown
).decode(self.decode(), self.path) | [
"def",
"get_data",
"(",
"self",
",",
"path",
")",
":",
"return",
"LineCacheNotebookDecoder",
"(",
"code",
"=",
"self",
".",
"code",
",",
"raw",
"=",
"self",
".",
"raw",
",",
"markdown",
"=",
"self",
".",
"markdown",
")",
".",
"decode",
"(",
"self",
"... | Needs to return the string source for the module. | [
"Needs",
"to",
"return",
"the",
"string",
"source",
"for",
"the",
"module",
"."
] | ec870d1f8ab99fd5b363267f89787a3e442a779f | https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L138-L142 | train |
deathbeds/importnb | src/importnb/loader.py | NotebookBaseLoader.loader | def loader(self):
"""Create a lazy loader source file loader."""
loader = super().loader
if self._lazy and (sys.version_info.major, sys.version_info.minor) != (3, 4):
loader = LazyLoader.factory(loader)
# Strip the leading underscore from slots
return partial(
... | python | def loader(self):
"""Create a lazy loader source file loader."""
loader = super().loader
if self._lazy and (sys.version_info.major, sys.version_info.minor) != (3, 4):
loader = LazyLoader.factory(loader)
# Strip the leading underscore from slots
return partial(
... | [
"def",
"loader",
"(",
"self",
")",
":",
"loader",
"=",
"super",
"(",
")",
".",
"loader",
"if",
"self",
".",
"_lazy",
"and",
"(",
"sys",
".",
"version_info",
".",
"major",
",",
"sys",
".",
"version_info",
".",
"minor",
")",
"!=",
"(",
"3",
",",
"4... | Create a lazy loader source file loader. | [
"Create",
"a",
"lazy",
"loader",
"source",
"file",
"loader",
"."
] | ec870d1f8ab99fd5b363267f89787a3e442a779f | https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L182-L190 | train |
deathbeds/importnb | src/importnb/loader.py | FromFileMixin.load | def load(cls, filename, dir=None, main=False, **kwargs):
"""Import a notebook as a module from a filename.
dir: The directory to load the file from.
main: Load the module in the __main__ context.
> assert Notebook.load('loader.ipynb')
"""
name = main and... | python | def load(cls, filename, dir=None, main=False, **kwargs):
"""Import a notebook as a module from a filename.
dir: The directory to load the file from.
main: Load the module in the __main__ context.
> assert Notebook.load('loader.ipynb')
"""
name = main and... | [
"def",
"load",
"(",
"cls",
",",
"filename",
",",
"dir",
"=",
"None",
",",
"main",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"main",
"and",
"\"__main__\"",
"or",
"Path",
"(",
"filename",
")",
".",
"stem",
"loader",
"=",
"cls",
... | Import a notebook as a module from a filename.
dir: The directory to load the file from.
main: Load the module in the __main__ context.
> assert Notebook.load('loader.ipynb') | [
"Import",
"a",
"notebook",
"as",
"a",
"module",
"from",
"a",
"filename",
".",
"dir",
":",
"The",
"directory",
"to",
"load",
"the",
"file",
"from",
".",
"main",
":",
"Load",
"the",
"module",
"in",
"the",
"__main__",
"context",
".",
">",
"assert",
"Noteb... | ec870d1f8ab99fd5b363267f89787a3e442a779f | https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L213-L233 | train |
deathbeds/importnb | src/importnb/loader.py | Notebook.source_to_code | def source_to_code(self, nodes, path, *, _optimize=-1):
"""* Convert the current source to ast
* Apply ast transformers.
* Compile the code."""
if not isinstance(nodes, ast.Module):
nodes = ast.parse(nodes, self.path)
if self._markdown_docstring:
nodes = ... | python | def source_to_code(self, nodes, path, *, _optimize=-1):
"""* Convert the current source to ast
* Apply ast transformers.
* Compile the code."""
if not isinstance(nodes, ast.Module):
nodes = ast.parse(nodes, self.path)
if self._markdown_docstring:
nodes = ... | [
"def",
"source_to_code",
"(",
"self",
",",
"nodes",
",",
"path",
",",
"*",
",",
"_optimize",
"=",
"-",
"1",
")",
":",
"if",
"not",
"isinstance",
"(",
"nodes",
",",
"ast",
".",
"Module",
")",
":",
"nodes",
"=",
"ast",
".",
"parse",
"(",
"nodes",
"... | * Convert the current source to ast
* Apply ast transformers.
* Compile the code. | [
"*",
"Convert",
"the",
"current",
"source",
"to",
"ast",
"*",
"Apply",
"ast",
"transformers",
".",
"*",
"Compile",
"the",
"code",
"."
] | ec870d1f8ab99fd5b363267f89787a3e442a779f | https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L293-L303 | train |
opennode/waldur-core | waldur_core/core/admin.py | ExtraActionsMixin.get_urls | def get_urls(self):
"""
Inject extra action URLs.
"""
urls = []
for action in self.get_extra_actions():
regex = r'^{}/$'.format(self._get_action_href(action))
view = self.admin_site.admin_view(action)
urls.append(url(regex, view))
ret... | python | def get_urls(self):
"""
Inject extra action URLs.
"""
urls = []
for action in self.get_extra_actions():
regex = r'^{}/$'.format(self._get_action_href(action))
view = self.admin_site.admin_view(action)
urls.append(url(regex, view))
ret... | [
"def",
"get_urls",
"(",
"self",
")",
":",
"urls",
"=",
"[",
"]",
"for",
"action",
"in",
"self",
".",
"get_extra_actions",
"(",
")",
":",
"regex",
"=",
"r'^{}/$'",
".",
"format",
"(",
"self",
".",
"_get_action_href",
"(",
"action",
")",
")",
"view",
"... | Inject extra action URLs. | [
"Inject",
"extra",
"action",
"URLs",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/admin.py#L312-L323 | train |
opennode/waldur-core | waldur_core/core/admin.py | ExtraActionsMixin.changelist_view | def changelist_view(self, request, extra_context=None):
"""
Inject extra links into template context.
"""
links = []
for action in self.get_extra_actions():
links.append({
'label': self._get_action_label(action),
'href': self._get_acti... | python | def changelist_view(self, request, extra_context=None):
"""
Inject extra links into template context.
"""
links = []
for action in self.get_extra_actions():
links.append({
'label': self._get_action_label(action),
'href': self._get_acti... | [
"def",
"changelist_view",
"(",
"self",
",",
"request",
",",
"extra_context",
"=",
"None",
")",
":",
"links",
"=",
"[",
"]",
"for",
"action",
"in",
"self",
".",
"get_extra_actions",
"(",
")",
":",
"links",
".",
"append",
"(",
"{",
"'label'",
":",
"self"... | Inject extra links into template context. | [
"Inject",
"extra",
"links",
"into",
"template",
"context",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/admin.py#L325-L342 | train |
nuagenetworks/bambou | bambou/nurest_session.py | NURESTSession.start | def start(self):
"""
Starts the session.
Starting the session will actually get the API key of the current user
"""
if NURESTSession.session_stack:
bambou_logger.critical("Starting a session inside a with statement is not supported.")
raise Excep... | python | def start(self):
"""
Starts the session.
Starting the session will actually get the API key of the current user
"""
if NURESTSession.session_stack:
bambou_logger.critical("Starting a session inside a with statement is not supported.")
raise Excep... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"NURESTSession",
".",
"session_stack",
":",
"bambou_logger",
".",
"critical",
"(",
"\"Starting a session inside a with statement is not supported.\"",
")",
"raise",
"Exception",
"(",
"\"Starting a session inside a with statement is... | Starts the session.
Starting the session will actually get the API key of the current user | [
"Starts",
"the",
"session",
"."
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_session.py#L155-L169 | train |
opennode/waldur-core | waldur_core/quotas/handlers.py | init_quotas | def init_quotas(sender, instance, created=False, **kwargs):
""" Initialize new instances quotas """
if not created:
return
for field in sender.get_quotas_fields():
try:
field.get_or_create_quota(scope=instance)
except CreationConditionFailedQuotaError:
pass | python | def init_quotas(sender, instance, created=False, **kwargs):
""" Initialize new instances quotas """
if not created:
return
for field in sender.get_quotas_fields():
try:
field.get_or_create_quota(scope=instance)
except CreationConditionFailedQuotaError:
pass | [
"def",
"init_quotas",
"(",
"sender",
",",
"instance",
",",
"created",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"created",
":",
"return",
"for",
"field",
"in",
"sender",
".",
"get_quotas_fields",
"(",
")",
":",
"try",
":",
"field",
... | Initialize new instances quotas | [
"Initialize",
"new",
"instances",
"quotas"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/handlers.py#L35-L43 | train |
opennode/waldur-core | waldur_core/quotas/handlers.py | count_quota_handler_factory | def count_quota_handler_factory(count_quota_field):
""" Creates handler that will recalculate count_quota on creation/deletion """
def recalculate_count_quota(sender, instance, **kwargs):
signal = kwargs['signal']
if signal == signals.post_save and kwargs.get('created'):
count_quota... | python | def count_quota_handler_factory(count_quota_field):
""" Creates handler that will recalculate count_quota on creation/deletion """
def recalculate_count_quota(sender, instance, **kwargs):
signal = kwargs['signal']
if signal == signals.post_save and kwargs.get('created'):
count_quota... | [
"def",
"count_quota_handler_factory",
"(",
"count_quota_field",
")",
":",
"def",
"recalculate_count_quota",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"signal",
"=",
"kwargs",
"[",
"'signal'",
"]",
"if",
"signal",
"==",
"signals",
".",
... | Creates handler that will recalculate count_quota on creation/deletion | [
"Creates",
"handler",
"that",
"will",
"recalculate",
"count_quota",
"on",
"creation",
"/",
"deletion"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/handlers.py#L46-L56 | train |
opennode/waldur-core | waldur_core/quotas/handlers.py | handle_aggregated_quotas | def handle_aggregated_quotas(sender, instance, **kwargs):
""" Call aggregated quotas fields update methods """
quota = instance
# aggregation is not supported for global quotas.
if quota.scope is None:
return
quota_field = quota.get_field()
# usage aggregation should not count another us... | python | def handle_aggregated_quotas(sender, instance, **kwargs):
""" Call aggregated quotas fields update methods """
quota = instance
# aggregation is not supported for global quotas.
if quota.scope is None:
return
quota_field = quota.get_field()
# usage aggregation should not count another us... | [
"def",
"handle_aggregated_quotas",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"quota",
"=",
"instance",
"# aggregation is not supported for global quotas.",
"if",
"quota",
".",
"scope",
"is",
"None",
":",
"return",
"quota_field",
"=",
"quot... | Call aggregated quotas fields update methods | [
"Call",
"aggregated",
"quotas",
"fields",
"update",
"methods"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/handlers.py#L59-L75 | train |
opennode/waldur-core | waldur_core/structure/serializers.py | NestedServiceProjectLinkSerializer.get_settings | def get_settings(self, link):
"""
URL of service settings
"""
return reverse(
'servicesettings-detail', kwargs={'uuid': link.service.settings.uuid}, request=self.context['request']) | python | def get_settings(self, link):
"""
URL of service settings
"""
return reverse(
'servicesettings-detail', kwargs={'uuid': link.service.settings.uuid}, request=self.context['request']) | [
"def",
"get_settings",
"(",
"self",
",",
"link",
")",
":",
"return",
"reverse",
"(",
"'servicesettings-detail'",
",",
"kwargs",
"=",
"{",
"'uuid'",
":",
"link",
".",
"service",
".",
"settings",
".",
"uuid",
"}",
",",
"request",
"=",
"self",
".",
"context... | URL of service settings | [
"URL",
"of",
"service",
"settings"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/serializers.py#L140-L145 | train |
opennode/waldur-core | waldur_core/structure/serializers.py | NestedServiceProjectLinkSerializer.get_url | def get_url(self, link):
"""
URL of service
"""
view_name = SupportedServices.get_detail_view_for_model(link.service)
return reverse(view_name, kwargs={'uuid': link.service.uuid.hex}, request=self.context['request']) | python | def get_url(self, link):
"""
URL of service
"""
view_name = SupportedServices.get_detail_view_for_model(link.service)
return reverse(view_name, kwargs={'uuid': link.service.uuid.hex}, request=self.context['request']) | [
"def",
"get_url",
"(",
"self",
",",
"link",
")",
":",
"view_name",
"=",
"SupportedServices",
".",
"get_detail_view_for_model",
"(",
"link",
".",
"service",
")",
"return",
"reverse",
"(",
"view_name",
",",
"kwargs",
"=",
"{",
"'uuid'",
":",
"link",
".",
"se... | URL of service | [
"URL",
"of",
"service"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/serializers.py#L147-L152 | train |
opennode/waldur-core | waldur_core/structure/serializers.py | NestedServiceProjectLinkSerializer.get_resources_count | def get_resources_count(self, link):
"""
Count total number of all resources connected to link
"""
total = 0
for model in SupportedServices.get_service_resources(link.service):
# Format query path from resource to service project link
query = {model.Permis... | python | def get_resources_count(self, link):
"""
Count total number of all resources connected to link
"""
total = 0
for model in SupportedServices.get_service_resources(link.service):
# Format query path from resource to service project link
query = {model.Permis... | [
"def",
"get_resources_count",
"(",
"self",
",",
"link",
")",
":",
"total",
"=",
"0",
"for",
"model",
"in",
"SupportedServices",
".",
"get_service_resources",
"(",
"link",
".",
"service",
")",
":",
"# Format query path from resource to service project link",
"query",
... | Count total number of all resources connected to link | [
"Count",
"total",
"number",
"of",
"all",
"resources",
"connected",
"to",
"link"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/serializers.py#L166-L175 | train |
OpenDataScienceLab/skdata | skdata/data.py | SkDataSet.drop_columns | def drop_columns(
self, max_na_values: int = None, max_unique_values: int = None
):
"""
When max_na_values was informed, remove columns when the proportion of
total NA values more than max_na_values threshold.
When max_unique_values was informed, remove columns when the prop... | python | def drop_columns(
self, max_na_values: int = None, max_unique_values: int = None
):
"""
When max_na_values was informed, remove columns when the proportion of
total NA values more than max_na_values threshold.
When max_unique_values was informed, remove columns when the prop... | [
"def",
"drop_columns",
"(",
"self",
",",
"max_na_values",
":",
"int",
"=",
"None",
",",
"max_unique_values",
":",
"int",
"=",
"None",
")",
":",
"step",
"=",
"{",
"}",
"if",
"max_na_values",
"is",
"not",
"None",
":",
"step",
"=",
"{",
"'data-set'",
":",... | When max_na_values was informed, remove columns when the proportion of
total NA values more than max_na_values threshold.
When max_unique_values was informed, remove columns when the proportion
of the total of unique values is more than the max_unique_values
threshold, just for columns ... | [
"When",
"max_na_values",
"was",
"informed",
"remove",
"columns",
"when",
"the",
"proportion",
"of",
"total",
"NA",
"values",
"more",
"than",
"max_na_values",
"threshold",
"."
] | 34f06845a944ff4f048b55c7babdd8420f71a6b9 | https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L175-L204 | train |
OpenDataScienceLab/skdata | skdata/data.py | SkDataSet.dropna | def dropna(self):
"""
:return:
"""
step = {
'data-set': self.iid,
'operation': 'drop-na',
'expression': '{"axis": 0}'
}
self.attr_update(attr='steps', value=[step]) | python | def dropna(self):
"""
:return:
"""
step = {
'data-set': self.iid,
'operation': 'drop-na',
'expression': '{"axis": 0}'
}
self.attr_update(attr='steps', value=[step]) | [
"def",
"dropna",
"(",
"self",
")",
":",
"step",
"=",
"{",
"'data-set'",
":",
"self",
".",
"iid",
",",
"'operation'",
":",
"'drop-na'",
",",
"'expression'",
":",
"'{\"axis\": 0}'",
"}",
"self",
".",
"attr_update",
"(",
"attr",
"=",
"'steps'",
",",
"value"... | :return: | [
":",
"return",
":"
] | 34f06845a944ff4f048b55c7babdd8420f71a6b9 | https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L206-L217 | train |
OpenDataScienceLab/skdata | skdata/data.py | SkDataSet.log | def log(self, message: str):
"""
@deprecated
:param message:
:return:
"""
dset_log_id = '_%s_log' % self.iid
if dset_log_id not in self.parent.data.keys():
dset = self.parent.data.create_dataset(
dset_log_id, shape=(1,),
... | python | def log(self, message: str):
"""
@deprecated
:param message:
:return:
"""
dset_log_id = '_%s_log' % self.iid
if dset_log_id not in self.parent.data.keys():
dset = self.parent.data.create_dataset(
dset_log_id, shape=(1,),
... | [
"def",
"log",
"(",
"self",
",",
"message",
":",
"str",
")",
":",
"dset_log_id",
"=",
"'_%s_log'",
"%",
"self",
".",
"iid",
"if",
"dset_log_id",
"not",
"in",
"self",
".",
"parent",
".",
"data",
".",
"keys",
"(",
")",
":",
"dset",
"=",
"self",
".",
... | @deprecated
:param message:
:return: | [
"@deprecated"
] | 34f06845a944ff4f048b55c7babdd8420f71a6b9 | https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L219-L246 | train |
OpenDataScienceLab/skdata | skdata/data.py | SkDataSet.summary | def summary(self, compute=False) -> pd.DataFrame:
"""
:param compute: if should call compute method
:return:
"""
if compute or self.result is None:
self.compute()
return summary(self.result) | python | def summary(self, compute=False) -> pd.DataFrame:
"""
:param compute: if should call compute method
:return:
"""
if compute or self.result is None:
self.compute()
return summary(self.result) | [
"def",
"summary",
"(",
"self",
",",
"compute",
"=",
"False",
")",
"->",
"pd",
".",
"DataFrame",
":",
"if",
"compute",
"or",
"self",
".",
"result",
"is",
"None",
":",
"self",
".",
"compute",
"(",
")",
"return",
"summary",
"(",
"self",
".",
"result",
... | :param compute: if should call compute method
:return: | [
":",
"param",
"compute",
":",
"if",
"should",
"call",
"compute",
"method",
":",
"return",
":"
] | 34f06845a944ff4f048b55c7babdd8420f71a6b9 | https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L248-L255 | train |
stepank/pyws | src/pyws/adapters/_twisted.py | serve | def serve(request, server):
"""
Twisted Web adapter. It has two arguments:
#. ``request`` is a Twisted Web request object,
#. ``server`` is a pyws server object.
First one is the context of an application, function ``serve`` transforms
it into a pyws request object. Then it feeds the request t... | python | def serve(request, server):
"""
Twisted Web adapter. It has two arguments:
#. ``request`` is a Twisted Web request object,
#. ``server`` is a pyws server object.
First one is the context of an application, function ``serve`` transforms
it into a pyws request object. Then it feeds the request t... | [
"def",
"serve",
"(",
"request",
",",
"server",
")",
":",
"request_",
"=",
"Request",
"(",
"'/'",
".",
"join",
"(",
"request",
".",
"postpath",
")",
",",
"request",
".",
"content",
".",
"read",
"(",
")",
"if",
"not",
"request",
".",
"method",
"==",
... | Twisted Web adapter. It has two arguments:
#. ``request`` is a Twisted Web request object,
#. ``server`` is a pyws server object.
First one is the context of an application, function ``serve`` transforms
it into a pyws request object. Then it feeds the request to the server,
gets the response, set... | [
"Twisted",
"Web",
"adapter",
".",
"It",
"has",
"two",
"arguments",
":"
] | ff39133aabeb56bbb08d66286ac0cc8731eda7dd | https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/adapters/_twisted.py#L4-L25 | train |
opennode/waldur-core | waldur_core/structure/utils.py | get_sorted_dependencies | def get_sorted_dependencies(service_model):
"""
Returns list of application models in topological order.
It is used in order to correctly delete dependent resources.
"""
app_models = list(service_model._meta.app_config.get_models())
dependencies = {model: set() for model in app_models}
relat... | python | def get_sorted_dependencies(service_model):
"""
Returns list of application models in topological order.
It is used in order to correctly delete dependent resources.
"""
app_models = list(service_model._meta.app_config.get_models())
dependencies = {model: set() for model in app_models}
relat... | [
"def",
"get_sorted_dependencies",
"(",
"service_model",
")",
":",
"app_models",
"=",
"list",
"(",
"service_model",
".",
"_meta",
".",
"app_config",
".",
"get_models",
"(",
")",
")",
"dependencies",
"=",
"{",
"model",
":",
"set",
"(",
")",
"for",
"model",
"... | Returns list of application models in topological order.
It is used in order to correctly delete dependent resources. | [
"Returns",
"list",
"of",
"application",
"models",
"in",
"topological",
"order",
".",
"It",
"is",
"used",
"in",
"order",
"to",
"correctly",
"delete",
"dependent",
"resources",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L38-L53 | train |
opennode/waldur-core | waldur_core/structure/utils.py | update_pulled_fields | def update_pulled_fields(instance, imported_instance, fields):
"""
Update instance fields based on imported from backend data.
Save changes to DB only one or more fields were changed.
"""
modified = False
for field in fields:
pulled_value = getattr(imported_instance, field)
curre... | python | def update_pulled_fields(instance, imported_instance, fields):
"""
Update instance fields based on imported from backend data.
Save changes to DB only one or more fields were changed.
"""
modified = False
for field in fields:
pulled_value = getattr(imported_instance, field)
curre... | [
"def",
"update_pulled_fields",
"(",
"instance",
",",
"imported_instance",
",",
"fields",
")",
":",
"modified",
"=",
"False",
"for",
"field",
"in",
"fields",
":",
"pulled_value",
"=",
"getattr",
"(",
"imported_instance",
",",
"field",
")",
"current_value",
"=",
... | Update instance fields based on imported from backend data.
Save changes to DB only one or more fields were changed. | [
"Update",
"instance",
"fields",
"based",
"on",
"imported",
"from",
"backend",
"data",
".",
"Save",
"changes",
"to",
"DB",
"only",
"one",
"or",
"more",
"fields",
"were",
"changed",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L91-L110 | train |
opennode/waldur-core | waldur_core/structure/utils.py | handle_resource_not_found | def handle_resource_not_found(resource):
"""
Set resource state to ERRED and append/create "not found" error message.
"""
resource.set_erred()
resource.runtime_state = ''
message = 'Does not exist at backend.'
if message not in resource.error_message:
if not resource.error_message:
... | python | def handle_resource_not_found(resource):
"""
Set resource state to ERRED and append/create "not found" error message.
"""
resource.set_erred()
resource.runtime_state = ''
message = 'Does not exist at backend.'
if message not in resource.error_message:
if not resource.error_message:
... | [
"def",
"handle_resource_not_found",
"(",
"resource",
")",
":",
"resource",
".",
"set_erred",
"(",
")",
"resource",
".",
"runtime_state",
"=",
"''",
"message",
"=",
"'Does not exist at backend.'",
"if",
"message",
"not",
"in",
"resource",
".",
"error_message",
":",... | Set resource state to ERRED and append/create "not found" error message. | [
"Set",
"resource",
"state",
"to",
"ERRED",
"and",
"append",
"/",
"create",
"not",
"found",
"error",
"message",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L113-L127 | train |
opennode/waldur-core | waldur_core/structure/utils.py | handle_resource_update_success | def handle_resource_update_success(resource):
"""
Recover resource if its state is ERRED and clear error message.
"""
update_fields = []
if resource.state == resource.States.ERRED:
resource.recover()
update_fields.append('state')
if resource.state in (resource.States.UPDATING, r... | python | def handle_resource_update_success(resource):
"""
Recover resource if its state is ERRED and clear error message.
"""
update_fields = []
if resource.state == resource.States.ERRED:
resource.recover()
update_fields.append('state')
if resource.state in (resource.States.UPDATING, r... | [
"def",
"handle_resource_update_success",
"(",
"resource",
")",
":",
"update_fields",
"=",
"[",
"]",
"if",
"resource",
".",
"state",
"==",
"resource",
".",
"States",
".",
"ERRED",
":",
"resource",
".",
"recover",
"(",
")",
"update_fields",
".",
"append",
"(",... | Recover resource if its state is ERRED and clear error message. | [
"Recover",
"resource",
"if",
"its",
"state",
"is",
"ERRED",
"and",
"clear",
"error",
"message",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L130-L150 | train |
nuagenetworks/bambou | bambou/nurest_request.py | NURESTRequest.set_header | def set_header(self, header, value):
""" Set header value """
# requests>=2.11 only accepts `str` or `bytes` header values
# raising an exception here, instead of leaving it to `requests` makes
# it easy to know where we passed a wrong header type in the code.
if not isinstance(v... | python | def set_header(self, header, value):
""" Set header value """
# requests>=2.11 only accepts `str` or `bytes` header values
# raising an exception here, instead of leaving it to `requests` makes
# it easy to know where we passed a wrong header type in the code.
if not isinstance(v... | [
"def",
"set_header",
"(",
"self",
",",
"header",
",",
"value",
")",
":",
"# requests>=2.11 only accepts `str` or `bytes` header values",
"# raising an exception here, instead of leaving it to `requests` makes",
"# it easy to know where we passed a wrong header type in the code.",
"if",
"... | Set header value | [
"Set",
"header",
"value"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_request.py#L120-L127 | train |
opennode/waldur-core | waldur_core/structure/tasks.py | BackgroundPullTask.set_instance_erred | def set_instance_erred(self, instance, error_message):
""" Mark instance as erred and save error message """
instance.set_erred()
instance.error_message = error_message
instance.save(update_fields=['state', 'error_message']) | python | def set_instance_erred(self, instance, error_message):
""" Mark instance as erred and save error message """
instance.set_erred()
instance.error_message = error_message
instance.save(update_fields=['state', 'error_message']) | [
"def",
"set_instance_erred",
"(",
"self",
",",
"instance",
",",
"error_message",
")",
":",
"instance",
".",
"set_erred",
"(",
")",
"instance",
".",
"error_message",
"=",
"error_message",
"instance",
".",
"save",
"(",
"update_fields",
"=",
"[",
"'state'",
",",
... | Mark instance as erred and save error message | [
"Mark",
"instance",
"as",
"erred",
"and",
"save",
"error",
"message"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/tasks.py#L118-L122 | train |
noumar/iso639 | examples/logic.py | map_language | def map_language(language, dash3=True):
""" Use ISO 639-3 ?? """
if dash3:
from iso639 import languages
else:
from pycountry import languages
if '_' in language:
language = language.split('_')[0]
if len(language) == 2:
try: return languages.get(alpha2=language.lower(... | python | def map_language(language, dash3=True):
""" Use ISO 639-3 ?? """
if dash3:
from iso639 import languages
else:
from pycountry import languages
if '_' in language:
language = language.split('_')[0]
if len(language) == 2:
try: return languages.get(alpha2=language.lower(... | [
"def",
"map_language",
"(",
"language",
",",
"dash3",
"=",
"True",
")",
":",
"if",
"dash3",
":",
"from",
"iso639",
"import",
"languages",
"else",
":",
"from",
"pycountry",
"import",
"languages",
"if",
"'_'",
"in",
"language",
":",
"language",
"=",
"languag... | Use ISO 639-3 ?? | [
"Use",
"ISO",
"639",
"-",
"3",
"??"
] | 2175cf04b8b8cec79d99a6c4ad31295d67c22cd6 | https://github.com/noumar/iso639/blob/2175cf04b8b8cec79d99a6c4ad31295d67c22cd6/examples/logic.py#L11-L39 | train |
opennode/waldur-core | waldur_core/structure/executors.py | BaseCleanupExecutor.get_task_signature | def get_task_signature(cls, instance, serialized_instance, **kwargs):
"""
Delete each resource using specific executor.
Convert executors to task and combine all deletion task into single sequential task.
"""
cleanup_tasks = [
ProjectResourceCleanupTask().si(
... | python | def get_task_signature(cls, instance, serialized_instance, **kwargs):
"""
Delete each resource using specific executor.
Convert executors to task and combine all deletion task into single sequential task.
"""
cleanup_tasks = [
ProjectResourceCleanupTask().si(
... | [
"def",
"get_task_signature",
"(",
"cls",
",",
"instance",
",",
"serialized_instance",
",",
"*",
"*",
"kwargs",
")",
":",
"cleanup_tasks",
"=",
"[",
"ProjectResourceCleanupTask",
"(",
")",
".",
"si",
"(",
"core_utils",
".",
"serialize_class",
"(",
"executor_cls",... | Delete each resource using specific executor.
Convert executors to task and combine all deletion task into single sequential task. | [
"Delete",
"each",
"resource",
"using",
"specific",
"executor",
".",
"Convert",
"executors",
"to",
"task",
"and",
"combine",
"all",
"deletion",
"task",
"into",
"single",
"sequential",
"task",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/executors.py#L99-L116 | train |
opennode/waldur-core | waldur_core/core/utils.py | sort_dict | def sort_dict(unsorted_dict):
"""
Return a OrderedDict ordered by key names from the :unsorted_dict:
"""
sorted_dict = OrderedDict()
# sort items before inserting them into a dict
for key, value in sorted(unsorted_dict.items(), key=itemgetter(0)):
sorted_dict[key] = value
return sort... | python | def sort_dict(unsorted_dict):
"""
Return a OrderedDict ordered by key names from the :unsorted_dict:
"""
sorted_dict = OrderedDict()
# sort items before inserting them into a dict
for key, value in sorted(unsorted_dict.items(), key=itemgetter(0)):
sorted_dict[key] = value
return sort... | [
"def",
"sort_dict",
"(",
"unsorted_dict",
")",
":",
"sorted_dict",
"=",
"OrderedDict",
"(",
")",
"# sort items before inserting them into a dict",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"unsorted_dict",
".",
"items",
"(",
")",
",",
"key",
"=",
"itemget... | Return a OrderedDict ordered by key names from the :unsorted_dict: | [
"Return",
"a",
"OrderedDict",
"ordered",
"by",
"key",
"names",
"from",
"the",
":",
"unsorted_dict",
":"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L25-L33 | train |
opennode/waldur-core | waldur_core/core/utils.py | format_time_and_value_to_segment_list | def format_time_and_value_to_segment_list(time_and_value_list, segments_count, start_timestamp,
end_timestamp, average=False):
"""
Format time_and_value_list to time segments
Parameters
^^^^^^^^^^
time_and_value_list: list of tuples
Have to be sorte... | python | def format_time_and_value_to_segment_list(time_and_value_list, segments_count, start_timestamp,
end_timestamp, average=False):
"""
Format time_and_value_list to time segments
Parameters
^^^^^^^^^^
time_and_value_list: list of tuples
Have to be sorte... | [
"def",
"format_time_and_value_to_segment_list",
"(",
"time_and_value_list",
",",
"segments_count",
",",
"start_timestamp",
",",
"end_timestamp",
",",
"average",
"=",
"False",
")",
":",
"segment_list",
"=",
"[",
"]",
"time_step",
"=",
"(",
"end_timestamp",
"-",
"star... | Format time_and_value_list to time segments
Parameters
^^^^^^^^^^
time_and_value_list: list of tuples
Have to be sorted by time
Example: [(time, value), (time, value) ...]
segments_count: integer
How many segments will be in result
Returns
^^^^^^^
List of dictionarie... | [
"Format",
"time_and_value_list",
"to",
"time",
"segments"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L36-L71 | train |
opennode/waldur-core | waldur_core/core/utils.py | serialize_instance | def serialize_instance(instance):
""" Serialize Django model instance """
model_name = force_text(instance._meta)
return '{}:{}'.format(model_name, instance.pk) | python | def serialize_instance(instance):
""" Serialize Django model instance """
model_name = force_text(instance._meta)
return '{}:{}'.format(model_name, instance.pk) | [
"def",
"serialize_instance",
"(",
"instance",
")",
":",
"model_name",
"=",
"force_text",
"(",
"instance",
".",
"_meta",
")",
"return",
"'{}:{}'",
".",
"format",
"(",
"model_name",
",",
"instance",
".",
"pk",
")"
] | Serialize Django model instance | [
"Serialize",
"Django",
"model",
"instance"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L121-L124 | train |
opennode/waldur-core | waldur_core/core/utils.py | deserialize_instance | def deserialize_instance(serialized_instance):
""" Deserialize Django model instance """
model_name, pk = serialized_instance.split(':')
model = apps.get_model(model_name)
return model._default_manager.get(pk=pk) | python | def deserialize_instance(serialized_instance):
""" Deserialize Django model instance """
model_name, pk = serialized_instance.split(':')
model = apps.get_model(model_name)
return model._default_manager.get(pk=pk) | [
"def",
"deserialize_instance",
"(",
"serialized_instance",
")",
":",
"model_name",
",",
"pk",
"=",
"serialized_instance",
".",
"split",
"(",
"':'",
")",
"model",
"=",
"apps",
".",
"get_model",
"(",
"model_name",
")",
"return",
"model",
".",
"_default_manager",
... | Deserialize Django model instance | [
"Deserialize",
"Django",
"model",
"instance"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L127-L131 | train |
opennode/waldur-core | waldur_core/core/utils.py | deserialize_class | def deserialize_class(serilalized_cls):
""" Deserialize Python class """
module_name, cls_name = serilalized_cls.split(':')
module = importlib.import_module(module_name)
return getattr(module, cls_name) | python | def deserialize_class(serilalized_cls):
""" Deserialize Python class """
module_name, cls_name = serilalized_cls.split(':')
module = importlib.import_module(module_name)
return getattr(module, cls_name) | [
"def",
"deserialize_class",
"(",
"serilalized_cls",
")",
":",
"module_name",
",",
"cls_name",
"=",
"serilalized_cls",
".",
"split",
"(",
"':'",
")",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"return",
"getattr",
"(",
"module",
... | Deserialize Python class | [
"Deserialize",
"Python",
"class"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L139-L143 | train |
opennode/waldur-core | waldur_core/core/utils.py | instance_from_url | def instance_from_url(url, user=None):
""" Restore instance from URL """
# XXX: This circular dependency will be removed then filter_queryset_for_user
# will be moved to model manager method
from waldur_core.structure.managers import filter_queryset_for_user
url = clear_url(url)
match = resolve... | python | def instance_from_url(url, user=None):
""" Restore instance from URL """
# XXX: This circular dependency will be removed then filter_queryset_for_user
# will be moved to model manager method
from waldur_core.structure.managers import filter_queryset_for_user
url = clear_url(url)
match = resolve... | [
"def",
"instance_from_url",
"(",
"url",
",",
"user",
"=",
"None",
")",
":",
"# XXX: This circular dependency will be removed then filter_queryset_for_user",
"# will be moved to model manager method",
"from",
"waldur_core",
".",
"structure",
".",
"managers",
"import",
"filter_qu... | Restore instance from URL | [
"Restore",
"instance",
"from",
"URL"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L161-L173 | train |
zeromake/aiosqlite3 | aiosqlite3/sa/transaction.py | Transaction.close | def close(self):
"""
Close this transaction.
If this transaction is the base transaction in a begin/commit
nesting, the transaction will rollback(). Otherwise, the
method returns.
This is used to cancel a Transaction without affecting the scope of
an enclosing ... | python | def close(self):
"""
Close this transaction.
If this transaction is the base transaction in a begin/commit
nesting, the transaction will rollback(). Otherwise, the
method returns.
This is used to cancel a Transaction without affecting the scope of
an enclosing ... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_connection",
"or",
"not",
"self",
".",
"_parent",
":",
"return",
"if",
"not",
"self",
".",
"_parent",
".",
"_is_active",
":",
"# pragma: no cover",
"self",
".",
"_connection",
"=",
"None"... | Close this transaction.
If this transaction is the base transaction in a begin/commit
nesting, the transaction will rollback(). Otherwise, the
method returns.
This is used to cancel a Transaction without affecting the scope of
an enclosing transaction. | [
"Close",
"this",
"transaction",
"."
] | 1a74a062507e2df8f833a70885e69dca0ab3e7e7 | https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sa/transaction.py#L50-L73 | train |
zeromake/aiosqlite3 | aiosqlite3/sa/transaction.py | Transaction.commit | def commit(self):
"""
Commit this transaction.
"""
if not self._parent._is_active:
raise exc.InvalidRequestError("This transaction is inactive")
yield from self._do_commit()
self._is_active = False | python | def commit(self):
"""
Commit this transaction.
"""
if not self._parent._is_active:
raise exc.InvalidRequestError("This transaction is inactive")
yield from self._do_commit()
self._is_active = False | [
"def",
"commit",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_parent",
".",
"_is_active",
":",
"raise",
"exc",
".",
"InvalidRequestError",
"(",
"\"This transaction is inactive\"",
")",
"yield",
"from",
"self",
".",
"_do_commit",
"(",
")",
"self",
".",
... | Commit this transaction. | [
"Commit",
"this",
"transaction",
"."
] | 1a74a062507e2df8f833a70885e69dca0ab3e7e7 | https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sa/transaction.py#L90-L98 | train |
opennode/waldur-core | waldur_core/server/admin/dashboard.py | CustomIndexDashboard._get_app_config | def _get_app_config(self, app_name):
"""
Returns an app config for the given name, not by label.
"""
matches = [app_config for app_config in apps.get_app_configs()
if app_config.name == app_name]
if not matches:
return
return matches[0] | python | def _get_app_config(self, app_name):
"""
Returns an app config for the given name, not by label.
"""
matches = [app_config for app_config in apps.get_app_configs()
if app_config.name == app_name]
if not matches:
return
return matches[0] | [
"def",
"_get_app_config",
"(",
"self",
",",
"app_name",
")",
":",
"matches",
"=",
"[",
"app_config",
"for",
"app_config",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
"if",
"app_config",
".",
"name",
"==",
"app_name",
"]",
"if",
"not",
"matches",
":",
... | Returns an app config for the given name, not by label. | [
"Returns",
"an",
"app",
"config",
"for",
"the",
"given",
"name",
"not",
"by",
"label",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L56-L65 | train |
opennode/waldur-core | waldur_core/server/admin/dashboard.py | CustomIndexDashboard._get_app_version | def _get_app_version(self, app_config):
"""
Some plugins ship multiple applications and extensions.
However all of them have the same version, because they are released together.
That's why only-top level module is used to fetch version information.
"""
base_name = app_c... | python | def _get_app_version(self, app_config):
"""
Some plugins ship multiple applications and extensions.
However all of them have the same version, because they are released together.
That's why only-top level module is used to fetch version information.
"""
base_name = app_c... | [
"def",
"_get_app_version",
"(",
"self",
",",
"app_config",
")",
":",
"base_name",
"=",
"app_config",
".",
"__module__",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"module",
"=",
"__import__",
"(",
"base_name",
")",
"return",
"getattr",
"(",
"module",
... | Some plugins ship multiple applications and extensions.
However all of them have the same version, because they are released together.
That's why only-top level module is used to fetch version information. | [
"Some",
"plugins",
"ship",
"multiple",
"applications",
"and",
"extensions",
".",
"However",
"all",
"of",
"them",
"have",
"the",
"same",
"version",
"because",
"they",
"are",
"released",
"together",
".",
"That",
"s",
"why",
"only",
"-",
"top",
"level",
"module... | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L77-L86 | train |
opennode/waldur-core | waldur_core/server/admin/dashboard.py | CustomIndexDashboard._get_quick_access_info | def _get_quick_access_info(self):
"""
Returns a list of ListLink items to be added to Quick Access tab.
Contains:
- links to Organizations, Projects and Users;
- a link to shared service settings;
- custom configured links in admin/settings FLUENT_DASHBOARD_QUICK_ACCESS_L... | python | def _get_quick_access_info(self):
"""
Returns a list of ListLink items to be added to Quick Access tab.
Contains:
- links to Organizations, Projects and Users;
- a link to shared service settings;
- custom configured links in admin/settings FLUENT_DASHBOARD_QUICK_ACCESS_L... | [
"def",
"_get_quick_access_info",
"(",
"self",
")",
":",
"quick_access_links",
"=",
"[",
"]",
"# add custom links",
"quick_access_links",
".",
"extend",
"(",
"settings",
".",
"FLUENT_DASHBOARD_QUICK_ACCESS_LINKS",
")",
"for",
"model",
"in",
"(",
"structure_models",
"."... | Returns a list of ListLink items to be added to Quick Access tab.
Contains:
- links to Organizations, Projects and Users;
- a link to shared service settings;
- custom configured links in admin/settings FLUENT_DASHBOARD_QUICK_ACCESS_LINKS attribute; | [
"Returns",
"a",
"list",
"of",
"ListLink",
"items",
"to",
"be",
"added",
"to",
"Quick",
"Access",
"tab",
".",
"Contains",
":",
"-",
"links",
"to",
"Organizations",
"Projects",
"and",
"Users",
";",
"-",
"a",
"link",
"to",
"shared",
"service",
"settings",
"... | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L88-L107 | train |
opennode/waldur-core | waldur_core/server/admin/dashboard.py | CustomIndexDashboard._get_erred_shared_settings_module | def _get_erred_shared_settings_module(self):
"""
Returns a LinkList based module which contains link to shared service setting instances in ERRED state.
"""
result_module = modules.LinkList(title=_('Shared provider settings in erred state'))
result_module.template = 'admin/dashbo... | python | def _get_erred_shared_settings_module(self):
"""
Returns a LinkList based module which contains link to shared service setting instances in ERRED state.
"""
result_module = modules.LinkList(title=_('Shared provider settings in erred state'))
result_module.template = 'admin/dashbo... | [
"def",
"_get_erred_shared_settings_module",
"(",
"self",
")",
":",
"result_module",
"=",
"modules",
".",
"LinkList",
"(",
"title",
"=",
"_",
"(",
"'Shared provider settings in erred state'",
")",
")",
"result_module",
".",
"template",
"=",
"'admin/dashboard/erred_link_l... | Returns a LinkList based module which contains link to shared service setting instances in ERRED state. | [
"Returns",
"a",
"LinkList",
"based",
"module",
"which",
"contains",
"link",
"to",
"shared",
"service",
"setting",
"instances",
"in",
"ERRED",
"state",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L135-L155 | train |
opennode/waldur-core | waldur_core/server/admin/dashboard.py | CustomIndexDashboard._get_erred_resources_module | def _get_erred_resources_module(self):
"""
Returns a list of links to resources which are in ERRED state and linked to a shared service settings.
"""
result_module = modules.LinkList(title=_('Resources in erred state'))
erred_state = structure_models.NewResource.States.ERRED
... | python | def _get_erred_resources_module(self):
"""
Returns a list of links to resources which are in ERRED state and linked to a shared service settings.
"""
result_module = modules.LinkList(title=_('Resources in erred state'))
erred_state = structure_models.NewResource.States.ERRED
... | [
"def",
"_get_erred_resources_module",
"(",
"self",
")",
":",
"result_module",
"=",
"modules",
".",
"LinkList",
"(",
"title",
"=",
"_",
"(",
"'Resources in erred state'",
")",
")",
"erred_state",
"=",
"structure_models",
".",
"NewResource",
".",
"States",
".",
"E... | Returns a list of links to resources which are in ERRED state and linked to a shared service settings. | [
"Returns",
"a",
"list",
"of",
"links",
"to",
"resources",
"which",
"are",
"in",
"ERRED",
"state",
"and",
"linked",
"to",
"a",
"shared",
"service",
"settings",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L157-L181 | train |
stepank/pyws | src/pyws/adapters/_django.py | serve | def serve(request, tail, server):
"""
Django adapter. It has three arguments:
#. ``request`` is a Django request object,
#. ``tail`` is everything that's left from an URL, which adapter is
attached to,
#. ``server`` is a pyws server object.
First two are the context of an application, f... | python | def serve(request, tail, server):
"""
Django adapter. It has three arguments:
#. ``request`` is a Django request object,
#. ``tail`` is everything that's left from an URL, which adapter is
attached to,
#. ``server`` is a pyws server object.
First two are the context of an application, f... | [
"def",
"serve",
"(",
"request",
",",
"tail",
",",
"server",
")",
":",
"if",
"request",
".",
"GET",
":",
"body",
"=",
"''",
"else",
":",
"try",
":",
"body",
"=",
"request",
".",
"body",
"except",
"AttributeError",
":",
"body",
"=",
"request",
".",
"... | Django adapter. It has three arguments:
#. ``request`` is a Django request object,
#. ``tail`` is everything that's left from an URL, which adapter is
attached to,
#. ``server`` is a pyws server object.
First two are the context of an application, function ``serve`` transforms
them into a p... | [
"Django",
"adapter",
".",
"It",
"has",
"three",
"arguments",
":"
] | ff39133aabeb56bbb08d66286ac0cc8731eda7dd | https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/adapters/_django.py#L10-L44 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher.index | def index(self, nurest_object):
""" Get index of the given item
Args:
nurest_object (bambou.NURESTObject): the NURESTObject object to verify
Returns:
Returns the position of the object.
Raises:
Raise a ValueError exception if ... | python | def index(self, nurest_object):
""" Get index of the given item
Args:
nurest_object (bambou.NURESTObject): the NURESTObject object to verify
Returns:
Returns the position of the object.
Raises:
Raise a ValueError exception if ... | [
"def",
"index",
"(",
"self",
",",
"nurest_object",
")",
":",
"for",
"index",
",",
"obj",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"obj",
".",
"equals",
"(",
"nurest_object",
")",
":",
"return",
"index",
"raise",
"ValueError",
"(",
"\"%s is not in... | Get index of the given item
Args:
nurest_object (bambou.NURESTObject): the NURESTObject object to verify
Returns:
Returns the position of the object.
Raises:
Raise a ValueError exception if object is not present | [
"Get",
"index",
"of",
"the",
"given",
"item",
"Args",
":",
"nurest_object",
"(",
"bambou",
".",
"NURESTObject",
")",
":",
"the",
"NURESTObject",
"object",
"to",
"verify"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L78-L93 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher.fetcher_with_object | def fetcher_with_object(cls, parent_object, relationship="child"):
""" Register the fetcher for a served object.
This method will fill the fetcher with `managed_class` instances
Args:
parent_object: the instance of the parent object to serve
Returns:
... | python | def fetcher_with_object(cls, parent_object, relationship="child"):
""" Register the fetcher for a served object.
This method will fill the fetcher with `managed_class` instances
Args:
parent_object: the instance of the parent object to serve
Returns:
... | [
"def",
"fetcher_with_object",
"(",
"cls",
",",
"parent_object",
",",
"relationship",
"=",
"\"child\"",
")",
":",
"fetcher",
"=",
"cls",
"(",
")",
"fetcher",
".",
"parent_object",
"=",
"parent_object",
"fetcher",
".",
"relationship",
"=",
"relationship",
"rest_na... | Register the fetcher for a served object.
This method will fill the fetcher with `managed_class` instances
Args:
parent_object: the instance of the parent object to serve
Returns:
It returns the fetcher instance. | [
"Register",
"the",
"fetcher",
"for",
"a",
"served",
"object",
"."
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L183-L202 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher._prepare_headers | def _prepare_headers(self, request, filter=None, order_by=None, group_by=[], page=None, page_size=None):
""" Prepare headers for the given request
Args:
request: the NURESTRequest to send
filter: string
order_by: string
group_by: list ... | python | def _prepare_headers(self, request, filter=None, order_by=None, group_by=[], page=None, page_size=None):
""" Prepare headers for the given request
Args:
request: the NURESTRequest to send
filter: string
order_by: string
group_by: list ... | [
"def",
"_prepare_headers",
"(",
"self",
",",
"request",
",",
"filter",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"group_by",
"=",
"[",
"]",
",",
"page",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"if",
"filter",
":",
"request",
".",
... | Prepare headers for the given request
Args:
request: the NURESTRequest to send
filter: string
order_by: string
group_by: list of names
page: int
page_size: int | [
"Prepare",
"headers",
"for",
"the",
"given",
"request"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L222-L249 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher.fetch | def fetch(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
""" Fetch objects according to given filter and page.
Note:
This method fetches all managed class objects and store them
... | python | def fetch(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
""" Fetch objects according to given filter and page.
Note:
This method fetches all managed class objects and store them
... | [
"def",
"fetch",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"group_by",
"=",
"[",
"]",
",",
"page",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"query_parameters",
"=",
"None",
",",
"commit",
"=",
"True",
",",
"... | Fetch objects according to given filter and page.
Note:
This method fetches all managed class objects and store them
in local_name of the served object. which means that the parent
object will hold them in a list. You can prevent this behavior
... | [
"Fetch",
"objects",
"according",
"to",
"given",
"filter",
"and",
"page",
"."
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L256-L291 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher._did_fetch | def _did_fetch(self, connection):
""" Fetching objects has been done """
self.current_connection = connection
response = connection.response
should_commit = 'commit' not in connection.user_info or connection.user_info['commit']
if connection.response.status_code >= 400 and Bamb... | python | def _did_fetch(self, connection):
""" Fetching objects has been done """
self.current_connection = connection
response = connection.response
should_commit = 'commit' not in connection.user_info or connection.user_info['commit']
if connection.response.status_code >= 400 and Bamb... | [
"def",
"_did_fetch",
"(",
"self",
",",
"connection",
")",
":",
"self",
".",
"current_connection",
"=",
"connection",
"response",
"=",
"connection",
".",
"response",
"should_commit",
"=",
"'commit'",
"not",
"in",
"connection",
".",
"user_info",
"or",
"connection"... | Fetching objects has been done | [
"Fetching",
"objects",
"has",
"been",
"done"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L293-L351 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher.get | def get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
""" Fetch object and directly return them
Note:
`get` won't put the fetched objects in the parent's children list.
You c... | python | def get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
""" Fetch object and directly return them
Note:
`get` won't put the fetched objects in the parent's children list.
You c... | [
"def",
"get",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"group_by",
"=",
"[",
"]",
",",
"page",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"query_parameters",
"=",
"None",
",",
"commit",
"=",
"True",
",",
"as... | Fetch object and directly return them
Note:
`get` won't put the fetched objects in the parent's children list.
You cannot override this behavior. If you want to commit them in the parent
you can use :method:vsdk.NURESTFetcher.fetch or manually add the list wi... | [
"Fetch",
"object",
"and",
"directly",
"return",
"them"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L353-L378 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher.get_first | def get_first(self, filter=None, order_by=None, group_by=[], query_parameters=None, commit=False, async=False, callback=None):
""" Fetch object and directly return the first one
Note:
`get_first` won't put the fetched object in the parent's children list.
You cannot ... | python | def get_first(self, filter=None, order_by=None, group_by=[], query_parameters=None, commit=False, async=False, callback=None):
""" Fetch object and directly return the first one
Note:
`get_first` won't put the fetched object in the parent's children list.
You cannot ... | [
"def",
"get_first",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"group_by",
"=",
"[",
"]",
",",
"query_parameters",
"=",
"None",
",",
"commit",
"=",
"False",
",",
"async",
"=",
"False",
",",
"callback",
"=",
"None",
")... | Fetch object and directly return the first one
Note:
`get_first` won't put the fetched object in the parent's children list.
You cannot override this behavior. If you want to commit it in the parent
you can use :method:vsdk.NURESTFetcher.fetch or manually add... | [
"Fetch",
"object",
"and",
"directly",
"return",
"the",
"first",
"one"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L380-L406 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher.count | def count(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, async=False, callback=None):
""" Get the total count of objects that can be fetched according to filter
This method can be asynchronous and trigger the callback method
when result ... | python | def count(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, async=False, callback=None):
""" Get the total count of objects that can be fetched according to filter
This method can be asynchronous and trigger the callback method
when result ... | [
"def",
"count",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"group_by",
"=",
"[",
"]",
",",
"page",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"query_parameters",
"=",
"None",
",",
"async",
"=",
"False",
",",
"... | Get the total count of objects that can be fetched according to filter
This method can be asynchronous and trigger the callback method
when result is ready.
Args:
filter (string): string that represents a predicate fitler (eg. name == 'x')
order_by (... | [
"Get",
"the",
"total",
"count",
"of",
"objects",
"that",
"can",
"be",
"fetched",
"according",
"to",
"filter"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L408-L436 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher.get_count | def get_count(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None):
""" Get the total count of objects that can be fetched according to filter
Args:
filter (string): string that represents a predicate fitler (eg. name == 'x')
... | python | def get_count(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None):
""" Get the total count of objects that can be fetched according to filter
Args:
filter (string): string that represents a predicate fitler (eg. name == 'x')
... | [
"def",
"get_count",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"group_by",
"=",
"[",
"]",
",",
"page",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"query_parameters",
"=",
"None",
")",
":",
"return",
"self",
".",... | Get the total count of objects that can be fetched according to filter
Args:
filter (string): string that represents a predicate fitler (eg. name == 'x')
order_by (string): string that represents an order by clause
group_by (string): list of names for groupin... | [
"Get",
"the",
"total",
"count",
"of",
"objects",
"that",
"can",
"be",
"fetched",
"according",
"to",
"filter"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L438-L452 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher._did_count | def _did_count(self, connection):
""" Called when count if finished """
self.current_connection = connection
response = connection.response
count = 0
callback = None
if 'X-Nuage-Count' in response.headers:
count = int(response.headers['X-Nuage-Count'])
... | python | def _did_count(self, connection):
""" Called when count if finished """
self.current_connection = connection
response = connection.response
count = 0
callback = None
if 'X-Nuage-Count' in response.headers:
count = int(response.headers['X-Nuage-Count'])
... | [
"def",
"_did_count",
"(",
"self",
",",
"connection",
")",
":",
"self",
".",
"current_connection",
"=",
"connection",
"response",
"=",
"connection",
".",
"response",
"count",
"=",
"0",
"callback",
"=",
"None",
"if",
"'X-Nuage-Count'",
"in",
"response",
".",
"... | Called when count if finished | [
"Called",
"when",
"count",
"if",
"finished"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L454-L479 | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | NURESTFetcher._send_content | def _send_content(self, content, connection):
""" Send a content array from the connection """
if connection:
if connection.async:
callback = connection.callbacks['remote']
if callback:
callback(self, self.parent_object, content)
... | python | def _send_content(self, content, connection):
""" Send a content array from the connection """
if connection:
if connection.async:
callback = connection.callbacks['remote']
if callback:
callback(self, self.parent_object, content)
... | [
"def",
"_send_content",
"(",
"self",
",",
"content",
",",
"connection",
")",
":",
"if",
"connection",
":",
"if",
"connection",
".",
"async",
":",
"callback",
"=",
"connection",
".",
"callbacks",
"[",
"'remote'",
"]",
"if",
"callback",
":",
"callback",
"(",... | Send a content array from the connection | [
"Send",
"a",
"content",
"array",
"from",
"the",
"connection"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L481-L495 | train |
opennode/waldur-core | waldur_core/cost_tracking/models.py | ConsumptionDetails.update_configuration | def update_configuration(self, new_configuration):
""" Save how much consumables were used and update current configuration.
Return True if configuration changed.
"""
if new_configuration == self.configuration:
return False
now = timezone.now()
if now.mon... | python | def update_configuration(self, new_configuration):
""" Save how much consumables were used and update current configuration.
Return True if configuration changed.
"""
if new_configuration == self.configuration:
return False
now = timezone.now()
if now.mon... | [
"def",
"update_configuration",
"(",
"self",
",",
"new_configuration",
")",
":",
"if",
"new_configuration",
"==",
"self",
".",
"configuration",
":",
"return",
"False",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"if",
"now",
".",
"month",
"!=",
"self",
".... | Save how much consumables were used and update current configuration.
Return True if configuration changed. | [
"Save",
"how",
"much",
"consumables",
"were",
"used",
"and",
"update",
"current",
"configuration",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/models.py#L288-L306 | train |
opennode/waldur-core | waldur_core/cost_tracking/models.py | ConsumptionDetails.consumed_in_month | def consumed_in_month(self):
""" How many resources were (or will be) consumed until end of the month """
month_end = core_utils.month_end(datetime.date(self.price_estimate.year, self.price_estimate.month, 1))
return self._get_consumed(month_end) | python | def consumed_in_month(self):
""" How many resources were (or will be) consumed until end of the month """
month_end = core_utils.month_end(datetime.date(self.price_estimate.year, self.price_estimate.month, 1))
return self._get_consumed(month_end) | [
"def",
"consumed_in_month",
"(",
"self",
")",
":",
"month_end",
"=",
"core_utils",
".",
"month_end",
"(",
"datetime",
".",
"date",
"(",
"self",
".",
"price_estimate",
".",
"year",
",",
"self",
".",
"price_estimate",
".",
"month",
",",
"1",
")",
")",
"ret... | How many resources were (or will be) consumed until end of the month | [
"How",
"many",
"resources",
"were",
"(",
"or",
"will",
"be",
")",
"consumed",
"until",
"end",
"of",
"the",
"month"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/models.py#L309-L312 | train |
opennode/waldur-core | waldur_core/cost_tracking/models.py | ConsumptionDetails._get_consumed | def _get_consumed(self, time):
""" How many consumables were (or will be) used by resource until given time. """
minutes_from_last_update = self._get_minutes_from_last_update(time)
if minutes_from_last_update < 0:
raise ConsumptionDetailCalculateError('Cannot calculate consumption if... | python | def _get_consumed(self, time):
""" How many consumables were (or will be) used by resource until given time. """
minutes_from_last_update = self._get_minutes_from_last_update(time)
if minutes_from_last_update < 0:
raise ConsumptionDetailCalculateError('Cannot calculate consumption if... | [
"def",
"_get_consumed",
"(",
"self",
",",
"time",
")",
":",
"minutes_from_last_update",
"=",
"self",
".",
"_get_minutes_from_last_update",
"(",
"time",
")",
"if",
"minutes_from_last_update",
"<",
"0",
":",
"raise",
"ConsumptionDetailCalculateError",
"(",
"'Cannot calc... | How many consumables were (or will be) used by resource until given time. | [
"How",
"many",
"consumables",
"were",
"(",
"or",
"will",
"be",
")",
"used",
"by",
"resource",
"until",
"given",
"time",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/models.py#L319-L329 | train |
opennode/waldur-core | waldur_core/cost_tracking/models.py | ConsumptionDetails._get_minutes_from_last_update | def _get_minutes_from_last_update(self, time):
""" How much minutes passed from last update to given time """
time_from_last_update = time - self.last_update_time
return int(time_from_last_update.total_seconds() / 60) | python | def _get_minutes_from_last_update(self, time):
""" How much minutes passed from last update to given time """
time_from_last_update = time - self.last_update_time
return int(time_from_last_update.total_seconds() / 60) | [
"def",
"_get_minutes_from_last_update",
"(",
"self",
",",
"time",
")",
":",
"time_from_last_update",
"=",
"time",
"-",
"self",
".",
"last_update_time",
"return",
"int",
"(",
"time_from_last_update",
".",
"total_seconds",
"(",
")",
"/",
"60",
")"
] | How much minutes passed from last update to given time | [
"How",
"much",
"minutes",
"passed",
"from",
"last",
"update",
"to",
"given",
"time"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/models.py#L331-L334 | train |
opennode/waldur-core | waldur_core/cost_tracking/models.py | PriceListItem.get_for_resource | def get_for_resource(resource):
""" Get list of all price list items that should be used for resource.
If price list item is defined for service - return it, otherwise -
return default price list item.
"""
resource_content_type = ContentType.objects.get_for_model(resourc... | python | def get_for_resource(resource):
""" Get list of all price list items that should be used for resource.
If price list item is defined for service - return it, otherwise -
return default price list item.
"""
resource_content_type = ContentType.objects.get_for_model(resourc... | [
"def",
"get_for_resource",
"(",
"resource",
")",
":",
"resource_content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"resource",
")",
"default_items",
"=",
"set",
"(",
"DefaultPriceListItem",
".",
"objects",
".",
"filter",
"(",
"resource_c... | Get list of all price list items that should be used for resource.
If price list item is defined for service - return it, otherwise -
return default price list item. | [
"Get",
"list",
"of",
"all",
"price",
"list",
"items",
"that",
"should",
"be",
"used",
"for",
"resource",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/models.py#L457-L469 | train |
opennode/waldur-core | waldur_core/core/__init__.py | WaldurExtension.get_extensions | def get_extensions(cls):
""" Get a list of available extensions """
assemblies = []
for waldur_extension in pkg_resources.iter_entry_points('waldur_extensions'):
extension_module = waldur_extension.load()
if inspect.isclass(extension_module) and issubclass(extension_modul... | python | def get_extensions(cls):
""" Get a list of available extensions """
assemblies = []
for waldur_extension in pkg_resources.iter_entry_points('waldur_extensions'):
extension_module = waldur_extension.load()
if inspect.isclass(extension_module) and issubclass(extension_modul... | [
"def",
"get_extensions",
"(",
"cls",
")",
":",
"assemblies",
"=",
"[",
"]",
"for",
"waldur_extension",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'waldur_extensions'",
")",
":",
"extension_module",
"=",
"waldur_extension",
".",
"load",
"(",
")",
"if"... | Get a list of available extensions | [
"Get",
"a",
"list",
"of",
"available",
"extensions"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/__init__.py#L50-L61 | train |
quora/qcore | qcore/helpers.py | ellipsis | def ellipsis(source, max_length):
"""Truncates a string to be at most max_length long."""
if max_length == 0 or len(source) <= max_length:
return source
return source[: max(0, max_length - 3)] + "..." | python | def ellipsis(source, max_length):
"""Truncates a string to be at most max_length long."""
if max_length == 0 or len(source) <= max_length:
return source
return source[: max(0, max_length - 3)] + "..." | [
"def",
"ellipsis",
"(",
"source",
",",
"max_length",
")",
":",
"if",
"max_length",
"==",
"0",
"or",
"len",
"(",
"source",
")",
"<=",
"max_length",
":",
"return",
"source",
"return",
"source",
"[",
":",
"max",
"(",
"0",
",",
"max_length",
"-",
"3",
")... | Truncates a string to be at most max_length long. | [
"Truncates",
"a",
"string",
"to",
"be",
"at",
"most",
"max_length",
"long",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L232-L236 | train |
quora/qcore | qcore/helpers.py | safe_str | def safe_str(source, max_length=0):
"""Wrapper for str() that catches exceptions."""
try:
return ellipsis(str(source), max_length)
except Exception as e:
return ellipsis("<n/a: str(...) raised %s>" % e, max_length) | python | def safe_str(source, max_length=0):
"""Wrapper for str() that catches exceptions."""
try:
return ellipsis(str(source), max_length)
except Exception as e:
return ellipsis("<n/a: str(...) raised %s>" % e, max_length) | [
"def",
"safe_str",
"(",
"source",
",",
"max_length",
"=",
"0",
")",
":",
"try",
":",
"return",
"ellipsis",
"(",
"str",
"(",
"source",
")",
",",
"max_length",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"ellipsis",
"(",
"\"<n/a: str(...) raised %s... | Wrapper for str() that catches exceptions. | [
"Wrapper",
"for",
"str",
"()",
"that",
"catches",
"exceptions",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L239-L244 | train |
quora/qcore | qcore/helpers.py | safe_repr | def safe_repr(source, max_length=0):
"""Wrapper for repr() that catches exceptions."""
try:
return ellipsis(repr(source), max_length)
except Exception as e:
return ellipsis("<n/a: repr(...) raised %s>" % e, max_length) | python | def safe_repr(source, max_length=0):
"""Wrapper for repr() that catches exceptions."""
try:
return ellipsis(repr(source), max_length)
except Exception as e:
return ellipsis("<n/a: repr(...) raised %s>" % e, max_length) | [
"def",
"safe_repr",
"(",
"source",
",",
"max_length",
"=",
"0",
")",
":",
"try",
":",
"return",
"ellipsis",
"(",
"repr",
"(",
"source",
")",
",",
"max_length",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"ellipsis",
"(",
"\"<n/a: repr(...) raised... | Wrapper for repr() that catches exceptions. | [
"Wrapper",
"for",
"repr",
"()",
"that",
"catches",
"exceptions",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L247-L252 | train |
quora/qcore | qcore/helpers.py | dict_to_object | def dict_to_object(source):
"""Returns an object with the key-value pairs in source as attributes."""
target = inspectable_class.InspectableClass()
for k, v in source.items():
setattr(target, k, v)
return target | python | def dict_to_object(source):
"""Returns an object with the key-value pairs in source as attributes."""
target = inspectable_class.InspectableClass()
for k, v in source.items():
setattr(target, k, v)
return target | [
"def",
"dict_to_object",
"(",
"source",
")",
":",
"target",
"=",
"inspectable_class",
".",
"InspectableClass",
"(",
")",
"for",
"k",
",",
"v",
"in",
"source",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"target",
",",
"k",
",",
"v",
")",
"return",
"... | Returns an object with the key-value pairs in source as attributes. | [
"Returns",
"an",
"object",
"with",
"the",
"key",
"-",
"value",
"pairs",
"in",
"source",
"as",
"attributes",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L255-L260 | train |
quora/qcore | qcore/helpers.py | copy_public_attrs | def copy_public_attrs(source_obj, dest_obj):
"""Shallow copies all public attributes from source_obj to dest_obj.
Overwrites them if they already exist.
"""
for name, value in inspect.getmembers(source_obj):
if not any(name.startswith(x) for x in ["_", "func", "im"]):
setattr(dest_... | python | def copy_public_attrs(source_obj, dest_obj):
"""Shallow copies all public attributes from source_obj to dest_obj.
Overwrites them if they already exist.
"""
for name, value in inspect.getmembers(source_obj):
if not any(name.startswith(x) for x in ["_", "func", "im"]):
setattr(dest_... | [
"def",
"copy_public_attrs",
"(",
"source_obj",
",",
"dest_obj",
")",
":",
"for",
"name",
",",
"value",
"in",
"inspect",
".",
"getmembers",
"(",
"source_obj",
")",
":",
"if",
"not",
"any",
"(",
"name",
".",
"startswith",
"(",
"x",
")",
"for",
"x",
"in",... | Shallow copies all public attributes from source_obj to dest_obj.
Overwrites them if they already exist. | [
"Shallow",
"copies",
"all",
"public",
"attributes",
"from",
"source_obj",
"to",
"dest_obj",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L263-L271 | train |
quora/qcore | qcore/helpers.py | object_from_string | def object_from_string(name):
"""Creates a Python class or function from its fully qualified name.
:param name: A fully qualified name of a class or a function. In Python 3 this
is only allowed to be of text type (unicode). In Python 2, both bytes and unicode
are allowed.
:return: A functio... | python | def object_from_string(name):
"""Creates a Python class or function from its fully qualified name.
:param name: A fully qualified name of a class or a function. In Python 3 this
is only allowed to be of text type (unicode). In Python 2, both bytes and unicode
are allowed.
:return: A functio... | [
"def",
"object_from_string",
"(",
"name",
")",
":",
"if",
"six",
".",
"PY3",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"name must be str, not %r\"",
"%",
"type",
"(",
"name",
")",
")",
"else",
":",
... | Creates a Python class or function from its fully qualified name.
:param name: A fully qualified name of a class or a function. In Python 3 this
is only allowed to be of text type (unicode). In Python 2, both bytes and unicode
are allowed.
:return: A function or class object.
This method i... | [
"Creates",
"a",
"Python",
"class",
"or",
"function",
"from",
"its",
"fully",
"qualified",
"name",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L274-L313 | train |
quora/qcore | qcore/helpers.py | catchable_exceptions | def catchable_exceptions(exceptions):
"""Returns True if exceptions can be caught in the except clause.
The exception can be caught if it is an Exception type or a tuple of
exception types.
"""
if isinstance(exceptions, type) and issubclass(exceptions, BaseException):
return True
if (... | python | def catchable_exceptions(exceptions):
"""Returns True if exceptions can be caught in the except clause.
The exception can be caught if it is an Exception type or a tuple of
exception types.
"""
if isinstance(exceptions, type) and issubclass(exceptions, BaseException):
return True
if (... | [
"def",
"catchable_exceptions",
"(",
"exceptions",
")",
":",
"if",
"isinstance",
"(",
"exceptions",
",",
"type",
")",
"and",
"issubclass",
"(",
"exceptions",
",",
"BaseException",
")",
":",
"return",
"True",
"if",
"(",
"isinstance",
"(",
"exceptions",
",",
"t... | Returns True if exceptions can be caught in the except clause.
The exception can be caught if it is an Exception type or a tuple of
exception types. | [
"Returns",
"True",
"if",
"exceptions",
"can",
"be",
"caught",
"in",
"the",
"except",
"clause",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L316-L333 | train |
quora/qcore | qcore/helpers.py | ScopedValue.override | def override(self, value):
"""Temporarily overrides the old value with the new one."""
if self._value is not value:
return _ScopedValueOverrideContext(self, value)
else:
return empty_context | python | def override(self, value):
"""Temporarily overrides the old value with the new one."""
if self._value is not value:
return _ScopedValueOverrideContext(self, value)
else:
return empty_context | [
"def",
"override",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_value",
"is",
"not",
"value",
":",
"return",
"_ScopedValueOverrideContext",
"(",
"self",
",",
"value",
")",
"else",
":",
"return",
"empty_context"
] | Temporarily overrides the old value with the new one. | [
"Temporarily",
"overrides",
"the",
"old",
"value",
"with",
"the",
"new",
"one",
"."
] | fa5cd438eea554db35fd29cbc8dfbde69f09961c | https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L181-L186 | train |
opennode/waldur-core | waldur_core/core/views.py | ActionsViewSet.validate_object_action | def validate_object_action(self, action_name, obj=None):
""" Execute validation for actions that are related to particular object """
action_method = getattr(self, action_name)
if not getattr(action_method, 'detail', False) and action_name not in ('update', 'partial_update', 'destroy'):
... | python | def validate_object_action(self, action_name, obj=None):
""" Execute validation for actions that are related to particular object """
action_method = getattr(self, action_name)
if not getattr(action_method, 'detail', False) and action_name not in ('update', 'partial_update', 'destroy'):
... | [
"def",
"validate_object_action",
"(",
"self",
",",
"action_name",
",",
"obj",
"=",
"None",
")",
":",
"action_method",
"=",
"getattr",
"(",
"self",
",",
"action_name",
")",
"if",
"not",
"getattr",
"(",
"action_method",
",",
"'detail'",
",",
"False",
")",
"a... | Execute validation for actions that are related to particular object | [
"Execute",
"validation",
"for",
"actions",
"that",
"are",
"related",
"to",
"particular",
"object"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/views.py#L290-L299 | train |
mhjohnson/PyParse | PyParse.py | Parser.row_dict | def row_dict(self, row):
"""returns dictionary version of row using keys from self.field_map"""
d = {}
for field_name,index in self.field_map.items():
d[field_name] = self.field_value(row, field_name)
return d | python | def row_dict(self, row):
"""returns dictionary version of row using keys from self.field_map"""
d = {}
for field_name,index in self.field_map.items():
d[field_name] = self.field_value(row, field_name)
return d | [
"def",
"row_dict",
"(",
"self",
",",
"row",
")",
":",
"d",
"=",
"{",
"}",
"for",
"field_name",
",",
"index",
"in",
"self",
".",
"field_map",
".",
"items",
"(",
")",
":",
"d",
"[",
"field_name",
"]",
"=",
"self",
".",
"field_value",
"(",
"row",
",... | returns dictionary version of row using keys from self.field_map | [
"returns",
"dictionary",
"version",
"of",
"row",
"using",
"keys",
"from",
"self",
".",
"field_map"
] | 4a78160255d2d9ca95728ea655dd188ef74b5075 | https://github.com/mhjohnson/PyParse/blob/4a78160255d2d9ca95728ea655dd188ef74b5075/PyParse.py#L95-L100 | train |
mhjohnson/PyParse | PyParse.py | Parser._dialect | def _dialect(self, filepath):
"""returns detected dialect of filepath and sets self.has_header
if not passed in __init__ kwargs
Arguments:
filepath (str): filepath of target csv file
"""
with open(filepath, self.read_mode) as csvfile:
sample = csvfile.read... | python | def _dialect(self, filepath):
"""returns detected dialect of filepath and sets self.has_header
if not passed in __init__ kwargs
Arguments:
filepath (str): filepath of target csv file
"""
with open(filepath, self.read_mode) as csvfile:
sample = csvfile.read... | [
"def",
"_dialect",
"(",
"self",
",",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"self",
".",
"read_mode",
")",
"as",
"csvfile",
":",
"sample",
"=",
"csvfile",
".",
"read",
"(",
"1024",
")",
"dialect",
"=",
"csv",
".",
"Sniffer",
"(",... | returns detected dialect of filepath and sets self.has_header
if not passed in __init__ kwargs
Arguments:
filepath (str): filepath of target csv file | [
"returns",
"detected",
"dialect",
"of",
"filepath",
"and",
"sets",
"self",
".",
"has_header",
"if",
"not",
"passed",
"in",
"__init__",
"kwargs",
"Arguments",
":",
"filepath",
"(",
"str",
")",
":",
"filepath",
"of",
"target",
"csv",
"file"
] | 4a78160255d2d9ca95728ea655dd188ef74b5075 | https://github.com/mhjohnson/PyParse/blob/4a78160255d2d9ca95728ea655dd188ef74b5075/PyParse.py#L102-L115 | train |
opennode/waldur-core | waldur_core/cost_tracking/admin.py | _get_content_type_queryset | def _get_content_type_queryset(models_list):
""" Get list of services content types """
content_type_ids = {c.id for c in ContentType.objects.get_for_models(*models_list).values()}
return ContentType.objects.filter(id__in=content_type_ids) | python | def _get_content_type_queryset(models_list):
""" Get list of services content types """
content_type_ids = {c.id for c in ContentType.objects.get_for_models(*models_list).values()}
return ContentType.objects.filter(id__in=content_type_ids) | [
"def",
"_get_content_type_queryset",
"(",
"models_list",
")",
":",
"content_type_ids",
"=",
"{",
"c",
".",
"id",
"for",
"c",
"in",
"ContentType",
".",
"objects",
".",
"get_for_models",
"(",
"*",
"models_list",
")",
".",
"values",
"(",
")",
"}",
"return",
"... | Get list of services content types | [
"Get",
"list",
"of",
"services",
"content",
"types"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/admin.py#L15-L18 | train |
opennode/waldur-core | waldur_core/cost_tracking/admin.py | DefaultPriceListItemAdmin.init_registered | def init_registered(self, request):
""" Create default price list items for each registered resource. """
created_items = models.DefaultPriceListItem.init_from_registered_resources()
if created_items:
message = ungettext(
_('Price item was created: %s.') % created_it... | python | def init_registered(self, request):
""" Create default price list items for each registered resource. """
created_items = models.DefaultPriceListItem.init_from_registered_resources()
if created_items:
message = ungettext(
_('Price item was created: %s.') % created_it... | [
"def",
"init_registered",
"(",
"self",
",",
"request",
")",
":",
"created_items",
"=",
"models",
".",
"DefaultPriceListItem",
".",
"init_from_registered_resources",
"(",
")",
"if",
"created_items",
":",
"message",
"=",
"ungettext",
"(",
"_",
"(",
"'Price item was ... | Create default price list items for each registered resource. | [
"Create",
"default",
"price",
"list",
"items",
"for",
"each",
"registered",
"resource",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/admin.py#L60-L74 | train |
opennode/waldur-core | waldur_core/cost_tracking/admin.py | DefaultPriceListItemAdmin.reinit_configurations | def reinit_configurations(self, request):
""" Re-initialize configuration for resource if it has been changed.
This method should be called if resource consumption strategy was changed.
"""
now = timezone.now()
# Step 1. Collect all resources with changed configuration.
... | python | def reinit_configurations(self, request):
""" Re-initialize configuration for resource if it has been changed.
This method should be called if resource consumption strategy was changed.
"""
now = timezone.now()
# Step 1. Collect all resources with changed configuration.
... | [
"def",
"reinit_configurations",
"(",
"self",
",",
"request",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"# Step 1. Collect all resources with changed configuration.",
"changed_resources",
"=",
"[",
"]",
"for",
"resource_model",
"in",
"CostTrackingRegister",... | Re-initialize configuration for resource if it has been changed.
This method should be called if resource consumption strategy was changed. | [
"Re",
"-",
"initialize",
"configuration",
"for",
"resource",
"if",
"it",
"has",
"been",
"changed",
"."
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/admin.py#L106-L133 | train |
nuagenetworks/bambou | bambou/utils/sha1.py | Sha1.encrypt | def encrypt(self, message):
""" Encrypt the given message """
if not isinstance(message, (bytes, str)):
raise TypeError
return hashlib.sha1(message.encode('utf-8')).hexdigest() | python | def encrypt(self, message):
""" Encrypt the given message """
if not isinstance(message, (bytes, str)):
raise TypeError
return hashlib.sha1(message.encode('utf-8')).hexdigest() | [
"def",
"encrypt",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"(",
"bytes",
",",
"str",
")",
")",
":",
"raise",
"TypeError",
"return",
"hashlib",
".",
"sha1",
"(",
"message",
".",
"encode",
"(",
"'utf-8'",
"... | Encrypt the given message | [
"Encrypt",
"the",
"given",
"message"
] | d334fea23e384d3df8e552fe1849ad707941c666 | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/utils/sha1.py#L37-L43 | train |
opennode/waldur-core | waldur_core/core/models.py | ScheduleMixin.save | def save(self, *args, **kwargs):
"""
Updates next_trigger_at field if:
- instance become active
- instance.schedule changed
- instance is new
"""
try:
prev_instance = self.__class__.objects.get(pk=self.pk)
except self.DoesNotExist:
... | python | def save(self, *args, **kwargs):
"""
Updates next_trigger_at field if:
- instance become active
- instance.schedule changed
- instance is new
"""
try:
prev_instance = self.__class__.objects.get(pk=self.pk)
except self.DoesNotExist:
... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"prev_instance",
"=",
"self",
".",
"__class__",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"pk",
")",
"except",
"self",
".",
"DoesNotExist",
... | Updates next_trigger_at field if:
- instance become active
- instance.schedule changed
- instance is new | [
"Updates",
"next_trigger_at",
"field",
"if",
":",
"-",
"instance",
"become",
"active",
"-",
"instance",
".",
"schedule",
"changed",
"-",
"instance",
"is",
"new"
] | d6c17a9592bb6c49c33567542eef8d099605a46a | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/models.py#L115-L131 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.