partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
ResourceTreeServicePostgreSQL.set_position
Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_session=None):
ziggurat_foundations/models/services/resource_tree_postgres.py
def set_position(cls, resource_id, to_position, db_session=None, *args, **kwargs): """ Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_ses...
def set_position(cls, resource_id, to_position, db_session=None, *args, **kwargs): """ Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_ses...
[ "Sets", "node", "position", "for", "new", "node", "in", "the", "tree" ]
ergo/ziggurat_foundations
python
https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/resource_tree_postgres.py#L318-L339
[ "def", "set_position", "(", "cls", ",", "resource_id", ",", "to_position", ",", "db_session", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "db_session", "=", "get_db_session", "(", "db_session", ")", "# lets lock rows to prevent bad tree sta...
9eeec894d08e8d7defa60ddc04b63f69cd4cbeba
train
ResourceTreeServicePostgreSQL.check_node_parent
Checks if parent destination is valid for node :param resource_id: :param new_parent_id: :param db_session: :return:
ziggurat_foundations/models/services/resource_tree_postgres.py
def check_node_parent( cls, resource_id, new_parent_id, db_session=None, *args, **kwargs ): """ Checks if parent destination is valid for node :param resource_id: :param new_parent_id: :param db_session: :return: """ db_session = get_db_sessio...
def check_node_parent( cls, resource_id, new_parent_id, db_session=None, *args, **kwargs ): """ Checks if parent destination is valid for node :param resource_id: :param new_parent_id: :param db_session: :return: """ db_session = get_db_sessio...
[ "Checks", "if", "parent", "destination", "is", "valid", "for", "node" ]
ergo/ziggurat_foundations
python
https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/resource_tree_postgres.py#L342-L366
[ "def", "check_node_parent", "(", "cls", ",", "resource_id", ",", "new_parent_id", ",", "db_session", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "db_session", "=", "get_db_session", "(", "db_session", ")", "new_parent", "=", "ResourceSe...
9eeec894d08e8d7defa60ddc04b63f69cd4cbeba
train
ResourceTreeServicePostgreSQL.count_children
Counts children of resource node :param resource_id: :param db_session: :return:
ziggurat_foundations/models/services/resource_tree_postgres.py
def count_children(cls, resource_id, db_session=None, *args, **kwargs): """ Counts children of resource node :param resource_id: :param db_session: :return: """ query = db_session.query(cls.model.resource_id) query = query.filter(cls.model.parent_id == re...
def count_children(cls, resource_id, db_session=None, *args, **kwargs): """ Counts children of resource node :param resource_id: :param db_session: :return: """ query = db_session.query(cls.model.resource_id) query = query.filter(cls.model.parent_id == re...
[ "Counts", "children", "of", "resource", "node" ]
ergo/ziggurat_foundations
python
https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/resource_tree_postgres.py#L369-L379
[ "def", "count_children", "(", "cls", ",", "resource_id", ",", "db_session", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "db_session", ".", "query", "(", "cls", ".", "model", ".", "resource_id", ")", "query", "=", "...
9eeec894d08e8d7defa60ddc04b63f69cd4cbeba
train
ResourceTreeServicePostgreSQL.check_node_position
Checks if node position for given parent is valid, raises exception if this is not the case :param parent_id: :param position: :param on_same_branch: indicates that we are checking same branch :param db_session: :return:
ziggurat_foundations/models/services/resource_tree_postgres.py
def check_node_position( cls, parent_id, position, on_same_branch, db_session=None, *args, **kwargs ): """ Checks if node position for given parent is valid, raises exception if this is not the case :param parent_id: :param position: :param on_same_branch: in...
def check_node_position( cls, parent_id, position, on_same_branch, db_session=None, *args, **kwargs ): """ Checks if node position for given parent is valid, raises exception if this is not the case :param parent_id: :param position: :param on_same_branch: in...
[ "Checks", "if", "node", "position", "for", "given", "parent", "is", "valid", "raises", "exception", "if", "this", "is", "not", "the", "case" ]
ergo/ziggurat_foundations
python
https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/resource_tree_postgres.py#L382-L405
[ "def", "check_node_position", "(", "cls", ",", "parent_id", ",", "position", ",", "on_same_branch", ",", "db_session", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "db_session", "=", "get_db_session", "(", "db_session", ")", "if", "not...
9eeec894d08e8d7defa60ddc04b63f69cd4cbeba
train
egcd
Given two integers (b, n), returns (gcd(b, n), a, m) such that a*b + n*m = gcd(b, n). Adapted from several sources: https://brilliant.org/wiki/extended-euclidean-algorithm/ https://rosettacode.org/wiki/Modular_inverse https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Exte...
egcd/egcd.py
def egcd(b, n): ''' Given two integers (b, n), returns (gcd(b, n), a, m) such that a*b + n*m = gcd(b, n). Adapted from several sources: https://brilliant.org/wiki/extended-euclidean-algorithm/ https://rosettacode.org/wiki/Modular_inverse https://en.wikibooks.org/wiki/Algorithm_Imp...
def egcd(b, n): ''' Given two integers (b, n), returns (gcd(b, n), a, m) such that a*b + n*m = gcd(b, n). Adapted from several sources: https://brilliant.org/wiki/extended-euclidean-algorithm/ https://rosettacode.org/wiki/Modular_inverse https://en.wikibooks.org/wiki/Algorithm_Imp...
[ "Given", "two", "integers", "(", "b", "n", ")", "returns", "(", "gcd", "(", "b", "n", ")", "a", "m", ")", "such", "that", "a", "*", "b", "+", "n", "*", "m", "=", "gcd", "(", "b", "n", ")", ".", "Adapted", "from", "several", "sources", ":", ...
lapets/egcd
python
https://github.com/lapets/egcd/blob/44fbab4a8eb04ad198526b4f14ddce6dff2bae77/egcd/egcd.py#L16-L42
[ "def", "egcd", "(", "b", ",", "n", ")", ":", "(", "x0", ",", "x1", ",", "y0", ",", "y1", ")", "=", "(", "1", ",", "0", ",", "0", ",", "1", ")", "while", "n", "!=", "0", ":", "(", "q", ",", "b", ",", "n", ")", "=", "(", "b", "//", ...
44fbab4a8eb04ad198526b4f14ddce6dff2bae77
train
register
Add the needed transformations and supressions.
pylint_mongoengine/__init__.py
def register(linter): """Add the needed transformations and supressions. """ linter.register_checker(MongoEngineChecker(linter)) add_transform('mongoengine') add_transform('mongomotor') suppress_qs_decorator_messages(linter) suppress_fields_attrs_messages(linter)
def register(linter): """Add the needed transformations and supressions. """ linter.register_checker(MongoEngineChecker(linter)) add_transform('mongoengine') add_transform('mongomotor') suppress_qs_decorator_messages(linter) suppress_fields_attrs_messages(linter)
[ "Add", "the", "needed", "transformations", "and", "supressions", "." ]
jucacrispim/pylint-mongoengine
python
https://github.com/jucacrispim/pylint-mongoengine/blob/b873653d1224a5748f75dd507f492f8c60d95ce3/pylint_mongoengine/__init__.py#L25-L33
[ "def", "register", "(", "linter", ")", ":", "linter", ".", "register_checker", "(", "MongoEngineChecker", "(", "linter", ")", ")", "add_transform", "(", "'mongoengine'", ")", "add_transform", "(", "'mongomotor'", ")", "suppress_qs_decorator_messages", "(", "linter",...
b873653d1224a5748f75dd507f492f8c60d95ce3
train
output_as_csv
Transpose all channels and output a csv that is easier to read and do charting on :param file_name: The NEM file to process :param nmi: Which NMI to output if more than one :param output_file: Specify different output location :returns: The file that was created
nemreader/outputs.py
def output_as_csv(file_name, nmi=None, output_file=None): """ Transpose all channels and output a csv that is easier to read and do charting on :param file_name: The NEM file to process :param nmi: Which NMI to output if more than one :param output_file: Specify different output location :r...
def output_as_csv(file_name, nmi=None, output_file=None): """ Transpose all channels and output a csv that is easier to read and do charting on :param file_name: The NEM file to process :param nmi: Which NMI to output if more than one :param output_file: Specify different output location :r...
[ "Transpose", "all", "channels", "and", "output", "a", "csv", "that", "is", "easier", "to", "read", "and", "do", "charting", "on" ]
aguinane/nem-reader
python
https://github.com/aguinane/nem-reader/blob/5405a5cba4bb8ebdad05c28455d12bb34a6d3ce5/nemreader/outputs.py#L11-L51
[ "def", "output_as_csv", "(", "file_name", ",", "nmi", "=", "None", ",", "output_file", "=", "None", ")", ":", "m", "=", "read_nem_file", "(", "file_name", ")", "if", "nmi", "is", "None", ":", "nmi", "=", "list", "(", "m", ".", "readings", ".", "keys"...
5405a5cba4bb8ebdad05c28455d12bb34a6d3ce5
train
GroupService.get
Fetch row using primary key - will use existing object in session if already present :param group_id: :param db_session: :return:
ziggurat_foundations/models/services/group.py
def get(cls, group_id, db_session=None): """ Fetch row using primary key - will use existing object in session if already present :param group_id: :param db_session: :return: """ db_session = get_db_session(db_session) return db_session.query(cls....
def get(cls, group_id, db_session=None): """ Fetch row using primary key - will use existing object in session if already present :param group_id: :param db_session: :return: """ db_session = get_db_session(db_session) return db_session.query(cls....
[ "Fetch", "row", "using", "primary", "key", "-", "will", "use", "existing", "object", "in", "session", "if", "already", "present" ]
ergo/ziggurat_foundations
python
https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/group.py#L19-L29
[ "def", "get", "(", "cls", ",", "group_id", ",", "db_session", "=", "None", ")", ":", "db_session", "=", "get_db_session", "(", "db_session", ")", "return", "db_session", ".", "query", "(", "cls", ".", "model", ")", ".", "get", "(", "group_id", ")" ]
9eeec894d08e8d7defa60ddc04b63f69cd4cbeba
train
GroupService.by_group_name
fetch group by name :param group_name: :param db_session: :return:
ziggurat_foundations/models/services/group.py
def by_group_name(cls, group_name, db_session=None): """ fetch group by name :param group_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).filter(cls.model.group_name == group_name) ...
def by_group_name(cls, group_name, db_session=None): """ fetch group by name :param group_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).filter(cls.model.group_name == group_name) ...
[ "fetch", "group", "by", "name" ]
ergo/ziggurat_foundations
python
https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/group.py#L32-L42
[ "def", "by_group_name", "(", "cls", ",", "group_name", ",", "db_session", "=", "None", ")", ":", "db_session", "=", "get_db_session", "(", "db_session", ")", "query", "=", "db_session", ".", "query", "(", "cls", ".", "model", ")", ".", "filter", "(", "cl...
9eeec894d08e8d7defa60ddc04b63f69cd4cbeba
train
GroupService.get_user_paginator
returns paginator over users belonging to the group :param instance: :param page: :param item_count: :param items_per_page: :param user_ids: :param GET_params: :return:
ziggurat_foundations/models/services/group.py
def get_user_paginator( cls, instance, page=1, item_count=None, items_per_page=50, user_ids=None, GET_params=None, ): """ returns paginator over users belonging to the group :param instance: :param page: :param item_cou...
def get_user_paginator( cls, instance, page=1, item_count=None, items_per_page=50, user_ids=None, GET_params=None, ): """ returns paginator over users belonging to the group :param instance: :param page: :param item_cou...
[ "returns", "paginator", "over", "users", "belonging", "to", "the", "group" ]
ergo/ziggurat_foundations
python
https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/group.py#L45-L77
[ "def", "get_user_paginator", "(", "cls", ",", "instance", ",", "page", "=", "1", ",", "item_count", "=", "None", ",", "items_per_page", "=", "50", ",", "user_ids", "=", "None", ",", "GET_params", "=", "None", ",", ")", ":", "if", "not", "GET_params", "...
9eeec894d08e8d7defa60ddc04b63f69cd4cbeba
train
GroupService.resources_with_possible_perms
returns list of permissions and resources for this group, resource_ids restricts the search to specific resources :param instance: :param perm_names: :param resource_ids: :param resource_types: :param db_session: :return:
ziggurat_foundations/models/services/group.py
def resources_with_possible_perms( cls, instance, perm_names=None, resource_ids=None, resource_types=None, db_session=None, ): """ returns list of permissions and resources for this group, resource_ids restricts the search to specific resou...
def resources_with_possible_perms( cls, instance, perm_names=None, resource_ids=None, resource_types=None, db_session=None, ): """ returns list of permissions and resources for this group, resource_ids restricts the search to specific resou...
[ "returns", "list", "of", "permissions", "and", "resources", "for", "this", "group", "resource_ids", "restricts", "the", "search", "to", "specific", "resources" ]
ergo/ziggurat_foundations
python
https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/group.py#L80-L144
[ "def", "resources_with_possible_perms", "(", "cls", ",", "instance", ",", "perm_names", "=", "None", ",", "resource_ids", "=", "None", ",", "resource_types", "=", "None", ",", "db_session", "=", "None", ",", ")", ":", "db_session", "=", "get_db_session", "(", ...
9eeec894d08e8d7defa60ddc04b63f69cd4cbeba
train
create_pool
创建支持上下文管理的pool
aiosqlite3/pool.py
def create_pool( database, minsize=1, maxsize=10, echo=False, loop=None, **kwargs ): """ 创建支持上下文管理的pool """ coro = _create_pool( database=database, minsize=minsize, maxsize=maxsize, echo=echo, loop=loop, **kw...
def create_pool( database, minsize=1, maxsize=10, echo=False, loop=None, **kwargs ): """ 创建支持上下文管理的pool """ coro = _create_pool( database=database, minsize=minsize, maxsize=maxsize, echo=echo, loop=loop, **kw...
[ "创建支持上下文管理的pool" ]
zeromake/aiosqlite3
python
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/pool.py#L14-L33
[ "def", "create_pool", "(", "database", ",", "minsize", "=", "1", ",", "maxsize", "=", "10", ",", "echo", "=", "False", ",", "loop", "=", "None", ",", "*", "*", "kwargs", ")", ":", "coro", "=", "_create_pool", "(", "database", "=", "database", ",", ...
1a74a062507e2df8f833a70885e69dca0ab3e7e7
train
Pool.wait_closed
Wait for closing all pool's connections.
aiosqlite3/pool.py
def wait_closed(self): """ Wait for closing all pool's connections. """ if self._closed: return if not self._closing: raise RuntimeError( ".wait_closed() should be called " "after .close()" ) while self....
def wait_closed(self): """ Wait for closing all pool's connections. """ if self._closed: return if not self._closing: raise RuntimeError( ".wait_closed() should be called " "after .close()" ) while self....
[ "Wait", "for", "closing", "all", "pool", "s", "connections", "." ]
zeromake/aiosqlite3
python
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/pool.py#L169-L192
[ "def", "wait_closed", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "return", "if", "not", "self", ".", "_closing", ":", "raise", "RuntimeError", "(", "\".wait_closed() should be called \"", "\"after .close()\"", ")", "while", "self", ".", "_free", ...
1a74a062507e2df8f833a70885e69dca0ab3e7e7
train
Pool.sync_close
同步关闭
aiosqlite3/pool.py
def sync_close(self): """ 同步关闭 """ if self._closed: return while self._free: conn = self._free.popleft() if not conn.closed: # pragma: no cover conn.sync_close() for conn in self._used: if not...
def sync_close(self): """ 同步关闭 """ if self._closed: return while self._free: conn = self._free.popleft() if not conn.closed: # pragma: no cover conn.sync_close() for conn in self._used: if not...
[ "同步关闭" ]
zeromake/aiosqlite3
python
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/pool.py#L194-L211
[ "def", "sync_close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "return", "while", "self", ".", "_free", ":", "conn", "=", "self", ".", "_free", ".", "popleft", "(", ")", "if", "not", "conn", ".", "closed", ":", "# pragma: no cover", "...
1a74a062507e2df8f833a70885e69dca0ab3e7e7
train
Pool._fill_free_pool
iterate over free connections and remove timeouted ones
aiosqlite3/pool.py
def _fill_free_pool(self, override_min): """ iterate over free connections and remove timeouted ones """ while self.size < self.minsize: self._acquiring += 1 try: conn = yield from connect( database=self._database, ...
def _fill_free_pool(self, override_min): """ iterate over free connections and remove timeouted ones """ while self.size < self.minsize: self._acquiring += 1 try: conn = yield from connect( database=self._database, ...
[ "iterate", "over", "free", "connections", "and", "remove", "timeouted", "ones" ]
zeromake/aiosqlite3
python
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/pool.py#L242-L274
[ "def", "_fill_free_pool", "(", "self", ",", "override_min", ")", ":", "while", "self", ".", "size", "<", "self", ".", "minsize", ":", "self", ".", "_acquiring", "+=", "1", "try", ":", "conn", "=", "yield", "from", "connect", "(", "database", "=", "self...
1a74a062507e2df8f833a70885e69dca0ab3e7e7
train
FixedFunctionManager.add_function
Adds the function to the list of registered functions.
src/pyws/functions/managers.py
def add_function(self, function): """ Adds the function to the list of registered functions. """ function = self.build_function(function) if function.name in self.functions: raise FunctionAlreadyRegistered(function.name) self.functions[function.name] = functio...
def add_function(self, function): """ Adds the function to the list of registered functions. """ function = self.build_function(function) if function.name in self.functions: raise FunctionAlreadyRegistered(function.name) self.functions[function.name] = functio...
[ "Adds", "the", "function", "to", "the", "list", "of", "registered", "functions", "." ]
stepank/pyws
python
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/managers.py#L44-L51
[ "def", "add_function", "(", "self", ",", "function", ")", ":", "function", "=", "self", ".", "build_function", "(", "function", ")", "if", "function", ".", "name", "in", "self", ".", "functions", ":", "raise", "FunctionAlreadyRegistered", "(", "function", "....
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
train
FixedFunctionManager.get_one
Returns a function if it is registered, the context is ignored.
src/pyws/functions/managers.py
def get_one(self, context, name): """ Returns a function if it is registered, the context is ignored. """ try: return self.functions[name] except KeyError: raise FunctionNotFound(name)
def get_one(self, context, name): """ Returns a function if it is registered, the context is ignored. """ try: return self.functions[name] except KeyError: raise FunctionNotFound(name)
[ "Returns", "a", "function", "if", "it", "is", "registered", "the", "context", "is", "ignored", "." ]
stepank/pyws
python
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/managers.py#L53-L60
[ "def", "get_one", "(", "self", ",", "context", ",", "name", ")", ":", "try", ":", "return", "self", ".", "functions", "[", "name", "]", "except", "KeyError", ":", "raise", "FunctionNotFound", "(", "name", ")" ]
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
train
subfield_get
Verbatim copy from: https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38
waldur_core/core/monkeypatch.py
def subfield_get(self, obj, type=None): """ Verbatim copy from: https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38 """ if obj is None: return self return obj.__dict__[self.field.name]
def subfield_get(self, obj, type=None): """ Verbatim copy from: https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38 """ if obj is None: return self return obj.__dict__[self.field.name]
[ "Verbatim", "copy", "from", ":", "https", ":", "//", "github", ".", "com", "/", "django", "/", "django", "/", "blob", "/", "1", ".", "9", ".", "13", "/", "django", "/", "db", "/", "models", "/", "fields", "/", "subclassing", ".", "py#L38" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/monkeypatch.py#L14-L21
[ "def", "subfield_get", "(", "self", ",", "obj", ",", "type", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "return", "self", "return", "obj", ".", "__dict__", "[", "self", ".", "field", ".", "name", "]" ]
d6c17a9592bb6c49c33567542eef8d099605a46a
train
GenericKeyMixin._preprocess_kwargs
Replace generic key related attribute with filters by object_id and content_type fields
waldur_core/core/managers.py
def _preprocess_kwargs(self, initial_kwargs): """ Replace generic key related attribute with filters by object_id and content_type fields """ kwargs = initial_kwargs.copy() generic_key_related_kwargs = self._get_generic_key_related_kwargs(initial_kwargs) for key, value in generic_key_rel...
def _preprocess_kwargs(self, initial_kwargs): """ Replace generic key related attribute with filters by object_id and content_type fields """ kwargs = initial_kwargs.copy() generic_key_related_kwargs = self._get_generic_key_related_kwargs(initial_kwargs) for key, value in generic_key_rel...
[ "Replace", "generic", "key", "related", "attribute", "with", "filters", "by", "object_id", "and", "content_type", "fields" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/managers.py#L29-L44
[ "def", "_preprocess_kwargs", "(", "self", ",", "initial_kwargs", ")", ":", "kwargs", "=", "initial_kwargs", ".", "copy", "(", ")", "generic_key_related_kwargs", "=", "self", ".", "_get_generic_key_related_kwargs", "(", "initial_kwargs", ")", "for", "key", ",", "va...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
categorize
:param data: :param col_name: :param new_col_name: :param categories: :param max_categories: max proportion threshold of categories :return: new categories :rtype dict:
skdata/cleaning.py
def categorize( data, col_name: str = None, new_col_name: str = None, categories: dict = None, max_categories: float = 0.15 ): """ :param data: :param col_name: :param new_col_name: :param categories: :param max_categories: max proportion threshold of categories :return: new categori...
def categorize( data, col_name: str = None, new_col_name: str = None, categories: dict = None, max_categories: float = 0.15 ): """ :param data: :param col_name: :param new_col_name: :param categories: :param max_categories: max proportion threshold of categories :return: new categori...
[ ":", "param", "data", ":", ":", "param", "col_name", ":", ":", "param", "new_col_name", ":", ":", "param", "categories", ":", ":", "param", "max_categories", ":", "max", "proportion", "threshold", "of", "categories", ":", "return", ":", "new", "categories", ...
OpenDataScienceLab/skdata
python
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/cleaning.py#L4-L57
[ "def", "categorize", "(", "data", ",", "col_name", ":", "str", "=", "None", ",", "new_col_name", ":", "str", "=", "None", ",", "categories", ":", "dict", "=", "None", ",", "max_categories", ":", "float", "=", "0.15", ")", ":", "_categories", "=", "{", ...
34f06845a944ff4f048b55c7babdd8420f71a6b9
train
dropna
Remove columns with more NA values than threshold level :param data: :param axis: Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0), and the second running horizontally ...
skdata/cleaning.py
def dropna(data: pd.DataFrame, axis: int, **params): """ Remove columns with more NA values than threshold level :param data: :param axis: Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding axes: the first running vertically downwards...
def dropna(data: pd.DataFrame, axis: int, **params): """ Remove columns with more NA values than threshold level :param data: :param axis: Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding axes: the first running vertically downwards...
[ "Remove", "columns", "with", "more", "NA", "values", "than", "threshold", "level" ]
OpenDataScienceLab/skdata
python
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/cleaning.py#L60-L78
[ "def", "dropna", "(", "data", ":", "pd", ".", "DataFrame", ",", "axis", ":", "int", ",", "*", "*", "params", ")", ":", "if", "axis", "==", "0", ":", "dropna_rows", "(", "data", "=", "data", ",", "*", "*", "params", ")", "else", ":", "dropna_colum...
34f06845a944ff4f048b55c7babdd8420f71a6b9
train
dropna_columns
Remove columns with more NA values than threshold level :param data: :param max_na_values: proportion threshold of max na values :return:
skdata/cleaning.py
def dropna_columns(data: pd.DataFrame, max_na_values: int=0.15): """ Remove columns with more NA values than threshold level :param data: :param max_na_values: proportion threshold of max na values :return: """ size = data.shape[0] df_na = (data.isnull().sum()/size) >= max_na_values ...
def dropna_columns(data: pd.DataFrame, max_na_values: int=0.15): """ Remove columns with more NA values than threshold level :param data: :param max_na_values: proportion threshold of max na values :return: """ size = data.shape[0] df_na = (data.isnull().sum()/size) >= max_na_values ...
[ "Remove", "columns", "with", "more", "NA", "values", "than", "threshold", "level" ]
OpenDataScienceLab/skdata
python
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/cleaning.py#L81-L92
[ "def", "dropna_columns", "(", "data", ":", "pd", ".", "DataFrame", ",", "max_na_values", ":", "int", "=", "0.15", ")", ":", "size", "=", "data", ".", "shape", "[", "0", "]", "df_na", "=", "(", "data", ".", "isnull", "(", ")", ".", "sum", "(", ")"...
34f06845a944ff4f048b55c7babdd8420f71a6b9
train
dropna_rows
Remove columns with more NA values than threshold level :param data: :param columns_name: :return:
skdata/cleaning.py
def dropna_rows(data: pd.DataFrame, columns_name: str=None): """ Remove columns with more NA values than threshold level :param data: :param columns_name: :return: """ params = {} if columns_name is not None: params.update({'subset': columns_name.split(',')}) data.dropna(in...
def dropna_rows(data: pd.DataFrame, columns_name: str=None): """ Remove columns with more NA values than threshold level :param data: :param columns_name: :return: """ params = {} if columns_name is not None: params.update({'subset': columns_name.split(',')}) data.dropna(in...
[ "Remove", "columns", "with", "more", "NA", "values", "than", "threshold", "level" ]
OpenDataScienceLab/skdata
python
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/cleaning.py#L95-L107
[ "def", "dropna_rows", "(", "data", ":", "pd", ".", "DataFrame", ",", "columns_name", ":", "str", "=", "None", ")", ":", "params", "=", "{", "}", "if", "columns_name", "is", "not", "None", ":", "params", ".", "update", "(", "{", "'subset'", ":", "colu...
34f06845a944ff4f048b55c7babdd8420f71a6b9
train
drop_columns_with_unique_values
Remove columns when the proportion of the total of unique values is more than the max_unique_values threshold, just for columns with type as object or category :param data: :param max_unique_values: :return:
skdata/cleaning.py
def drop_columns_with_unique_values( data: pd.DataFrame, max_unique_values: int = 0.25 ): """ Remove columns when the proportion of the total of unique values is more than the max_unique_values threshold, just for columns with type as object or category :param data: :param max_unique_values...
def drop_columns_with_unique_values( data: pd.DataFrame, max_unique_values: int = 0.25 ): """ Remove columns when the proportion of the total of unique values is more than the max_unique_values threshold, just for columns with type as object or category :param data: :param max_unique_values...
[ "Remove", "columns", "when", "the", "proportion", "of", "the", "total", "of", "unique", "values", "is", "more", "than", "the", "max_unique_values", "threshold", "just", "for", "columns", "with", "type", "as", "object", "or", "category" ]
OpenDataScienceLab/skdata
python
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/cleaning.py#L110-L130
[ "def", "drop_columns_with_unique_values", "(", "data", ":", "pd", ".", "DataFrame", ",", "max_unique_values", ":", "int", "=", "0.25", ")", ":", "size", "=", "data", ".", "shape", "[", "0", "]", "df_uv", "=", "data", ".", "apply", "(", "lambda", "se", ...
34f06845a944ff4f048b55c7babdd8420f71a6b9
train
QuotaViewSet.list
To get an actual value for object quotas limit and usage issue a **GET** request against */api/<objects>/*. To get all quotas visible to the user issue a **GET** request against */api/quotas/*
waldur_core/quotas/views.py
def list(self, request, *args, **kwargs): """ To get an actual value for object quotas limit and usage issue a **GET** request against */api/<objects>/*. To get all quotas visible to the user issue a **GET** request against */api/quotas/* """ return super(QuotaViewSet, self).lis...
def list(self, request, *args, **kwargs): """ To get an actual value for object quotas limit and usage issue a **GET** request against */api/<objects>/*. To get all quotas visible to the user issue a **GET** request against */api/quotas/* """ return super(QuotaViewSet, self).lis...
[ "To", "get", "an", "actual", "value", "for", "object", "quotas", "limit", "and", "usage", "issue", "a", "**", "GET", "**", "request", "against", "*", "/", "api", "/", "<objects", ">", "/", "*", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/views.py#L27-L33
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "QuotaViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
d6c17a9592bb6c49c33567542eef8d099605a46a
train
QuotaViewSet.retrieve
To set quota limit issue a **PUT** request against */api/quotas/<quota uuid>** with limit values. Please note that if a quota is a cache of a backend quota (e.g. 'storage' size of an OpenStack tenant), it will be impossible to modify it through */api/quotas/<quota uuid>** endpoint. Example of ...
waldur_core/quotas/views.py
def retrieve(self, request, *args, **kwargs): """ To set quota limit issue a **PUT** request against */api/quotas/<quota uuid>** with limit values. Please note that if a quota is a cache of a backend quota (e.g. 'storage' size of an OpenStack tenant), it will be impossible to modify it ...
def retrieve(self, request, *args, **kwargs): """ To set quota limit issue a **PUT** request against */api/quotas/<quota uuid>** with limit values. Please note that if a quota is a cache of a backend quota (e.g. 'storage' size of an OpenStack tenant), it will be impossible to modify it ...
[ "To", "set", "quota", "limit", "issue", "a", "**", "PUT", "**", "request", "against", "*", "/", "api", "/", "quotas", "/", "<quota", "uuid", ">", "**", "with", "limit", "values", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/views.py#L35-L71
[ "def", "retrieve", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "QuotaViewSet", ",", "self", ")", ".", "retrieve", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
d6c17a9592bb6c49c33567542eef8d099605a46a
train
QuotaViewSet.history
Historical data endpoints could be available for any objects (currently implemented for quotas and events count). The data is available at *<object_endpoint>/history/*, for example: */api/quotas/<uuid>/history/*. There are two ways to define datetime points for historical data. 1. Send...
waldur_core/quotas/views.py
def history(self, request, uuid=None): """ Historical data endpoints could be available for any objects (currently implemented for quotas and events count). The data is available at *<object_endpoint>/history/*, for example: */api/quotas/<uuid>/history/*. There are two ways to d...
def history(self, request, uuid=None): """ Historical data endpoints could be available for any objects (currently implemented for quotas and events count). The data is available at *<object_endpoint>/history/*, for example: */api/quotas/<uuid>/history/*. There are two ways to d...
[ "Historical", "data", "endpoints", "could", "be", "available", "for", "any", "objects", "(", "currently", "implemented", "for", "quotas", "and", "events", "count", ")", ".", "The", "data", "is", "available", "at", "*", "<object_endpoint", ">", "/", "history", ...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/views.py#L96-L151
[ "def", "history", "(", "self", ",", "request", ",", "uuid", "=", "None", ")", ":", "mapped", "=", "{", "'start'", ":", "request", ".", "query_params", ".", "get", "(", "'start'", ")", ",", "'end'", ":", "request", ".", "query_params", ".", "get", "("...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
GenericRelatedField._get_url
Gets object url
waldur_core/core/serializers.py
def _get_url(self, obj): """ Gets object url """ format_kwargs = { 'app_label': obj._meta.app_label, } try: format_kwargs['model_name'] = getattr(obj.__class__, 'get_url_name')() except AttributeError: format_kwargs['model_name'...
def _get_url(self, obj): """ Gets object url """ format_kwargs = { 'app_label': obj._meta.app_label, } try: format_kwargs['model_name'] = getattr(obj.__class__, 'get_url_name')() except AttributeError: format_kwargs['model_name'...
[ "Gets", "object", "url" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/serializers.py#L82-L93
[ "def", "_get_url", "(", "self", ",", "obj", ")", ":", "format_kwargs", "=", "{", "'app_label'", ":", "obj", ".", "_meta", ".", "app_label", ",", "}", "try", ":", "format_kwargs", "[", "'model_name'", "]", "=", "getattr", "(", "obj", ".", "__class__", "...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
GenericRelatedField.to_representation
Serializes any object to his url representation
waldur_core/core/serializers.py
def to_representation(self, obj): """ Serializes any object to his url representation """ kwargs = None for field in self.lookup_fields: if hasattr(obj, field): kwargs = {field: getattr(obj, field)} break if kwargs is None: ...
def to_representation(self, obj): """ Serializes any object to his url representation """ kwargs = None for field in self.lookup_fields: if hasattr(obj, field): kwargs = {field: getattr(obj, field)} break if kwargs is None: ...
[ "Serializes", "any", "object", "to", "his", "url", "representation" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/serializers.py#L101-L113
[ "def", "to_representation", "(", "self", ",", "obj", ")", ":", "kwargs", "=", "None", "for", "field", "in", "self", ".", "lookup_fields", ":", "if", "hasattr", "(", "obj", ",", "field", ")", ":", "kwargs", "=", "{", "field", ":", "getattr", "(", "obj...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
GenericRelatedField.to_internal_value
Restores model instance from its url
waldur_core/core/serializers.py
def to_internal_value(self, data): """ Restores model instance from its url """ if not data: return None request = self._get_request() user = request.user try: obj = core_utils.instance_from_url(data, user=user) model = obj.__cl...
def to_internal_value(self, data): """ Restores model instance from its url """ if not data: return None request = self._get_request() user = request.user try: obj = core_utils.instance_from_url(data, user=user) model = obj.__cl...
[ "Restores", "model", "instance", "from", "its", "url" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/serializers.py#L115-L132
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "if", "not", "data", ":", "return", "None", "request", "=", "self", ".", "_get_request", "(", ")", "user", "=", "request", ".", "user", "try", ":", "obj", "=", "core_utils", ".", "instance...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
TimestampIntervalSerializer.validate
Check that the start is before the end.
waldur_core/core/serializers.py
def validate(self, data): """ Check that the start is before the end. """ if 'start' in data and 'end' in data and data['start'] >= data['end']: raise serializers.ValidationError(_('End must occur after start.')) return data
def validate(self, data): """ Check that the start is before the end. """ if 'start' in data and 'end' in data and data['start'] >= data['end']: raise serializers.ValidationError(_('End must occur after start.')) return data
[ "Check", "that", "the", "start", "is", "before", "the", "end", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/serializers.py#L373-L379
[ "def", "validate", "(", "self", ",", "data", ")", ":", "if", "'start'", "in", "data", "and", "'end'", "in", "data", "and", "data", "[", "'start'", "]", ">=", "data", "[", "'end'", "]", ":", "raise", "serializers", ".", "ValidationError", "(", "_", "(...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
send_task
A helper function to deal with waldur_core "high-level" tasks. Define high-level task with explicit name using a pattern: waldur_core.<app_label>.<task_name> .. code-block:: python @shared_task(name='waldur_core.openstack.provision_instance') def provision_instance_fn(in...
waldur_core/core/tasks.py
def send_task(app_label, task_name): """ A helper function to deal with waldur_core "high-level" tasks. Define high-level task with explicit name using a pattern: waldur_core.<app_label>.<task_name> .. code-block:: python @shared_task(name='waldur_core.openstack.provision_instan...
def send_task(app_label, task_name): """ A helper function to deal with waldur_core "high-level" tasks. Define high-level task with explicit name using a pattern: waldur_core.<app_label>.<task_name> .. code-block:: python @shared_task(name='waldur_core.openstack.provision_instan...
[ "A", "helper", "function", "to", "deal", "with", "waldur_core", "high", "-", "level", "tasks", ".", "Define", "high", "-", "level", "task", "with", "explicit", "name", "using", "a", "pattern", ":", "waldur_core", ".", "<app_label", ">", ".", "<task_name", ...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/tasks.py#L54-L80
[ "def", "send_task", "(", "app_label", ",", "task_name", ")", ":", "def", "delay", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "full_task_name", "=", "'waldur_core.%s.%s'", "%", "(", "app_label", ",", "task_name", ")", "send_celery_task", "(", "ful...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
log_celery_task
Add description to celery log output
waldur_core/core/tasks.py
def log_celery_task(request): """ Add description to celery log output """ task = request.task description = None if isinstance(task, Task): try: description = task.get_description(*request.args, **request.kwargs) except NotImplementedError: pass except Ex...
def log_celery_task(request): """ Add description to celery log output """ task = request.task description = None if isinstance(task, Task): try: description = task.get_description(*request.args, **request.kwargs) except NotImplementedError: pass except Ex...
[ "Add", "description", "to", "celery", "log", "output" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/tasks.py#L440-L458
[ "def", "log_celery_task", "(", "request", ")", ":", "task", "=", "request", ".", "task", "description", "=", "None", "if", "isinstance", "(", "task", ",", "Task", ")", ":", "try", ":", "description", "=", "task", ".", "get_description", "(", "*", "reques...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
Task.run
Deserialize input data and start backend operation execution
waldur_core/core/tasks.py
def run(self, serialized_instance, *args, **kwargs): """ Deserialize input data and start backend operation execution """ try: instance = utils.deserialize_instance(serialized_instance) except ObjectDoesNotExist: message = ('Cannot restore instance from serialized object ...
def run(self, serialized_instance, *args, **kwargs): """ Deserialize input data and start backend operation execution """ try: instance = utils.deserialize_instance(serialized_instance) except ObjectDoesNotExist: message = ('Cannot restore instance from serialized object ...
[ "Deserialize", "input", "data", "and", "start", "backend", "operation", "execution" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/tasks.py#L97-L114
[ "def", "run", "(", "self", ",", "serialized_instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "instance", "=", "utils", ".", "deserialize_instance", "(", "serialized_instance", ")", "except", "ObjectDoesNotExist", ":", "message", "=...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
BackgroundTask.is_previous_task_processing
Return True if exist task that is equal to current and is uncompleted
waldur_core/core/tasks.py
def is_previous_task_processing(self, *args, **kwargs): """ Return True if exist task that is equal to current and is uncompleted """ app = self._get_app() inspect = app.control.inspect() active = inspect.active() or {} scheduled = inspect.scheduled() or {} reserved = ins...
def is_previous_task_processing(self, *args, **kwargs): """ Return True if exist task that is equal to current and is uncompleted """ app = self._get_app() inspect = app.control.inspect() active = inspect.active() or {} scheduled = inspect.scheduled() or {} reserved = ins...
[ "Return", "True", "if", "exist", "task", "that", "is", "equal", "to", "current", "and", "is", "uncompleted" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/tasks.py#L353-L361
[ "def", "is_previous_task_processing", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "app", "=", "self", ".", "_get_app", "(", ")", "inspect", "=", "app", ".", "control", ".", "inspect", "(", ")", "active", "=", "inspect", ".", "ac...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
BackgroundTask.apply_async
Do not run background task if previous task is uncompleted
waldur_core/core/tasks.py
def apply_async(self, args=None, kwargs=None, **options): """ Do not run background task if previous task is uncompleted """ if self.is_previous_task_processing(*args, **kwargs): message = 'Background task %s was not scheduled, because its predecessor is not completed yet.' % self.name ...
def apply_async(self, args=None, kwargs=None, **options): """ Do not run background task if previous task is uncompleted """ if self.is_previous_task_processing(*args, **kwargs): message = 'Background task %s was not scheduled, because its predecessor is not completed yet.' % self.name ...
[ "Do", "not", "run", "background", "task", "if", "previous", "task", "is", "uncompleted" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/tasks.py#L363-L370
[ "def", "apply_async", "(", "self", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "*", "*", "options", ")", ":", "if", "self", ".", "is_previous_task_processing", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "message", "=", "'Back...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
PenalizedBackgroundTask._get_cache_key
Returns key to be used in cache
waldur_core/core/tasks.py
def _get_cache_key(self, args, kwargs): """ Returns key to be used in cache """ hash_input = json.dumps({'name': self.name, 'args': args, 'kwargs': kwargs}, sort_keys=True) # md5 is used for internal caching, not need to care about security return hashlib.md5(hash_input).hexdigest()
def _get_cache_key(self, args, kwargs): """ Returns key to be used in cache """ hash_input = json.dumps({'name': self.name, 'args': args, 'kwargs': kwargs}, sort_keys=True) # md5 is used for internal caching, not need to care about security return hashlib.md5(hash_input).hexdigest()
[ "Returns", "key", "to", "be", "used", "in", "cache" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/tasks.py#L396-L400
[ "def", "_get_cache_key", "(", "self", ",", "args", ",", "kwargs", ")", ":", "hash_input", "=", "json", ".", "dumps", "(", "{", "'name'", ":", "self", ".", "name", ",", "'args'", ":", "args", ",", "'kwargs'", ":", "kwargs", "}", ",", "sort_keys", "=",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
PenalizedBackgroundTask.apply_async
Checks whether task must be skipped and decreases the counter in that case.
waldur_core/core/tasks.py
def apply_async(self, args=None, kwargs=None, **options): """ Checks whether task must be skipped and decreases the counter in that case. """ key = self._get_cache_key(args, kwargs) counter, penalty = cache.get(key, (0, 0)) if not counter: return super(Penaliz...
def apply_async(self, args=None, kwargs=None, **options): """ Checks whether task must be skipped and decreases the counter in that case. """ key = self._get_cache_key(args, kwargs) counter, penalty = cache.get(key, (0, 0)) if not counter: return super(Penaliz...
[ "Checks", "whether", "task", "must", "be", "skipped", "and", "decreases", "the", "counter", "in", "that", "case", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/tasks.py#L402-L413
[ "def", "apply_async", "(", "self", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "*", "*", "options", ")", ":", "key", "=", "self", ".", "_get_cache_key", "(", "args", ",", "kwargs", ")", "counter", ",", "penalty", "=", "cache", ".", "...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
PenalizedBackgroundTask.on_failure
Increases penalty for the task and resets the counter.
waldur_core/core/tasks.py
def on_failure(self, exc, task_id, args, kwargs, einfo): """ Increases penalty for the task and resets the counter. """ key = self._get_cache_key(args, kwargs) _, penalty = cache.get(key, (0, 0)) if penalty < self.MAX_PENALTY: penalty += 1 logger.debu...
def on_failure(self, exc, task_id, args, kwargs, einfo): """ Increases penalty for the task and resets the counter. """ key = self._get_cache_key(args, kwargs) _, penalty = cache.get(key, (0, 0)) if penalty < self.MAX_PENALTY: penalty += 1 logger.debu...
[ "Increases", "penalty", "for", "the", "task", "and", "resets", "the", "counter", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/tasks.py#L415-L426
[ "def", "on_failure", "(", "self", ",", "exc", ",", "task_id", ",", "args", ",", "kwargs", ",", "einfo", ")", ":", "key", "=", "self", ".", "_get_cache_key", "(", "args", ",", "kwargs", ")", "_", ",", "penalty", "=", "cache", ".", "get", "(", "key",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
PenalizedBackgroundTask.on_success
Clears cache for the task.
waldur_core/core/tasks.py
def on_success(self, retval, task_id, args, kwargs): """ Clears cache for the task. """ key = self._get_cache_key(args, kwargs) if cache.get(key) is not None: cache.delete(key) logger.debug('Penalty for the task %s has been removed.' % self.name) ...
def on_success(self, retval, task_id, args, kwargs): """ Clears cache for the task. """ key = self._get_cache_key(args, kwargs) if cache.get(key) is not None: cache.delete(key) logger.debug('Penalty for the task %s has been removed.' % self.name) ...
[ "Clears", "cache", "for", "the", "task", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/tasks.py#L428-L437
[ "def", "on_success", "(", "self", ",", "retval", ",", "task_id", ",", "args", ",", "kwargs", ")", ":", "key", "=", "self", ".", "_get_cache_key", "(", "args", ",", "kwargs", ")", "if", "cache", ".", "get", "(", "key", ")", "is", "not", "None", ":",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
log_backend_action
Logging for backend method. Expects django model instance as first argument.
waldur_core/structure/__init__.py
def log_backend_action(action=None): """ Logging for backend method. Expects django model instance as first argument. """ def decorator(func): @functools.wraps(func) def wrapped(self, instance, *args, **kwargs): action_name = func.func_name.replace('_', ' ') if action is Non...
def log_backend_action(action=None): """ Logging for backend method. Expects django model instance as first argument. """ def decorator(func): @functools.wraps(func) def wrapped(self, instance, *args, **kwargs): action_name = func.func_name.replace('_', ' ') if action is Non...
[ "Logging", "for", "backend", "method", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L417-L433
[ "def", "log_backend_action", "(", "action", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "self", ",", "instance", ",", "*", "args", ",", "*", "*", "kwargs",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SupportedServices.get_services
Get a list of services endpoints. { "Oracle": "/api/oracle/", "OpenStack": "/api/openstack/", "GitLab": "/api/gitlab/", "DigitalOcean": "/api/digitalocean/" }
waldur_core/structure/__init__.py
def get_services(cls, request=None): """ Get a list of services endpoints. { "Oracle": "/api/oracle/", "OpenStack": "/api/openstack/", "GitLab": "/api/gitlab/", "DigitalOcean": "/api/digitalocean/" } """ retu...
def get_services(cls, request=None): """ Get a list of services endpoints. { "Oracle": "/api/oracle/", "OpenStack": "/api/openstack/", "GitLab": "/api/gitlab/", "DigitalOcean": "/api/digitalocean/" } """ retu...
[ "Get", "a", "list", "of", "services", "endpoints", ".", "{", "Oracle", ":", "/", "api", "/", "oracle", "/", "OpenStack", ":", "/", "api", "/", "openstack", "/", "GitLab", ":", "/", "api", "/", "gitlab", "/", "DigitalOcean", ":", "/", "api", "/", "d...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L161-L171
[ "def", "get_services", "(", "cls", ",", "request", "=", "None", ")", ":", "return", "{", "service", "[", "'name'", "]", ":", "reverse", "(", "service", "[", "'list_view'", "]", ",", "request", "=", "request", ")", "for", "service", "in", "cls", ".", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SupportedServices.get_resources
Get a list of resources endpoints. { "DigitalOcean.Droplet": "/api/digitalocean-droplets/", "Oracle.Database": "/api/oracle-databases/", "GitLab.Group": "/api/gitlab-groups/", "GitLab.Project": "/api/gitlab-projects/" }
waldur_core/structure/__init__.py
def get_resources(cls, request=None): """ Get a list of resources endpoints. { "DigitalOcean.Droplet": "/api/digitalocean-droplets/", "Oracle.Database": "/api/oracle-databases/", "GitLab.Group": "/api/gitlab-groups/", "GitLab.Project": ...
def get_resources(cls, request=None): """ Get a list of resources endpoints. { "DigitalOcean.Droplet": "/api/digitalocean-droplets/", "Oracle.Database": "/api/oracle-databases/", "GitLab.Group": "/api/gitlab-groups/", "GitLab.Project": ...
[ "Get", "a", "list", "of", "resources", "endpoints", ".", "{", "DigitalOcean", ".", "Droplet", ":", "/", "api", "/", "digitalocean", "-", "droplets", "/", "Oracle", ".", "Database", ":", "/", "api", "/", "oracle", "-", "databases", "/", "GitLab", ".", "...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L184-L195
[ "def", "get_resources", "(", "cls", ",", "request", "=", "None", ")", ":", "return", "{", "'.'", ".", "join", "(", "[", "service", "[", "'name'", "]", ",", "resource", "[", "'name'", "]", "]", ")", ":", "reverse", "(", "resource", "[", "'list_view'",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SupportedServices.get_services_with_resources
Get a list of services and resources endpoints. { ... "GitLab": { "url": "/api/gitlab/", "service_project_link_url": "/api/gitlab-service-project-link/", "resources": { "Project": "/api/gitlab...
waldur_core/structure/__init__.py
def get_services_with_resources(cls, request=None): """ Get a list of services and resources endpoints. { ... "GitLab": { "url": "/api/gitlab/", "service_project_link_url": "/api/gitlab-service-project-link/", ...
def get_services_with_resources(cls, request=None): """ Get a list of services and resources endpoints. { ... "GitLab": { "url": "/api/gitlab/", "service_project_link_url": "/api/gitlab-service-project-link/", ...
[ "Get", "a", "list", "of", "services", "and", "resources", "endpoints", ".", "{", "...", "GitLab", ":", "{", "url", ":", "/", "api", "/", "gitlab", "/", "service_project_link_url", ":", "/", "api", "/", "gitlab", "-", "service", "-", "project", "-", "li...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L216-L248
[ "def", "get_services_with_resources", "(", "cls", ",", "request", "=", "None", ")", ":", "from", "django", ".", "apps", "import", "apps", "data", "=", "{", "}", "for", "service", "in", "cls", ".", "_registry", ".", "values", "(", ")", ":", "service_model...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SupportedServices.get_service_models
Get a list of service models. { ... 'gitlab': { "service": nodeconductor_gitlab.models.GitLabService, "service_project_link": nodeconductor_gitlab.models.GitLabServiceProjectLink, "resources": [ ...
waldur_core/structure/__init__.py
def get_service_models(cls): """ Get a list of service models. { ... 'gitlab': { "service": nodeconductor_gitlab.models.GitLabService, "service_project_link": nodeconductor_gitlab.models.GitLabServiceProjectLink, ...
def get_service_models(cls): """ Get a list of service models. { ... 'gitlab': { "service": nodeconductor_gitlab.models.GitLabService, "service_project_link": nodeconductor_gitlab.models.GitLabServiceProjectLink, ...
[ "Get", "a", "list", "of", "service", "models", ".", "{", "...", "gitlab", ":", "{", "service", ":", "nodeconductor_gitlab", ".", "models", ".", "GitLabService", "service_project_link", ":", "nodeconductor_gitlab", ".", "models", ".", "GitLabServiceProjectLink", "r...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L252-L281
[ "def", "get_service_models", "(", "cls", ")", ":", "from", "django", ".", "apps", "import", "apps", "data", "=", "{", "}", "for", "key", ",", "service", "in", "cls", ".", "_registry", ".", "items", "(", ")", ":", "service_model", "=", "apps", ".", "g...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SupportedServices.get_resource_models
Get a list of resource models. { 'DigitalOcean.Droplet': waldur_digitalocean.models.Droplet, 'JIRA.Project': waldur_jira.models.Project, 'OpenStack.Tenant': waldur_openstack.models.Tenant }
waldur_core/structure/__init__.py
def get_resource_models(cls): """ Get a list of resource models. { 'DigitalOcean.Droplet': waldur_digitalocean.models.Droplet, 'JIRA.Project': waldur_jira.models.Project, 'OpenStack.Tenant': waldur_openstack.models.Tenant } """ ...
def get_resource_models(cls): """ Get a list of resource models. { 'DigitalOcean.Droplet': waldur_digitalocean.models.Droplet, 'JIRA.Project': waldur_jira.models.Project, 'OpenStack.Tenant': waldur_openstack.models.Tenant } """ ...
[ "Get", "a", "list", "of", "resource", "models", ".", "{", "DigitalOcean", ".", "Droplet", ":", "waldur_digitalocean", ".", "models", ".", "Droplet", "JIRA", ".", "Project", ":", "waldur_jira", ".", "models", ".", "Project", "OpenStack", ".", "Tenant", ":", ...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L285-L298
[ "def", "get_resource_models", "(", "cls", ")", ":", "from", "django", ".", "apps", "import", "apps", "return", "{", "'.'", ".", "join", "(", "[", "service", "[", "'name'", "]", ",", "attrs", "[", "'name'", "]", "]", ")", ":", "apps", ".", "get_model"...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SupportedServices.get_service_resources
Get resource models by service model
waldur_core/structure/__init__.py
def get_service_resources(cls, model): """ Get resource models by service model """ key = cls.get_model_key(model) return cls.get_service_name_resources(key)
def get_service_resources(cls, model): """ Get resource models by service model """ key = cls.get_model_key(model) return cls.get_service_name_resources(key)
[ "Get", "resource", "models", "by", "service", "model" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L302-L305
[ "def", "get_service_resources", "(", "cls", ",", "model", ")", ":", "key", "=", "cls", ".", "get_model_key", "(", "model", ")", "return", "cls", ".", "get_service_name_resources", "(", "key", ")" ]
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SupportedServices.get_service_name_resources
Get resource models by service name
waldur_core/structure/__init__.py
def get_service_name_resources(cls, service_name): """ Get resource models by service name """ from django.apps import apps resources = cls._registry[service_name]['resources'].keys() return [apps.get_model(resource) for resource in resources]
def get_service_name_resources(cls, service_name): """ Get resource models by service name """ from django.apps import apps resources = cls._registry[service_name]['resources'].keys() return [apps.get_model(resource) for resource in resources]
[ "Get", "resource", "models", "by", "service", "name" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L309-L314
[ "def", "get_service_name_resources", "(", "cls", ",", "service_name", ")", ":", "from", "django", ".", "apps", "import", "apps", "resources", "=", "cls", ".", "_registry", "[", "service_name", "]", "[", "'resources'", "]", ".", "keys", "(", ")", "return", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SupportedServices.get_name_for_model
Get a name for given class or model: -- it's a service type for a service -- it's a <service_type>.<resource_model_name> for a resource
waldur_core/structure/__init__.py
def get_name_for_model(cls, model): """ Get a name for given class or model: -- it's a service type for a service -- it's a <service_type>.<resource_model_name> for a resource """ key = cls.get_model_key(model) model_str = cls._get_model_str(model) service...
def get_name_for_model(cls, model): """ Get a name for given class or model: -- it's a service type for a service -- it's a <service_type>.<resource_model_name> for a resource """ key = cls.get_model_key(model) model_str = cls._get_model_str(model) service...
[ "Get", "a", "name", "for", "given", "class", "or", "model", ":", "--", "it", "s", "a", "service", "type", "for", "a", "service", "--", "it", "s", "a", "<service_type", ">", ".", "<resource_model_name", ">", "for", "a", "resource" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L317-L328
[ "def", "get_name_for_model", "(", "cls", ",", "model", ")", ":", "key", "=", "cls", ".", "get_model_key", "(", "model", ")", "model_str", "=", "cls", ".", "_get_model_str", "(", "model", ")", "service", "=", "cls", ".", "_registry", "[", "key", "]", "i...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SupportedServices.get_related_models
Get a dictionary with related structure models for given class or model: >> SupportedServices.get_related_models(gitlab_models.Project) { 'service': nodeconductor_gitlab.models.GitLabService, 'service_project_link': nodeconductor_gitlab.models.GitLabServiceProjec...
waldur_core/structure/__init__.py
def get_related_models(cls, model): """ Get a dictionary with related structure models for given class or model: >> SupportedServices.get_related_models(gitlab_models.Project) { 'service': nodeconductor_gitlab.models.GitLabService, 'service_project_link':...
def get_related_models(cls, model): """ Get a dictionary with related structure models for given class or model: >> SupportedServices.get_related_models(gitlab_models.Project) { 'service': nodeconductor_gitlab.models.GitLabService, 'service_project_link':...
[ "Get", "a", "dictionary", "with", "related", "structure", "models", "for", "given", "class", "or", "model", ":" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L331-L358
[ "def", "get_related_models", "(", "cls", ",", "model", ")", ":", "from", "waldur_core", ".", "structure", ".", "models", "import", "ServiceSettings", "if", "isinstance", "(", "model", ",", "ServiceSettings", ")", ":", "model_str", "=", "cls", ".", "_registry",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SupportedServices._is_active_model
Check is model app name is in list of INSTALLED_APPS
waldur_core/structure/__init__.py
def _is_active_model(cls, model): """ Check is model app name is in list of INSTALLED_APPS """ # We need to use such tricky way to check because of inconsistent apps names: # some apps are included in format "<module_name>.<app_name>" like "waldur_core.openstack" # other apps are include...
def _is_active_model(cls, model): """ Check is model app name is in list of INSTALLED_APPS """ # We need to use such tricky way to check because of inconsistent apps names: # some apps are included in format "<module_name>.<app_name>" like "waldur_core.openstack" # other apps are include...
[ "Check", "is", "model", "app", "name", "is", "in", "list", "of", "INSTALLED_APPS" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/__init__.py#L361-L367
[ "def", "_is_active_model", "(", "cls", ",", "model", ")", ":", "# We need to use such tricky way to check because of inconsistent apps names:", "# some apps are included in format \"<module_name>.<app_name>\" like \"waldur_core.openstack\"", "# other apps are included in format \"<app_name>\" li...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
PushHook.process
Send events as push notification via Google Cloud Messaging. Expected settings as follows: # https://developers.google.com/mobile/add WALDUR_CORE['GOOGLE_API'] = { 'NOTIFICATION_TITLE': "Waldur notification", 'Android': { ...
waldur_core/logging/models.py
def process(self, event): """ Send events as push notification via Google Cloud Messaging. Expected settings as follows: # https://developers.google.com/mobile/add WALDUR_CORE['GOOGLE_API'] = { 'NOTIFICATION_TITLE': "Waldur notification", ...
def process(self, event): """ Send events as push notification via Google Cloud Messaging. Expected settings as follows: # https://developers.google.com/mobile/add WALDUR_CORE['GOOGLE_API'] = { 'NOTIFICATION_TITLE': "Waldur notification", ...
[ "Send", "events", "as", "push", "notification", "via", "Google", "Cloud", "Messaging", ".", "Expected", "settings", "as", "follows", ":" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/models.py#L200-L241
[ "def", "process", "(", "self", ",", "event", ")", ":", "conf", "=", "settings", ".", "WALDUR_CORE", ".", "get", "(", "'GOOGLE_API'", ")", "or", "{", "}", "keys", "=", "conf", ".", "get", "(", "dict", "(", "self", ".", "Type", ".", "CHOICES", ")", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
get_context_data_from_headers
Extracts context data from request headers according to specified schema. >>> from lxml import etree as et >>> from datetime import date >>> from pyws.functions.args import TypeFactory >>> Fake = type('Fake', (object, ), {}) >>> request = Fake() >>> request.parsed_data = Fake() >>> request....
src/pyws/protocols/soap/__init__.py
def get_context_data_from_headers(request, headers_schema): """ Extracts context data from request headers according to specified schema. >>> from lxml import etree as et >>> from datetime import date >>> from pyws.functions.args import TypeFactory >>> Fake = type('Fake', (object, ), {}) >>...
def get_context_data_from_headers(request, headers_schema): """ Extracts context data from request headers according to specified schema. >>> from lxml import etree as et >>> from datetime import date >>> from pyws.functions.args import TypeFactory >>> Fake = type('Fake', (object, ), {}) >>...
[ "Extracts", "context", "data", "from", "request", "headers", "according", "to", "specified", "schema", "." ]
stepank/pyws
python
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/protocols/soap/__init__.py#L94-L131
[ "def", "get_context_data_from_headers", "(", "request", ",", "headers_schema", ")", ":", "if", "not", "headers_schema", ":", "return", "None", "env", "=", "request", ".", "parsed_data", ".", "xml", ".", "xpath", "(", "'/soap:Envelope'", ",", "namespaces", "=", ...
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
train
lazy_constant
Decorator to make a function that takes no arguments use the LazyConstant class.
qcore/caching.py
def lazy_constant(fn): """Decorator to make a function that takes no arguments use the LazyConstant class.""" class NewLazyConstant(LazyConstant): @functools.wraps(fn) def __call__(self): return self.get_value() return NewLazyConstant(fn)
def lazy_constant(fn): """Decorator to make a function that takes no arguments use the LazyConstant class.""" class NewLazyConstant(LazyConstant): @functools.wraps(fn) def __call__(self): return self.get_value() return NewLazyConstant(fn)
[ "Decorator", "to", "make", "a", "function", "that", "takes", "no", "arguments", "use", "the", "LazyConstant", "class", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L84-L92
[ "def", "lazy_constant", "(", "fn", ")", ":", "class", "NewLazyConstant", "(", "LazyConstant", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "__call__", "(", "self", ")", ":", "return", "self", ".", "get_value", "(", ")", "return", "N...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
lru_cache
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 ...
qcore/caching.py
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): """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...
[ "Decorator", "that", "adds", "an", "LRU", "cache", "of", "size", "maxsize", "to", "the", "decorated", "function", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L238-L278
[ "def", "lru_cache", "(", "maxsize", "=", "128", ",", "key_fn", "=", "None", ")", ":", "def", "decorator", "(", "fn", ")", ":", "cache", "=", "LRUCache", "(", "maxsize", ")", "argspec", "=", "inspect2", ".", "getfullargspec", "(", "fn", ")", "arg_names"...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
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.
qcore/caching.py
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(): """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...
[ "Decorator", "that", "adds", "caching", "to", "an", "instance", "method", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L281-L319
[ "def", "cached_per_instance", "(", ")", ":", "def", "cache_fun", "(", "fun", ")", ":", "argspec", "=", "inspect2", ".", "getfullargspec", "(", "fun", ")", "arg_names", "=", "argspec", ".", "args", "[", "1", ":", "]", "+", "argspec", ".", "kwonlyargs", ...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
get_args_tuple
Generates a cache key from the passed in arguments.
qcore/caching.py
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): """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_...
[ "Generates", "a", "cache", "key", "from", "the", "passed", "in", "arguments", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L322-L337
[ "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", ":", ...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
get_kwargs_defaults
Computes a kwargs_defaults dictionary for use by get_args_tuple given an argspec.
qcore/caching.py
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): """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...
[ "Computes", "a", "kwargs_defaults", "dictionary", "for", "use", "by", "get_args_tuple", "given", "an", "argspec", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L340-L350
[ "def", "get_kwargs_defaults", "(", "argspec", ")", ":", "arg_names", "=", "tuple", "(", "argspec", ".", "args", ")", "defaults", "=", "argspec", ".", "defaults", "or", "(", ")", "num_args", "=", "len", "(", "argspec", ".", "args", ")", "-", "len", "(",...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
memoize
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.
qcore/caching.py
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): """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...
[ "Memoizes", "return", "values", "of", "the", "decorated", "function", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L353-L380
[ "def", "memoize", "(", "fun", ")", ":", "argspec", "=", "inspect2", ".", "getfullargspec", "(", "fun", ")", "arg_names", "=", "argspec", ".", "args", "+", "argspec", ".", "kwonlyargs", "kwargs_defaults", "=", "get_kwargs_defaults", "(", "argspec", ")", "def"...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
memoize_with_ttl
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.
qcore/caching.py
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): """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 ...
[ "Memoizes", "return", "values", "of", "the", "decorated", "function", "for", "a", "given", "time", "-", "to", "-", "live", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L383-L445
[ "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", "...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
LazyConstant.get_value
Returns the value of the constant.
qcore/caching.py
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): """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
[ "Returns", "the", "value", "of", "the", "constant", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L64-L70
[ "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...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
LazyConstant.compute
Computes the value. Does not look at the cache.
qcore/caching.py
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): """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
[ "Computes", "the", "value", ".", "Does", "not", "look", "at", "the", "cache", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L72-L78
[ "def", "compute", "(", "self", ")", ":", "self", ".", "value", "=", "self", ".", "value_provider", "(", ")", "if", "self", ".", "value", "is", "not_computed", ":", "return", "None", "else", ":", "return", "self", ".", "value" ]
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
LRUCache.get
Return the value for given key if it exists.
qcore/caching.py
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): """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]
[ "Return", "the", "value", "for", "given", "key", "if", "it", "exists", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L187-L193
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "miss", ")", ":", "if", "key", "not", "in", "self", ".", "_dict", ":", "return", "default", "# invokes __getitem__, which updates the item", "return", "self", "[", "key", "]" ]
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
LRUCache.clear
Empty the cache and optionally invoke item_evicted callback.
qcore/caching.py
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): """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()
[ "Empty", "the", "cache", "and", "optionally", "invoke", "item_evicted", "callback", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L209-L215
[ "def", "clear", "(", "self", ",", "omit_item_evicted", "=", "False", ")", ":", "if", "not", "omit_item_evicted", ":", "items", "=", "self", ".", "_dict", ".", "items", "(", ")", "for", "key", ",", "value", "in", "items", ":", "self", ".", "_evict_item"...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
create_future
Compatibility wrapper for the loop.create_future() call introduced in 3.5.2.
aiosqlite3/utils.py
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 """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)
[ "Compatibility", "wrapper", "for", "the", "loop", ".", "create_future", "()", "call", "introduced", "in", "3", ".", "5", ".", "2", "." ]
zeromake/aiosqlite3
python
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/utils.py#L17-L23
[ "def", "create_future", "(", "loop", ")", ":", "# pragma: no cover", "if", "hasattr", "(", "loop", ",", "'create_future'", ")", ":", "return", "loop", ".", "create_future", "(", ")", "return", "asyncio", ".", "Future", "(", "loop", "=", "loop", ")" ]
1a74a062507e2df8f833a70885e69dca0ab3e7e7
train
create_task
Compatibility wrapper for the loop.create_task() call introduced in 3.4.2.
aiosqlite3/utils.py
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 """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)
[ "Compatibility", "wrapper", "for", "the", "loop", ".", "create_task", "()", "call", "introduced", "in", "3", ".", "4", ".", "2", "." ]
zeromake/aiosqlite3
python
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/utils.py#L26-L32
[ "def", "create_task", "(", "coro", ",", "loop", ")", ":", "# pragma: no cover", "if", "hasattr", "(", "loop", ",", "'create_task'", ")", ":", "return", "loop", ".", "create_task", "(", "coro", ")", "return", "asyncio", ".", "Task", "(", "coro", ",", "loo...
1a74a062507e2df8f833a70885e69dca0ab3e7e7
train
proxy_property_directly
为类添加代理属性
aiosqlite3/utils.py
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): """ 添加到类 """ for attr_name in attrs: setattr(cls, attr_name, _make_proxy_property(bind_attr, attr_name)) return cls return cls_builder
[ "为类添加代理属性" ]
zeromake/aiosqlite3
python
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/utils.py#L265-L276
[ "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...
1a74a062507e2df8f833a70885e69dca0ab3e7e7
train
StructureLoggableMixin.get_permitted_objects_uuids
Return query dictionary to search objects available to user.
waldur_core/structure/models.py
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): """ 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...
[ "Return", "query", "dictionary", "to", "search", "objects", "available", "to", "user", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/models.py#L79-L85
[ "def", "get_permitted_objects_uuids", "(", "cls", ",", "user", ")", ":", "uuids", "=", "filter_queryset_for_user", "(", "cls", ".", "objects", ".", "all", "(", ")", ",", "user", ")", ".", "values_list", "(", "'uuid'", ",", "flat", "=", "True", ")", "key"...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
PermissionMixin.has_user
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 ...
waldur_core/structure/models.py
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): """ 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. - ...
[ "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", ...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/models.py#L191-L209
[ "def", "has_user", "(", "self", ",", "user", ",", "role", "=", "None", ",", "timestamp", "=", "False", ")", ":", "permissions", "=", "self", ".", "permissions", ".", "filter", "(", "user", "=", "user", ",", "is_active", "=", "True", ")", "if", "role"...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
Magic.from_buffer
Identify the contents of `buf`
waldur_core/core/magic.py
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): """ 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 ...
[ "Identify", "the", "contents", "of", "buf" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/magic.py#L71-L84
[ "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", ","...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
NURESTPushCenter.start
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.
bambou/nurest_push_center.py
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): """ 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...
[ "Starts", "listening", "to", "events", "." ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L103-L128
[ "def", "start", "(", "self", ",", "timeout", "=", "None", ",", "root_object", "=", "None", ")", ":", "if", "self", ".", "_is_running", ":", "return", "if", "timeout", ":", "self", ".", "_timeout", "=", "timeout", "self", ".", "_start_time", "=", "int",...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTPushCenter.stop
Stops listening for events.
bambou/nurest_push_center.py
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): """ 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...
[ "Stops", "listening", "for", "events", "." ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L130-L144
[ "def", "stop", "(", "self", ")", ":", "if", "not", "self", ".", "_is_running", ":", "return", "pushcenter_logger", ".", "debug", "(", "\"[NURESTPushCenter] Stopping...\"", ")", "self", ".", "_thread", ".", "stop", "(", ")", "self", ".", "_thread", ".", "jo...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTPushCenter.wait_until_exit
Wait until thread exit Used for testing purpose only
bambou/nurest_push_center.py
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): """ 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()
[ "Wait", "until", "thread", "exit" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L146-L156
[ "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", "...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTPushCenter._did_receive_event
Receive an event from connection
bambou/nurest_push_center.py
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): """ 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...
[ "Receive", "an", "event", "from", "connection" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L173-L210
[ "def", "_did_receive_event", "(", "self", ",", "connection", ")", ":", "if", "not", "self", ".", "_is_running", ":", "return", "if", "connection", ".", "has_timeouted", ":", "return", "response", "=", "connection", ".", "response", "data", "=", "None", "if",...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTPushCenter._listen
Listen a connection uuid
bambou/nurest_push_center.py
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): """ 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?...
[ "Listen", "a", "connection", "uuid" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L212-L238
[ "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.\"", ")", "...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTPushCenter.add_delegate
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
bambou/nurest_push_center.py
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): """ 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...
[ "Registers", "a", "new", "delegate", "callback" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L240-L252
[ "def", "add_delegate", "(", "self", ",", "callback", ")", ":", "if", "callback", "in", "self", ".", "_delegate_methods", ":", "return", "self", ".", "_delegate_methods", ".", "append", "(", "callback", ")" ]
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTPushCenter.remove_delegate
Unregisters a registered delegate function or a method. Args: callback(function): method to trigger when push center receives events
bambou/nurest_push_center.py
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): """ 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...
[ "Unregisters", "a", "registered", "delegate", "function", "or", "a", "method", "." ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_push_center.py#L254-L264
[ "def", "remove_delegate", "(", "self", ",", "callback", ")", ":", "if", "callback", "not", "in", "self", ".", "_delegate_methods", ":", "return", "self", ".", "_delegate_methods", ".", "remove", "(", "callback", ")" ]
d334fea23e384d3df8e552fe1849ad707941c666
train
BambouConfig._read_config
Reads the configuration file if any
bambou/config.py
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): """ Reads the configuration file if any """ cls._config_parser = configparser.ConfigParser() cls._config_parser.read(cls._default_attribute_values_configuration_file_path)
[ "Reads", "the", "configuration", "file", "if", "any" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/config.py#L108-L113
[ "def", "_read_config", "(", "cls", ")", ":", "cls", ".", "_config_parser", "=", "configparser", ".", "ConfigParser", "(", ")", "cls", ".", "_config_parser", ".", "read", "(", "cls", ".", "_default_attribute_values_configuration_file_path", ")" ]
d334fea23e384d3df8e552fe1849ad707941c666
train
BambouConfig.get_default_attribute_value
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...
bambou/config.py
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): """ 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...
[ "Gets", "the", "default", "value", "of", "a", "given", "property", "for", "a", "given", "object", "." ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/config.py#L116-L157
[ "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...
d334fea23e384d3df8e552fe1849ad707941c666
train
SummaryFilter.filter
Filter each resource separately using its own filter
waldur_core/core/filters.py
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): """ 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...
[ "Filter", "each", "resource", "separately", "using", "its", "own", "filter" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/filters.py#L275-L285
[ "def", "filter", "(", "self", ",", "request", ",", "queryset", ",", "view", ")", ":", "summary_queryset", "=", "queryset", "filtered_querysets", "=", "[", "]", "for", "queryset", "in", "summary_queryset", ".", "querysets", ":", "filter_class", "=", "self", "...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
TypeFactory
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...
src/pyws/functions/args/types/__init__.py
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_): """ 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...
[ "This", "function", "creates", "a", "standard", "form", "type", "from", "a", "simplified", "form", "." ]
stepank/pyws
python
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/args/types/__init__.py#L21-L70
[ "def", "TypeFactory", "(", "type_", ")", ":", "if", "isinstance", "(", "type_", ",", "type", ")", "and", "issubclass", "(", "type_", ",", "Type", ")", ":", "return", "type_", "for", "x", "in", "__types__", ":", "if", "x", ".", "represents", "(", "typ...
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
train
dummy_image
Generate empty image in temporary file for testing
waldur_core/structure/images.py
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'): """ 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...
[ "Generate", "empty", "image", "in", "temporary", "file", "for", "testing" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/images.py#L14-L20
[ "def", "dummy_image", "(", "filetype", "=", "'gif'", ")", ":", "# 1x1px Transparent GIF", "GIF", "=", "'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'", "tmp_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.%s'", "%", "filetype", ")",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
utime_delta
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.
qcore/microtime.py
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): """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...
[ "Gets", "time", "delta", "in", "microseconds", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/microtime.py#L74-L81
[ "def", "utime_delta", "(", "days", "=", "0", ",", "hours", "=", "0", ",", "minutes", "=", "0", ",", "seconds", "=", "0", ")", ":", "return", "(", "days", "*", "DAY", ")", "+", "(", "hours", "*", "HOUR", ")", "+", "(", "minutes", "*", "MINUTE", ...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
execute_with_timeout
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...
qcore/microtime.py
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, timeout_exception_cls=TimeoutError, ): """ Executes specified function with timeout. Uses SIGALRM to interrupt it. :ty...
[ "Executes", "specified", "function", "with", "timeout", ".", "Uses", "SIGALRM", "to", "interrupt", "it", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/microtime.py#L132-L202
[ "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", "...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
get_original_fn
Gets the very original function of a decorated one.
qcore/inspection.py
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): """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...
[ "Gets", "the", "very", "original", "function", "of", "a", "decorated", "one", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L27-L38
[ "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", "(", "...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
get_full_name
Gets full class or function name.
qcore/inspection.py
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): """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...
[ "Gets", "full", "class", "or", "function", "name", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L41-L82
[ "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", ...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
get_function_call_str
Converts method call (function and its arguments) to a str(...)-like string.
qcore/inspection.py
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): """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...
[ "Converts", "method", "call", "(", "function", "and", "its", "arguments", ")", "to", "a", "str", "(", "...", ")", "-", "like", "string", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L85-L112
[ "def", "get_function_call_str", "(", "fn", ",", "args", ",", "kwargs", ")", ":", "def", "str_converter", "(", "v", ")", ":", "try", ":", "return", "str", "(", "v", ")", "except", "Exception", ":", "try", ":", "return", "repr", "(", "v", ")", "except"...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
get_function_call_repr
Converts method call (function and its arguments) to a repr(...)-like string.
qcore/inspection.py
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): """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) ...
[ "Converts", "method", "call", "(", "function", "and", "its", "arguments", ")", "to", "a", "repr", "(", "...", ")", "-", "like", "string", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L115-L133
[ "def", "get_function_call_repr", "(", "fn", ",", "args", ",", "kwargs", ")", ":", "result", "=", "get_full_name", "(", "fn", ")", "+", "\"(\"", "first", "=", "True", "for", "v", "in", "args", ":", "if", "first", ":", "first", "=", "False", "else", ":...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
getargspec
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...
qcore/inspection.py
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): """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...
[ "Variation", "of", "inspect", ".", "getargspec", "that", "works", "for", "more", "functions", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L136-L154
[ "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...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
is_cython_or_generator
Returns whether this function is either a generator function or a Cythonized function.
qcore/inspection.py
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): """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 ( ...
[ "Returns", "whether", "this", "function", "is", "either", "a", "generator", "function", "or", "a", "Cythonized", "function", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L157-L169
[ "def", "is_cython_or_generator", "(", "fn", ")", ":", "if", "hasattr", "(", "fn", ",", "\"__func__\"", ")", ":", "fn", "=", "fn", ".", "__func__", "# Class method, static method", "if", "inspect", ".", "isgeneratorfunction", "(", "fn", ")", ":", "return", "T...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
is_cython_function
Checks if a function is compiled w/Cython.
qcore/inspection.py
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): """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...
[ "Checks", "if", "a", "function", "is", "compiled", "w", "/", "Cython", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L172-L181
[ "def", "is_cython_function", "(", "fn", ")", ":", "if", "hasattr", "(", "fn", ",", "\"__func__\"", ")", ":", "fn", "=", "fn", ".", "__func__", "# Class method, static method", "name", "=", "type", "(", "fn", ")", ".", "__name__", "return", "(", "name", "...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
is_classmethod
Returns whether f is a classmethod.
qcore/inspection.py
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): """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...
[ "Returns", "whether", "f", "is", "a", "classmethod", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L189-L202
[ "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",...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
wraps
Cython-compatible functools.wraps implementation.
qcore/inspection.py
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 ): """Cython-compatible functools.wraps implementation.""" if not is_cython_function(wrapped): return functools.wraps(wrapped, assigned, updated) else: return lambda wrapper: wrapper
[ "Cython", "-", "compatible", "functools", ".", "wraps", "implementation", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L205-L212
[ "def", "wraps", "(", "wrapped", ",", "assigned", "=", "functools", ".", "WRAPPER_ASSIGNMENTS", ",", "updated", "=", "functools", ".", "WRAPPER_UPDATES", ")", ":", "if", "not", "is_cython_function", "(", "wrapped", ")", ":", "return", "functools", ".", "wraps",...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
get_subclass_tree
Returns all subclasses (direct and recursive) of cls.
qcore/inspection.py
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): """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...
[ "Returns", "all", "subclasses", "(", "direct", "and", "recursive", ")", "of", "cls", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/inspection.py#L215-L222
[ "def", "get_subclass_tree", "(", "cls", ",", "ensure_unique", "=", "True", ")", ":", "subclasses", "=", "[", "]", "# cls.__subclasses__() fails on classes inheriting from type", "for", "subcls", "in", "type", ".", "__subclasses__", "(", "cls", ")", ":", "subclasses"...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
DictOf
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...
src/pyws/functions/args/types/complex.py
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): """ 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__ ...
[ "This", "function", "creates", "a", "dict", "type", "with", "the", "specified", "name", "and", "fields", "." ]
stepank/pyws
python
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/args/types/complex.py#L88-L105
[ "def", "DictOf", "(", "name", ",", "*", "fields", ")", ":", "ret", "=", "type", "(", "name", ",", "(", "Dict", ",", ")", ",", "{", "'fields'", ":", "[", "]", "}", ")", "#noinspection PyUnresolvedReferences", "ret", ".", "add_fields", "(", "*", "field...
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
train
ListOf
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...
src/pyws/functions/args/types/complex.py
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): """ 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...
[ "This", "function", "creates", "a", "list", "type", "with", "element", "type", "element_type", "and", "an", "empty", "element", "value", "element_none_value", "." ]
stepank/pyws
python
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/args/types/complex.py#L108-L126
[ "def", "ListOf", "(", "element_type", ",", "element_none_value", "=", "None", ")", ":", "from", "pyws", ".", "functions", ".", "args", ".", "types", "import", "TypeFactory", "element_type", "=", "TypeFactory", "(", "element_type", ")", "return", "type", "(", ...
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
train
ActionsMetadata.get_actions
Return metadata for resource-specific actions, such as start, stop, unlink
waldur_core/structure/metadata.py
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): """ 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...
[ "Return", "metadata", "for", "resource", "-", "specific", "actions", "such", "as", "start", "stop", "unlink" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L96-L125
[ "def", "get_actions", "(", "self", ",", "request", ",", "view", ")", ":", "metadata", "=", "OrderedDict", "(", ")", "actions", "=", "self", ".", "get_resource_actions", "(", "view", ")", "resource", "=", "view", ".", "get_object", "(", ")", "for", "actio...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ActionsMetadata.get_action_fields
Get fields exposed by action's serializer
waldur_core/structure/metadata.py
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): """ 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...
[ "Get", "fields", "exposed", "by", "action", "s", "serializer" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L150-L158
[ "def", "get_action_fields", "(", "self", ",", "view", ",", "action_name", ",", "resource", ")", ":", "serializer", "=", "view", ".", "get_serializer", "(", "resource", ")", "fields", "=", "OrderedDict", "(", ")", "if", "not", "isinstance", "(", "serializer",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ActionsMetadata.get_serializer_info
Given an instance of a serializer, return a dictionary of metadata about its fields.
waldur_core/structure/metadata.py
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): """ 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...
[ "Given", "an", "instance", "of", "a", "serializer", "return", "a", "dictionary", "of", "metadata", "about", "its", "fields", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L160-L169
[ "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...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ActionsMetadata.get_fields
Get fields metadata skipping empty fields
waldur_core/structure/metadata.py
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): """ 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...
[ "Get", "fields", "metadata", "skipping", "empty", "fields" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L171-L184
[ "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...
d6c17a9592bb6c49c33567542eef8d099605a46a