repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
quora/qcore
qcore/caching.py
lru_cache
def lru_cache(maxsize=128, key_fn=None): """Decorator that adds an LRU cache of size maxsize to the decorated function. maxsize is the number of different keys cache can accomodate. key_fn is the function that builds key from args. The default key function creates a tuple out of args and kwargs. If you...
python
def lru_cache(maxsize=128, key_fn=None): """Decorator that adds an LRU cache of size maxsize to the decorated function. maxsize is the number of different keys cache can accomodate. key_fn is the function that builds key from args. The default key function creates a tuple out of args and kwargs. If you...
[ "def", "lru_cache", "(", "maxsize", "=", "128", ",", "key_fn", "=", "None", ")", ":", "def", "decorator", "(", "fn", ")", ":", "cache", "=", "LRUCache", "(", "maxsize", ")", "argspec", "=", "inspect2", ".", "getfullargspec", "(", "fn", ")", "arg_names"...
Decorator that adds an LRU cache of size maxsize to the decorated function. maxsize is the number of different keys cache can accomodate. key_fn is the function that builds key from args. The default key function creates a tuple out of args and kwargs. If you use the default, there is no reason not to ...
[ "Decorator", "that", "adds", "an", "LRU", "cache", "of", "size", "maxsize", "to", "the", "decorated", "function", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L238-L278
quora/qcore
qcore/caching.py
cached_per_instance
def cached_per_instance(): """Decorator that adds caching to an instance method. The cached value is stored so that it gets garbage collected together with the instance. The cached values are not stored when the object is pickled. """ def cache_fun(fun): argspec = inspect2.getfullargspec...
python
def cached_per_instance(): """Decorator that adds caching to an instance method. The cached value is stored so that it gets garbage collected together with the instance. The cached values are not stored when the object is pickled. """ def cache_fun(fun): argspec = inspect2.getfullargspec...
[ "def", "cached_per_instance", "(", ")", ":", "def", "cache_fun", "(", "fun", ")", ":", "argspec", "=", "inspect2", ".", "getfullargspec", "(", "fun", ")", "arg_names", "=", "argspec", ".", "args", "[", "1", ":", "]", "+", "argspec", ".", "kwonlyargs", ...
Decorator that adds caching to an instance method. The cached value is stored so that it gets garbage collected together with the instance. The cached values are not stored when the object is pickled.
[ "Decorator", "that", "adds", "caching", "to", "an", "instance", "method", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L281-L319
quora/qcore
qcore/caching.py
get_args_tuple
def get_args_tuple(args, kwargs, arg_names, kwargs_defaults): """Generates a cache key from the passed in arguments.""" args_list = list(args) args_len = len(args) all_args_len = len(arg_names) try: while args_len < all_args_len: arg_name = arg_names[args_len] if arg_...
python
def get_args_tuple(args, kwargs, arg_names, kwargs_defaults): """Generates a cache key from the passed in arguments.""" args_list = list(args) args_len = len(args) all_args_len = len(arg_names) try: while args_len < all_args_len: arg_name = arg_names[args_len] if arg_...
[ "def", "get_args_tuple", "(", "args", ",", "kwargs", ",", "arg_names", ",", "kwargs_defaults", ")", ":", "args_list", "=", "list", "(", "args", ")", "args_len", "=", "len", "(", "args", ")", "all_args_len", "=", "len", "(", "arg_names", ")", "try", ":", ...
Generates a cache key from the passed in arguments.
[ "Generates", "a", "cache", "key", "from", "the", "passed", "in", "arguments", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L322-L337
quora/qcore
qcore/caching.py
get_kwargs_defaults
def get_kwargs_defaults(argspec): """Computes a kwargs_defaults dictionary for use by get_args_tuple given an argspec.""" arg_names = tuple(argspec.args) defaults = argspec.defaults or () num_args = len(argspec.args) - len(defaults) kwargs_defaults = {} for i, default_value in enumerate(defaults...
python
def get_kwargs_defaults(argspec): """Computes a kwargs_defaults dictionary for use by get_args_tuple given an argspec.""" arg_names = tuple(argspec.args) defaults = argspec.defaults or () num_args = len(argspec.args) - len(defaults) kwargs_defaults = {} for i, default_value in enumerate(defaults...
[ "def", "get_kwargs_defaults", "(", "argspec", ")", ":", "arg_names", "=", "tuple", "(", "argspec", ".", "args", ")", "defaults", "=", "argspec", ".", "defaults", "or", "(", ")", "num_args", "=", "len", "(", "argspec", ".", "args", ")", "-", "len", "(",...
Computes a kwargs_defaults dictionary for use by get_args_tuple given an argspec.
[ "Computes", "a", "kwargs_defaults", "dictionary", "for", "use", "by", "get_args_tuple", "given", "an", "argspec", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L340-L350
quora/qcore
qcore/caching.py
memoize
def memoize(fun): """Memoizes return values of the decorated function. Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache() is called on the function. """ argspec = inspect2.getfullargspec(fun) arg_names = argspec.args + argspec.kwonlyargs kwargs...
python
def memoize(fun): """Memoizes return values of the decorated function. Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache() is called on the function. """ argspec = inspect2.getfullargspec(fun) arg_names = argspec.args + argspec.kwonlyargs kwargs...
[ "def", "memoize", "(", "fun", ")", ":", "argspec", "=", "inspect2", ".", "getfullargspec", "(", "fun", ")", "arg_names", "=", "argspec", ".", "args", "+", "argspec", ".", "kwonlyargs", "kwargs_defaults", "=", "get_kwargs_defaults", "(", "argspec", ")", "def"...
Memoizes return values of the decorated function. Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache() is called on the function.
[ "Memoizes", "return", "values", "of", "the", "decorated", "function", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L353-L380
quora/qcore
qcore/caching.py
memoize_with_ttl
def memoize_with_ttl(ttl_secs=60 * 60 * 24): """Memoizes return values of the decorated function for a given time-to-live. Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache() is called on the function or the time-to-live expires. By default, the time-to-live is ...
python
def memoize_with_ttl(ttl_secs=60 * 60 * 24): """Memoizes return values of the decorated function for a given time-to-live. Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache() is called on the function or the time-to-live expires. By default, the time-to-live is ...
[ "def", "memoize_with_ttl", "(", "ttl_secs", "=", "60", "*", "60", "*", "24", ")", ":", "error_msg", "=", "(", "\"Incorrect usage of qcore.caching.memoize_with_ttl: \"", "\"ttl_secs must be a positive integer.\"", ")", "assert_is_instance", "(", "ttl_secs", ",", "six", "...
Memoizes return values of the decorated function for a given time-to-live. Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache() is called on the function or the time-to-live expires. By default, the time-to-live is set to 24 hours.
[ "Memoizes", "return", "values", "of", "the", "decorated", "function", "for", "a", "given", "time", "-", "to", "-", "live", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L383-L445
quora/qcore
qcore/caching.py
LazyConstant.get_value
def get_value(self): """Returns the value of the constant.""" if self.value is not_computed: self.value = self.value_provider() if self.value is not_computed: return None return self.value
python
def get_value(self): """Returns the value of the constant.""" if self.value is not_computed: self.value = self.value_provider() if self.value is not_computed: return None return self.value
[ "def", "get_value", "(", "self", ")", ":", "if", "self", ".", "value", "is", "not_computed", ":", "self", ".", "value", "=", "self", ".", "value_provider", "(", ")", "if", "self", ".", "value", "is", "not_computed", ":", "return", "None", "return", "se...
Returns the value of the constant.
[ "Returns", "the", "value", "of", "the", "constant", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L64-L70
quora/qcore
qcore/caching.py
LazyConstant.compute
def compute(self): """Computes the value. Does not look at the cache.""" self.value = self.value_provider() if self.value is not_computed: return None else: return self.value
python
def compute(self): """Computes the value. Does not look at the cache.""" self.value = self.value_provider() if self.value is not_computed: return None else: return self.value
[ "def", "compute", "(", "self", ")", ":", "self", ".", "value", "=", "self", ".", "value_provider", "(", ")", "if", "self", ".", "value", "is", "not_computed", ":", "return", "None", "else", ":", "return", "self", ".", "value" ]
Computes the value. Does not look at the cache.
[ "Computes", "the", "value", ".", "Does", "not", "look", "at", "the", "cache", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L72-L78
quora/qcore
qcore/caching.py
LRUCache.get
def get(self, key, default=miss): """Return the value for given key if it exists.""" if key not in self._dict: return default # invokes __getitem__, which updates the item return self[key]
python
def get(self, key, default=miss): """Return the value for given key if it exists.""" if key not in self._dict: return default # invokes __getitem__, which updates the item return self[key]
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "miss", ")", ":", "if", "key", "not", "in", "self", ".", "_dict", ":", "return", "default", "# invokes __getitem__, which updates the item", "return", "self", "[", "key", "]" ]
Return the value for given key if it exists.
[ "Return", "the", "value", "for", "given", "key", "if", "it", "exists", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L187-L193
quora/qcore
qcore/caching.py
LRUCache.clear
def clear(self, omit_item_evicted=False): """Empty the cache and optionally invoke item_evicted callback.""" if not omit_item_evicted: items = self._dict.items() for key, value in items: self._evict_item(key, value) self._dict.clear()
python
def clear(self, omit_item_evicted=False): """Empty the cache and optionally invoke item_evicted callback.""" if not omit_item_evicted: items = self._dict.items() for key, value in items: self._evict_item(key, value) self._dict.clear()
[ "def", "clear", "(", "self", ",", "omit_item_evicted", "=", "False", ")", ":", "if", "not", "omit_item_evicted", ":", "items", "=", "self", ".", "_dict", ".", "items", "(", ")", "for", "key", ",", "value", "in", "items", ":", "self", ".", "_evict_item"...
Empty the cache and optionally invoke item_evicted callback.
[ "Empty", "the", "cache", "and", "optionally", "invoke", "item_evicted", "callback", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L209-L215
zeromake/aiosqlite3
aiosqlite3/utils.py
create_future
def create_future(loop): # pragma: no cover """Compatibility wrapper for the loop.create_future() call introduced in 3.5.2.""" if hasattr(loop, 'create_future'): return loop.create_future() return asyncio.Future(loop=loop)
python
def create_future(loop): # pragma: no cover """Compatibility wrapper for the loop.create_future() call introduced in 3.5.2.""" if hasattr(loop, 'create_future'): return loop.create_future() return asyncio.Future(loop=loop)
[ "def", "create_future", "(", "loop", ")", ":", "# pragma: no cover", "if", "hasattr", "(", "loop", ",", "'create_future'", ")", ":", "return", "loop", ".", "create_future", "(", ")", "return", "asyncio", ".", "Future", "(", "loop", "=", "loop", ")" ]
Compatibility wrapper for the loop.create_future() call introduced in 3.5.2.
[ "Compatibility", "wrapper", "for", "the", "loop", ".", "create_future", "()", "call", "introduced", "in", "3", ".", "5", ".", "2", "." ]
train
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/utils.py#L17-L23
zeromake/aiosqlite3
aiosqlite3/utils.py
create_task
def create_task(coro, loop): # pragma: no cover """Compatibility wrapper for the loop.create_task() call introduced in 3.4.2.""" if hasattr(loop, 'create_task'): return loop.create_task(coro) return asyncio.Task(coro, loop=loop)
python
def create_task(coro, loop): # pragma: no cover """Compatibility wrapper for the loop.create_task() call introduced in 3.4.2.""" if hasattr(loop, 'create_task'): return loop.create_task(coro) return asyncio.Task(coro, loop=loop)
[ "def", "create_task", "(", "coro", ",", "loop", ")", ":", "# pragma: no cover", "if", "hasattr", "(", "loop", ",", "'create_task'", ")", ":", "return", "loop", ".", "create_task", "(", "coro", ")", "return", "asyncio", ".", "Task", "(", "coro", ",", "loo...
Compatibility wrapper for the loop.create_task() call introduced in 3.4.2.
[ "Compatibility", "wrapper", "for", "the", "loop", ".", "create_task", "()", "call", "introduced", "in", "3", ".", "4", ".", "2", "." ]
train
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/utils.py#L26-L32
zeromake/aiosqlite3
aiosqlite3/utils.py
proxy_property_directly
def proxy_property_directly(bind_attr, attrs): """ 为类添加代理属性 """ def cls_builder(cls): """ 添加到类 """ for attr_name in attrs: setattr(cls, attr_name, _make_proxy_property(bind_attr, attr_name)) return cls return cls_builder
python
def proxy_property_directly(bind_attr, attrs): """ 为类添加代理属性 """ def cls_builder(cls): """ 添加到类 """ for attr_name in attrs: setattr(cls, attr_name, _make_proxy_property(bind_attr, attr_name)) return cls return cls_builder
[ "def", "proxy_property_directly", "(", "bind_attr", ",", "attrs", ")", ":", "def", "cls_builder", "(", "cls", ")", ":", "\"\"\"\n 添加到类\n \"\"\"", "for", "attr_name", "in", "attrs", ":", "setattr", "(", "cls", ",", "attr_name", ",", "_make_proxy_prope...
为类添加代理属性
[ "为类添加代理属性" ]
train
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/utils.py#L265-L276
opennode/waldur-core
waldur_core/structure/models.py
StructureLoggableMixin.get_permitted_objects_uuids
def get_permitted_objects_uuids(cls, user): """ Return query dictionary to search objects available to user. """ uuids = filter_queryset_for_user(cls.objects.all(), user).values_list('uuid', flat=True) key = core_utils.camel_case_to_underscore(cls.__name__) + '_uuid' retu...
python
def get_permitted_objects_uuids(cls, user): """ Return query dictionary to search objects available to user. """ uuids = filter_queryset_for_user(cls.objects.all(), user).values_list('uuid', flat=True) key = core_utils.camel_case_to_underscore(cls.__name__) + '_uuid' retu...
[ "def", "get_permitted_objects_uuids", "(", "cls", ",", "user", ")", ":", "uuids", "=", "filter_queryset_for_user", "(", "cls", ".", "objects", ".", "all", "(", ")", ",", "user", ")", ".", "values_list", "(", "'uuid'", ",", "flat", "=", "True", ")", "key"...
Return query dictionary to search objects available to user.
[ "Return", "query", "dictionary", "to", "search", "objects", "available", "to", "user", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/models.py#L79-L85
opennode/waldur-core
waldur_core/structure/models.py
PermissionMixin.has_user
def has_user(self, user, role=None, timestamp=False): """ Checks whether user has role in entity. `timestamp` can have following values: - False - check whether user has role in entity at the moment. - None - check whether user has permanent role in entity. - ...
python
def has_user(self, user, role=None, timestamp=False): """ Checks whether user has role in entity. `timestamp` can have following values: - False - check whether user has role in entity at the moment. - None - check whether user has permanent role in entity. - ...
[ "def", "has_user", "(", "self", ",", "user", ",", "role", "=", "None", ",", "timestamp", "=", "False", ")", ":", "permissions", "=", "self", ".", "permissions", ".", "filter", "(", "user", "=", "user", ",", "is_active", "=", "True", ")", "if", "role"...
Checks whether user has role in entity. `timestamp` can have following values: - False - check whether user has role in entity at the moment. - None - check whether user has permanent role in entity. - Datetime object - check whether user will have role in entity at specific ...
[ "Checks", "whether", "user", "has", "role", "in", "entity", ".", "timestamp", "can", "have", "following", "values", ":", "-", "False", "-", "check", "whether", "user", "has", "role", "in", "entity", "at", "the", "moment", ".", "-", "None", "-", "check", ...
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/models.py#L191-L209
opennode/waldur-core
waldur_core/core/magic.py
Magic.from_buffer
def from_buffer(self, buf): """ Identify the contents of `buf` """ with self.lock: try: # if we're on python3, convert buf to bytes # otherwise this string is passed as wchar* # which is not what libmagic expects ...
python
def from_buffer(self, buf): """ Identify the contents of `buf` """ with self.lock: try: # if we're on python3, convert buf to bytes # otherwise this string is passed as wchar* # which is not what libmagic expects ...
[ "def", "from_buffer", "(", "self", ",", "buf", ")", ":", "with", "self", ".", "lock", ":", "try", ":", "# if we're on python3, convert buf to bytes", "# otherwise this string is passed as wchar*", "# which is not what libmagic expects", "if", "isinstance", "(", "buf", ","...
Identify the contents of `buf`
[ "Identify", "the", "contents", "of", "buf" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/magic.py#L71-L84
nuagenetworks/bambou
bambou/nurest_push_center.py
NURESTPushCenter.start
def start(self, timeout=None, root_object=None): """ Starts listening to events. Args: timeout (int): number of seconds before timeout. Used for testing purpose only. root_object (bambou.NURESTRootObject): NURESTRootObject object that is listening. Used for testing p...
python
def start(self, timeout=None, root_object=None): """ Starts listening to events. Args: timeout (int): number of seconds before timeout. Used for testing purpose only. root_object (bambou.NURESTRootObject): NURESTRootObject object that is listening. Used for testing p...
[ "def", "start", "(", "self", ",", "timeout", "=", "None", ",", "root_object", "=", "None", ")", ":", "if", "self", ".", "_is_running", ":", "return", "if", "timeout", ":", "self", ".", "_timeout", "=", "timeout", "self", ".", "_start_time", "=", "int",...
Starts listening to events. Args: timeout (int): number of seconds before timeout. Used for testing purpose only. root_object (bambou.NURESTRootObject): NURESTRootObject object that is listening. Used for testing purpose only.
[ "Starts", "listening", "to", "events", "." ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L103-L128
nuagenetworks/bambou
bambou/nurest_push_center.py
NURESTPushCenter.stop
def stop(self): """ Stops listening for events. """ if not self._is_running: return pushcenter_logger.debug("[NURESTPushCenter] Stopping...") self._thread.stop() self._thread.join() self._is_running = False self._current_connection = None s...
python
def stop(self): """ Stops listening for events. """ if not self._is_running: return pushcenter_logger.debug("[NURESTPushCenter] Stopping...") self._thread.stop() self._thread.join() self._is_running = False self._current_connection = None s...
[ "def", "stop", "(", "self", ")", ":", "if", "not", "self", ".", "_is_running", ":", "return", "pushcenter_logger", ".", "debug", "(", "\"[NURESTPushCenter] Stopping...\"", ")", "self", ".", "_thread", ".", "stop", "(", ")", "self", ".", "_thread", ".", "jo...
Stops listening for events.
[ "Stops", "listening", "for", "events", "." ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L130-L144
nuagenetworks/bambou
bambou/nurest_push_center.py
NURESTPushCenter.wait_until_exit
def wait_until_exit(self): """ Wait until thread exit Used for testing purpose only """ if self._timeout is None: raise Exception("Thread will never exit. Use stop or specify timeout when starting it!") self._thread.join() self.stop()
python
def wait_until_exit(self): """ Wait until thread exit Used for testing purpose only """ if self._timeout is None: raise Exception("Thread will never exit. Use stop or specify timeout when starting it!") self._thread.join() self.stop()
[ "def", "wait_until_exit", "(", "self", ")", ":", "if", "self", ".", "_timeout", "is", "None", ":", "raise", "Exception", "(", "\"Thread will never exit. Use stop or specify timeout when starting it!\"", ")", "self", ".", "_thread", ".", "join", "(", ")", "self", "...
Wait until thread exit Used for testing purpose only
[ "Wait", "until", "thread", "exit" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L146-L156
nuagenetworks/bambou
bambou/nurest_push_center.py
NURESTPushCenter._did_receive_event
def _did_receive_event(self, connection): """ Receive an event from connection """ if not self._is_running: return if connection.has_timeouted: return response = connection.response data = None if response.status_code != 200: pushce...
python
def _did_receive_event(self, connection): """ Receive an event from connection """ if not self._is_running: return if connection.has_timeouted: return response = connection.response data = None if response.status_code != 200: pushce...
[ "def", "_did_receive_event", "(", "self", ",", "connection", ")", ":", "if", "not", "self", ".", "_is_running", ":", "return", "if", "connection", ".", "has_timeouted", ":", "return", "response", "=", "connection", ".", "response", "data", "=", "None", "if",...
Receive an event from connection
[ "Receive", "an", "event", "from", "connection" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L173-L210
nuagenetworks/bambou
bambou/nurest_push_center.py
NURESTPushCenter._listen
def _listen(self, uuid=None, session=None): """ Listen a connection uuid """ if self.url is None: raise Exception("NURESTPushCenter needs to have a valid URL. please use setURL: before starting it.") events_url = "%s/events" % self.url if uuid: events_url = "%s?...
python
def _listen(self, uuid=None, session=None): """ Listen a connection uuid """ if self.url is None: raise Exception("NURESTPushCenter needs to have a valid URL. please use setURL: before starting it.") events_url = "%s/events" % self.url if uuid: events_url = "%s?...
[ "def", "_listen", "(", "self", ",", "uuid", "=", "None", ",", "session", "=", "None", ")", ":", "if", "self", ".", "url", "is", "None", ":", "raise", "Exception", "(", "\"NURESTPushCenter needs to have a valid URL. please use setURL: before starting it.\"", ")", "...
Listen a connection uuid
[ "Listen", "a", "connection", "uuid" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L212-L238
nuagenetworks/bambou
bambou/nurest_push_center.py
NURESTPushCenter.add_delegate
def add_delegate(self, callback): """ Registers a new delegate callback The prototype should be function(data), where data will be the decoded json push Args: callback (function): method to trigger when push center receives events """ if callback in sel...
python
def add_delegate(self, callback): """ Registers a new delegate callback The prototype should be function(data), where data will be the decoded json push Args: callback (function): method to trigger when push center receives events """ if callback in sel...
[ "def", "add_delegate", "(", "self", ",", "callback", ")", ":", "if", "callback", "in", "self", ".", "_delegate_methods", ":", "return", "self", ".", "_delegate_methods", ".", "append", "(", "callback", ")" ]
Registers a new delegate callback The prototype should be function(data), where data will be the decoded json push Args: callback (function): method to trigger when push center receives events
[ "Registers", "a", "new", "delegate", "callback" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L240-L252
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", "." ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L254-L264
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/config.py#L108-L113
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", "." ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/config.py#L116-L157
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/filters.py#L275-L285
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", "." ]
train
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/args/types/__init__.py#L21-L70
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/images.py#L14-L20
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/microtime.py#L74-L81
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/microtime.py#L132-L202
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L27-L38
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L41-L82
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L85-L112
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L115-L133
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L136-L154
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L157-L169
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L172-L181
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L189-L202
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L205-L212
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", "." ]
train
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L215-L222
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", "." ]
train
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/args/types/complex.py#L88-L105
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", "." ]
train
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/args/types/complex.py#L108-L126
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L96-L125
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L150-L158
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L160-L169
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L171-L184
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L186-L230
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上下文模式" ]
train
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/connection.py#L443-L466
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/tasks.py#L8-L29
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", "." ]
train
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L138-L142
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", "." ]
train
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L182-L190
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...
train
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L213-L233
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", "." ]
train
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L293-L303
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/admin.py#L312-L323
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/admin.py#L325-L342
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", "." ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_session.py#L155-L169
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/handlers.py#L35-L43
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/handlers.py#L46-L56
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/handlers.py#L59-L75
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/serializers.py#L140-L145
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/serializers.py#L147-L152
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/serializers.py#L166-L175
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", "." ]
train
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L175-L204
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", ":" ]
train
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L206-L217
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" ]
train
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L219-L246
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", ":" ]
train
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L248-L255
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", ":" ]
train
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/adapters/_twisted.py#L4-L25
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L38-L53
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L91-L110
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L113-L127
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L130-L150
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_request.py#L120-L127
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/tasks.py#L118-L122
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", "??" ]
train
https://github.com/noumar/iso639/blob/2175cf04b8b8cec79d99a6c4ad31295d67c22cd6/examples/logic.py#L11-L39
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/executors.py#L99-L116
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", ":" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L25-L33
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L36-L71
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L121-L124
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L127-L131
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L139-L143
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" ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L161-L173
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", "." ]
train
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sa/transaction.py#L50-L73
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", "." ]
train
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sa/transaction.py#L90-L98
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L56-L65
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...
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L77-L86
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", "...
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L88-L107
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L135-L155
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", "." ]
train
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L157-L181
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", ":" ]
train
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/adapters/_django.py#L10-L44
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L78-L93
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", "." ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L183-L202
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L222-L249
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", "." ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L256-L291
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L293-L351
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L353-L378
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L380-L406
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L408-L436
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L438-L452
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L454-L479
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" ]
train
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L481-L495