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
ActionsMetadata.get_field_info
Given an instance of a serializer field, return a dictionary of metadata about it.
waldur_core/structure/metadata.py
def get_field_info(self, field, field_name): """ Given an instance of a serializer field, return a dictionary of metadata about it. """ field_info = OrderedDict() field_info['type'] = self.label_lookup[field] field_info['required'] = getattr(field, 'required', Fal...
def get_field_info(self, field, field_name): """ Given an instance of a serializer field, return a dictionary of metadata about it. """ field_info = OrderedDict() field_info['type'] = self.label_lookup[field] field_info['required'] = getattr(field, 'required', Fal...
[ "Given", "an", "instance", "of", "a", "serializer", "field", "return", "a", "dictionary", "of", "metadata", "about", "it", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/metadata.py#L186-L230
[ "def", "get_field_info", "(", "self", ",", "field", ",", "field_name", ")", ":", "field_info", "=", "OrderedDict", "(", ")", "field_info", "[", "'type'", "]", "=", "self", ".", "label_lookup", "[", "field", "]", "field_info", "[", "'required'", "]", "=", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
connect
把async方法执行后的对象创建为async上下文模式
aiosqlite3/connection.py
def connect( database: str, loop: asyncio.BaseEventLoop = None, executor: concurrent.futures.Executor = None, timeout: int = 5, echo: bool = False, isolation_level: str = '', check_same_thread: bool = False, **kwargs: dict ): """ 把async方法执行后的对象创建为a...
def connect( database: str, loop: asyncio.BaseEventLoop = None, executor: concurrent.futures.Executor = None, timeout: int = 5, echo: bool = False, isolation_level: str = '', check_same_thread: bool = False, **kwargs: dict ): """ 把async方法执行后的对象创建为a...
[ "把async方法执行后的对象创建为async上下文模式" ]
zeromake/aiosqlite3
python
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/connection.py#L443-L466
[ "def", "connect", "(", "database", ":", "str", ",", "loop", ":", "asyncio", ".", "BaseEventLoop", "=", "None", ",", "executor", ":", "concurrent", ".", "futures", ".", "Executor", "=", "None", ",", "timeout", ":", "int", "=", "5", ",", "echo", ":", "...
1a74a062507e2df8f833a70885e69dca0ab3e7e7
train
recalculate_estimate
Recalculate price of consumables that were used by resource until now. Regular task. It is too expensive to calculate consumed price on each request, so we store cached price each hour. If recalculate_total is True - task also recalculates total estimate for current month.
waldur_core/cost_tracking/tasks.py
def recalculate_estimate(recalculate_total=False): """ Recalculate price of consumables that were used by resource until now. Regular task. It is too expensive to calculate consumed price on each request, so we store cached price each hour. If recalculate_total is True - task also recalcula...
def recalculate_estimate(recalculate_total=False): """ Recalculate price of consumables that were used by resource until now. Regular task. It is too expensive to calculate consumed price on each request, so we store cached price each hour. If recalculate_total is True - task also recalcula...
[ "Recalculate", "price", "of", "consumables", "that", "were", "used", "by", "resource", "until", "now", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/tasks.py#L8-L29
[ "def", "recalculate_estimate", "(", "recalculate_total", "=", "False", ")", ":", "# Celery does not import server.urls and does not discover cost tracking modules.", "# So they should be discovered implicitly.", "CostTrackingRegister", ".", "autodiscover", "(", ")", "# Step 1. Recalcul...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ImportLibMixin.get_data
Needs to return the string source for the module.
src/importnb/loader.py
def get_data(self, path): """Needs to return the string source for the module.""" return LineCacheNotebookDecoder( code=self.code, raw=self.raw, markdown=self.markdown ).decode(self.decode(), self.path)
def get_data(self, path): """Needs to return the string source for the module.""" return LineCacheNotebookDecoder( code=self.code, raw=self.raw, markdown=self.markdown ).decode(self.decode(), self.path)
[ "Needs", "to", "return", "the", "string", "source", "for", "the", "module", "." ]
deathbeds/importnb
python
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L138-L142
[ "def", "get_data", "(", "self", ",", "path", ")", ":", "return", "LineCacheNotebookDecoder", "(", "code", "=", "self", ".", "code", ",", "raw", "=", "self", ".", "raw", ",", "markdown", "=", "self", ".", "markdown", ")", ".", "decode", "(", "self", "...
ec870d1f8ab99fd5b363267f89787a3e442a779f
train
NotebookBaseLoader.loader
Create a lazy loader source file loader.
src/importnb/loader.py
def loader(self): """Create a lazy loader source file loader.""" loader = super().loader if self._lazy and (sys.version_info.major, sys.version_info.minor) != (3, 4): loader = LazyLoader.factory(loader) # Strip the leading underscore from slots return partial( ...
def loader(self): """Create a lazy loader source file loader.""" loader = super().loader if self._lazy and (sys.version_info.major, sys.version_info.minor) != (3, 4): loader = LazyLoader.factory(loader) # Strip the leading underscore from slots return partial( ...
[ "Create", "a", "lazy", "loader", "source", "file", "loader", "." ]
deathbeds/importnb
python
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L182-L190
[ "def", "loader", "(", "self", ")", ":", "loader", "=", "super", "(", ")", ".", "loader", "if", "self", ".", "_lazy", "and", "(", "sys", ".", "version_info", ".", "major", ",", "sys", ".", "version_info", ".", "minor", ")", "!=", "(", "3", ",", "4...
ec870d1f8ab99fd5b363267f89787a3e442a779f
train
FromFileMixin.load
Import a notebook as a module from a filename. dir: The directory to load the file from. main: Load the module in the __main__ context. > assert Notebook.load('loader.ipynb')
src/importnb/loader.py
def load(cls, filename, dir=None, main=False, **kwargs): """Import a notebook as a module from a filename. dir: The directory to load the file from. main: Load the module in the __main__ context. > assert Notebook.load('loader.ipynb') """ name = main and...
def load(cls, filename, dir=None, main=False, **kwargs): """Import a notebook as a module from a filename. dir: The directory to load the file from. main: Load the module in the __main__ context. > assert Notebook.load('loader.ipynb') """ name = main and...
[ "Import", "a", "notebook", "as", "a", "module", "from", "a", "filename", ".", "dir", ":", "The", "directory", "to", "load", "the", "file", "from", ".", "main", ":", "Load", "the", "module", "in", "the", "__main__", "context", ".", ">", "assert", "Noteb...
deathbeds/importnb
python
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L213-L233
[ "def", "load", "(", "cls", ",", "filename", ",", "dir", "=", "None", ",", "main", "=", "False", ",", "*", "*", "kwargs", ")", ":", "name", "=", "main", "and", "\"__main__\"", "or", "Path", "(", "filename", ")", ".", "stem", "loader", "=", "cls", ...
ec870d1f8ab99fd5b363267f89787a3e442a779f
train
Notebook.source_to_code
* Convert the current source to ast * Apply ast transformers. * Compile the code.
src/importnb/loader.py
def source_to_code(self, nodes, path, *, _optimize=-1): """* Convert the current source to ast * Apply ast transformers. * Compile the code.""" if not isinstance(nodes, ast.Module): nodes = ast.parse(nodes, self.path) if self._markdown_docstring: nodes = ...
def source_to_code(self, nodes, path, *, _optimize=-1): """* Convert the current source to ast * Apply ast transformers. * Compile the code.""" if not isinstance(nodes, ast.Module): nodes = ast.parse(nodes, self.path) if self._markdown_docstring: nodes = ...
[ "*", "Convert", "the", "current", "source", "to", "ast", "*", "Apply", "ast", "transformers", ".", "*", "Compile", "the", "code", "." ]
deathbeds/importnb
python
https://github.com/deathbeds/importnb/blob/ec870d1f8ab99fd5b363267f89787a3e442a779f/src/importnb/loader.py#L293-L303
[ "def", "source_to_code", "(", "self", ",", "nodes", ",", "path", ",", "*", ",", "_optimize", "=", "-", "1", ")", ":", "if", "not", "isinstance", "(", "nodes", ",", "ast", ".", "Module", ")", ":", "nodes", "=", "ast", ".", "parse", "(", "nodes", "...
ec870d1f8ab99fd5b363267f89787a3e442a779f
train
ExtraActionsMixin.get_urls
Inject extra action URLs.
waldur_core/core/admin.py
def get_urls(self): """ Inject extra action URLs. """ urls = [] for action in self.get_extra_actions(): regex = r'^{}/$'.format(self._get_action_href(action)) view = self.admin_site.admin_view(action) urls.append(url(regex, view)) ret...
def get_urls(self): """ Inject extra action URLs. """ urls = [] for action in self.get_extra_actions(): regex = r'^{}/$'.format(self._get_action_href(action)) view = self.admin_site.admin_view(action) urls.append(url(regex, view)) ret...
[ "Inject", "extra", "action", "URLs", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/admin.py#L312-L323
[ "def", "get_urls", "(", "self", ")", ":", "urls", "=", "[", "]", "for", "action", "in", "self", ".", "get_extra_actions", "(", ")", ":", "regex", "=", "r'^{}/$'", ".", "format", "(", "self", ".", "_get_action_href", "(", "action", ")", ")", "view", "...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ExtraActionsMixin.changelist_view
Inject extra links into template context.
waldur_core/core/admin.py
def changelist_view(self, request, extra_context=None): """ Inject extra links into template context. """ links = [] for action in self.get_extra_actions(): links.append({ 'label': self._get_action_label(action), 'href': self._get_acti...
def changelist_view(self, request, extra_context=None): """ Inject extra links into template context. """ links = [] for action in self.get_extra_actions(): links.append({ 'label': self._get_action_label(action), 'href': self._get_acti...
[ "Inject", "extra", "links", "into", "template", "context", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/admin.py#L325-L342
[ "def", "changelist_view", "(", "self", ",", "request", ",", "extra_context", "=", "None", ")", ":", "links", "=", "[", "]", "for", "action", "in", "self", ".", "get_extra_actions", "(", ")", ":", "links", ".", "append", "(", "{", "'label'", ":", "self"...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
NURESTSession.start
Starts the session. Starting the session will actually get the API key of the current user
bambou/nurest_session.py
def start(self): """ Starts the session. Starting the session will actually get the API key of the current user """ if NURESTSession.session_stack: bambou_logger.critical("Starting a session inside a with statement is not supported.") raise Excep...
def start(self): """ Starts the session. Starting the session will actually get the API key of the current user """ if NURESTSession.session_stack: bambou_logger.critical("Starting a session inside a with statement is not supported.") raise Excep...
[ "Starts", "the", "session", "." ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_session.py#L155-L169
[ "def", "start", "(", "self", ")", ":", "if", "NURESTSession", ".", "session_stack", ":", "bambou_logger", ".", "critical", "(", "\"Starting a session inside a with statement is not supported.\"", ")", "raise", "Exception", "(", "\"Starting a session inside a with statement is...
d334fea23e384d3df8e552fe1849ad707941c666
train
init_quotas
Initialize new instances quotas
waldur_core/quotas/handlers.py
def init_quotas(sender, instance, created=False, **kwargs): """ Initialize new instances quotas """ if not created: return for field in sender.get_quotas_fields(): try: field.get_or_create_quota(scope=instance) except CreationConditionFailedQuotaError: pass
def init_quotas(sender, instance, created=False, **kwargs): """ Initialize new instances quotas """ if not created: return for field in sender.get_quotas_fields(): try: field.get_or_create_quota(scope=instance) except CreationConditionFailedQuotaError: pass
[ "Initialize", "new", "instances", "quotas" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/handlers.py#L35-L43
[ "def", "init_quotas", "(", "sender", ",", "instance", ",", "created", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "created", ":", "return", "for", "field", "in", "sender", ".", "get_quotas_fields", "(", ")", ":", "try", ":", "field", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
count_quota_handler_factory
Creates handler that will recalculate count_quota on creation/deletion
waldur_core/quotas/handlers.py
def count_quota_handler_factory(count_quota_field): """ Creates handler that will recalculate count_quota on creation/deletion """ def recalculate_count_quota(sender, instance, **kwargs): signal = kwargs['signal'] if signal == signals.post_save and kwargs.get('created'): count_quota...
def count_quota_handler_factory(count_quota_field): """ Creates handler that will recalculate count_quota on creation/deletion """ def recalculate_count_quota(sender, instance, **kwargs): signal = kwargs['signal'] if signal == signals.post_save and kwargs.get('created'): count_quota...
[ "Creates", "handler", "that", "will", "recalculate", "count_quota", "on", "creation", "/", "deletion" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/handlers.py#L46-L56
[ "def", "count_quota_handler_factory", "(", "count_quota_field", ")", ":", "def", "recalculate_count_quota", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "signal", "=", "kwargs", "[", "'signal'", "]", "if", "signal", "==", "signals", ".", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
handle_aggregated_quotas
Call aggregated quotas fields update methods
waldur_core/quotas/handlers.py
def handle_aggregated_quotas(sender, instance, **kwargs): """ Call aggregated quotas fields update methods """ quota = instance # aggregation is not supported for global quotas. if quota.scope is None: return quota_field = quota.get_field() # usage aggregation should not count another us...
def handle_aggregated_quotas(sender, instance, **kwargs): """ Call aggregated quotas fields update methods """ quota = instance # aggregation is not supported for global quotas. if quota.scope is None: return quota_field = quota.get_field() # usage aggregation should not count another us...
[ "Call", "aggregated", "quotas", "fields", "update", "methods" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/handlers.py#L59-L75
[ "def", "handle_aggregated_quotas", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "quota", "=", "instance", "# aggregation is not supported for global quotas.", "if", "quota", ".", "scope", "is", "None", ":", "return", "quota_field", "=", "quot...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
NestedServiceProjectLinkSerializer.get_settings
URL of service settings
waldur_core/structure/serializers.py
def get_settings(self, link): """ URL of service settings """ return reverse( 'servicesettings-detail', kwargs={'uuid': link.service.settings.uuid}, request=self.context['request'])
def get_settings(self, link): """ URL of service settings """ return reverse( 'servicesettings-detail', kwargs={'uuid': link.service.settings.uuid}, request=self.context['request'])
[ "URL", "of", "service", "settings" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/serializers.py#L140-L145
[ "def", "get_settings", "(", "self", ",", "link", ")", ":", "return", "reverse", "(", "'servicesettings-detail'", ",", "kwargs", "=", "{", "'uuid'", ":", "link", ".", "service", ".", "settings", ".", "uuid", "}", ",", "request", "=", "self", ".", "context...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
NestedServiceProjectLinkSerializer.get_url
URL of service
waldur_core/structure/serializers.py
def get_url(self, link): """ URL of service """ view_name = SupportedServices.get_detail_view_for_model(link.service) return reverse(view_name, kwargs={'uuid': link.service.uuid.hex}, request=self.context['request'])
def get_url(self, link): """ URL of service """ view_name = SupportedServices.get_detail_view_for_model(link.service) return reverse(view_name, kwargs={'uuid': link.service.uuid.hex}, request=self.context['request'])
[ "URL", "of", "service" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/serializers.py#L147-L152
[ "def", "get_url", "(", "self", ",", "link", ")", ":", "view_name", "=", "SupportedServices", ".", "get_detail_view_for_model", "(", "link", ".", "service", ")", "return", "reverse", "(", "view_name", ",", "kwargs", "=", "{", "'uuid'", ":", "link", ".", "se...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
NestedServiceProjectLinkSerializer.get_resources_count
Count total number of all resources connected to link
waldur_core/structure/serializers.py
def get_resources_count(self, link): """ Count total number of all resources connected to link """ total = 0 for model in SupportedServices.get_service_resources(link.service): # Format query path from resource to service project link query = {model.Permis...
def get_resources_count(self, link): """ Count total number of all resources connected to link """ total = 0 for model in SupportedServices.get_service_resources(link.service): # Format query path from resource to service project link query = {model.Permis...
[ "Count", "total", "number", "of", "all", "resources", "connected", "to", "link" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/serializers.py#L166-L175
[ "def", "get_resources_count", "(", "self", ",", "link", ")", ":", "total", "=", "0", "for", "model", "in", "SupportedServices", ".", "get_service_resources", "(", "link", ".", "service", ")", ":", "# Format query path from resource to service project link", "query", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
SkDataSet.drop_columns
When max_na_values was informed, remove columns when the proportion of total NA values more than max_na_values threshold. When max_unique_values was informed, remove columns when the proportion of the total of unique values is more than the max_unique_values threshold, just for columns ...
skdata/data.py
def drop_columns( self, max_na_values: int = None, max_unique_values: int = None ): """ When max_na_values was informed, remove columns when the proportion of total NA values more than max_na_values threshold. When max_unique_values was informed, remove columns when the prop...
def drop_columns( self, max_na_values: int = None, max_unique_values: int = None ): """ When max_na_values was informed, remove columns when the proportion of total NA values more than max_na_values threshold. When max_unique_values was informed, remove columns when the prop...
[ "When", "max_na_values", "was", "informed", "remove", "columns", "when", "the", "proportion", "of", "total", "NA", "values", "more", "than", "max_na_values", "threshold", "." ]
OpenDataScienceLab/skdata
python
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L175-L204
[ "def", "drop_columns", "(", "self", ",", "max_na_values", ":", "int", "=", "None", ",", "max_unique_values", ":", "int", "=", "None", ")", ":", "step", "=", "{", "}", "if", "max_na_values", "is", "not", "None", ":", "step", "=", "{", "'data-set'", ":",...
34f06845a944ff4f048b55c7babdd8420f71a6b9
train
SkDataSet.dropna
:return:
skdata/data.py
def dropna(self): """ :return: """ step = { 'data-set': self.iid, 'operation': 'drop-na', 'expression': '{"axis": 0}' } self.attr_update(attr='steps', value=[step])
def dropna(self): """ :return: """ step = { 'data-set': self.iid, 'operation': 'drop-na', 'expression': '{"axis": 0}' } self.attr_update(attr='steps', value=[step])
[ ":", "return", ":" ]
OpenDataScienceLab/skdata
python
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L206-L217
[ "def", "dropna", "(", "self", ")", ":", "step", "=", "{", "'data-set'", ":", "self", ".", "iid", ",", "'operation'", ":", "'drop-na'", ",", "'expression'", ":", "'{\"axis\": 0}'", "}", "self", ".", "attr_update", "(", "attr", "=", "'steps'", ",", "value"...
34f06845a944ff4f048b55c7babdd8420f71a6b9
train
SkDataSet.log
@deprecated :param message: :return:
skdata/data.py
def log(self, message: str): """ @deprecated :param message: :return: """ dset_log_id = '_%s_log' % self.iid if dset_log_id not in self.parent.data.keys(): dset = self.parent.data.create_dataset( dset_log_id, shape=(1,), ...
def log(self, message: str): """ @deprecated :param message: :return: """ dset_log_id = '_%s_log' % self.iid if dset_log_id not in self.parent.data.keys(): dset = self.parent.data.create_dataset( dset_log_id, shape=(1,), ...
[ "@deprecated" ]
OpenDataScienceLab/skdata
python
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L219-L246
[ "def", "log", "(", "self", ",", "message", ":", "str", ")", ":", "dset_log_id", "=", "'_%s_log'", "%", "self", ".", "iid", "if", "dset_log_id", "not", "in", "self", ".", "parent", ".", "data", ".", "keys", "(", ")", ":", "dset", "=", "self", ".", ...
34f06845a944ff4f048b55c7babdd8420f71a6b9
train
SkDataSet.summary
:param compute: if should call compute method :return:
skdata/data.py
def summary(self, compute=False) -> pd.DataFrame: """ :param compute: if should call compute method :return: """ if compute or self.result is None: self.compute() return summary(self.result)
def summary(self, compute=False) -> pd.DataFrame: """ :param compute: if should call compute method :return: """ if compute or self.result is None: self.compute() return summary(self.result)
[ ":", "param", "compute", ":", "if", "should", "call", "compute", "method", ":", "return", ":" ]
OpenDataScienceLab/skdata
python
https://github.com/OpenDataScienceLab/skdata/blob/34f06845a944ff4f048b55c7babdd8420f71a6b9/skdata/data.py#L248-L255
[ "def", "summary", "(", "self", ",", "compute", "=", "False", ")", "->", "pd", ".", "DataFrame", ":", "if", "compute", "or", "self", ".", "result", "is", "None", ":", "self", ".", "compute", "(", ")", "return", "summary", "(", "self", ".", "result", ...
34f06845a944ff4f048b55c7babdd8420f71a6b9
train
serve
Twisted Web adapter. It has two arguments: #. ``request`` is a Twisted Web request object, #. ``server`` is a pyws server object. First one is the context of an application, function ``serve`` transforms it into a pyws request object. Then it feeds the request to the server, gets the response, set...
src/pyws/adapters/_twisted.py
def serve(request, server): """ Twisted Web adapter. It has two arguments: #. ``request`` is a Twisted Web request object, #. ``server`` is a pyws server object. First one is the context of an application, function ``serve`` transforms it into a pyws request object. Then it feeds the request t...
def serve(request, server): """ Twisted Web adapter. It has two arguments: #. ``request`` is a Twisted Web request object, #. ``server`` is a pyws server object. First one is the context of an application, function ``serve`` transforms it into a pyws request object. Then it feeds the request t...
[ "Twisted", "Web", "adapter", ".", "It", "has", "two", "arguments", ":" ]
stepank/pyws
python
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/adapters/_twisted.py#L4-L25
[ "def", "serve", "(", "request", ",", "server", ")", ":", "request_", "=", "Request", "(", "'/'", ".", "join", "(", "request", ".", "postpath", ")", ",", "request", ".", "content", ".", "read", "(", ")", "if", "not", "request", ".", "method", "==", ...
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
train
get_sorted_dependencies
Returns list of application models in topological order. It is used in order to correctly delete dependent resources.
waldur_core/structure/utils.py
def get_sorted_dependencies(service_model): """ Returns list of application models in topological order. It is used in order to correctly delete dependent resources. """ app_models = list(service_model._meta.app_config.get_models()) dependencies = {model: set() for model in app_models} relat...
def get_sorted_dependencies(service_model): """ Returns list of application models in topological order. It is used in order to correctly delete dependent resources. """ app_models = list(service_model._meta.app_config.get_models()) dependencies = {model: set() for model in app_models} relat...
[ "Returns", "list", "of", "application", "models", "in", "topological", "order", ".", "It", "is", "used", "in", "order", "to", "correctly", "delete", "dependent", "resources", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L38-L53
[ "def", "get_sorted_dependencies", "(", "service_model", ")", ":", "app_models", "=", "list", "(", "service_model", ".", "_meta", ".", "app_config", ".", "get_models", "(", ")", ")", "dependencies", "=", "{", "model", ":", "set", "(", ")", "for", "model", "...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
update_pulled_fields
Update instance fields based on imported from backend data. Save changes to DB only one or more fields were changed.
waldur_core/structure/utils.py
def update_pulled_fields(instance, imported_instance, fields): """ Update instance fields based on imported from backend data. Save changes to DB only one or more fields were changed. """ modified = False for field in fields: pulled_value = getattr(imported_instance, field) curre...
def update_pulled_fields(instance, imported_instance, fields): """ Update instance fields based on imported from backend data. Save changes to DB only one or more fields were changed. """ modified = False for field in fields: pulled_value = getattr(imported_instance, field) curre...
[ "Update", "instance", "fields", "based", "on", "imported", "from", "backend", "data", ".", "Save", "changes", "to", "DB", "only", "one", "or", "more", "fields", "were", "changed", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L91-L110
[ "def", "update_pulled_fields", "(", "instance", ",", "imported_instance", ",", "fields", ")", ":", "modified", "=", "False", "for", "field", "in", "fields", ":", "pulled_value", "=", "getattr", "(", "imported_instance", ",", "field", ")", "current_value", "=", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
handle_resource_not_found
Set resource state to ERRED and append/create "not found" error message.
waldur_core/structure/utils.py
def handle_resource_not_found(resource): """ Set resource state to ERRED and append/create "not found" error message. """ resource.set_erred() resource.runtime_state = '' message = 'Does not exist at backend.' if message not in resource.error_message: if not resource.error_message: ...
def handle_resource_not_found(resource): """ Set resource state to ERRED and append/create "not found" error message. """ resource.set_erred() resource.runtime_state = '' message = 'Does not exist at backend.' if message not in resource.error_message: if not resource.error_message: ...
[ "Set", "resource", "state", "to", "ERRED", "and", "append", "/", "create", "not", "found", "error", "message", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L113-L127
[ "def", "handle_resource_not_found", "(", "resource", ")", ":", "resource", ".", "set_erred", "(", ")", "resource", ".", "runtime_state", "=", "''", "message", "=", "'Does not exist at backend.'", "if", "message", "not", "in", "resource", ".", "error_message", ":",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
handle_resource_update_success
Recover resource if its state is ERRED and clear error message.
waldur_core/structure/utils.py
def handle_resource_update_success(resource): """ Recover resource if its state is ERRED and clear error message. """ update_fields = [] if resource.state == resource.States.ERRED: resource.recover() update_fields.append('state') if resource.state in (resource.States.UPDATING, r...
def handle_resource_update_success(resource): """ Recover resource if its state is ERRED and clear error message. """ update_fields = [] if resource.state == resource.States.ERRED: resource.recover() update_fields.append('state') if resource.state in (resource.States.UPDATING, r...
[ "Recover", "resource", "if", "its", "state", "is", "ERRED", "and", "clear", "error", "message", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/utils.py#L130-L150
[ "def", "handle_resource_update_success", "(", "resource", ")", ":", "update_fields", "=", "[", "]", "if", "resource", ".", "state", "==", "resource", ".", "States", ".", "ERRED", ":", "resource", ".", "recover", "(", ")", "update_fields", ".", "append", "(",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
NURESTRequest.set_header
Set header value
bambou/nurest_request.py
def set_header(self, header, value): """ Set header value """ # requests>=2.11 only accepts `str` or `bytes` header values # raising an exception here, instead of leaving it to `requests` makes # it easy to know where we passed a wrong header type in the code. if not isinstance(v...
def set_header(self, header, value): """ Set header value """ # requests>=2.11 only accepts `str` or `bytes` header values # raising an exception here, instead of leaving it to `requests` makes # it easy to know where we passed a wrong header type in the code. if not isinstance(v...
[ "Set", "header", "value" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_request.py#L120-L127
[ "def", "set_header", "(", "self", ",", "header", ",", "value", ")", ":", "# requests>=2.11 only accepts `str` or `bytes` header values", "# raising an exception here, instead of leaving it to `requests` makes", "# it easy to know where we passed a wrong header type in the code.", "if", "...
d334fea23e384d3df8e552fe1849ad707941c666
train
BackgroundPullTask.set_instance_erred
Mark instance as erred and save error message
waldur_core/structure/tasks.py
def set_instance_erred(self, instance, error_message): """ Mark instance as erred and save error message """ instance.set_erred() instance.error_message = error_message instance.save(update_fields=['state', 'error_message'])
def set_instance_erred(self, instance, error_message): """ Mark instance as erred and save error message """ instance.set_erred() instance.error_message = error_message instance.save(update_fields=['state', 'error_message'])
[ "Mark", "instance", "as", "erred", "and", "save", "error", "message" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/tasks.py#L118-L122
[ "def", "set_instance_erred", "(", "self", ",", "instance", ",", "error_message", ")", ":", "instance", ".", "set_erred", "(", ")", "instance", ".", "error_message", "=", "error_message", "instance", ".", "save", "(", "update_fields", "=", "[", "'state'", ",", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
map_language
Use ISO 639-3 ??
examples/logic.py
def map_language(language, dash3=True): """ Use ISO 639-3 ?? """ if dash3: from iso639 import languages else: from pycountry import languages if '_' in language: language = language.split('_')[0] if len(language) == 2: try: return languages.get(alpha2=language.lower(...
def map_language(language, dash3=True): """ Use ISO 639-3 ?? """ if dash3: from iso639 import languages else: from pycountry import languages if '_' in language: language = language.split('_')[0] if len(language) == 2: try: return languages.get(alpha2=language.lower(...
[ "Use", "ISO", "639", "-", "3", "??" ]
noumar/iso639
python
https://github.com/noumar/iso639/blob/2175cf04b8b8cec79d99a6c4ad31295d67c22cd6/examples/logic.py#L11-L39
[ "def", "map_language", "(", "language", ",", "dash3", "=", "True", ")", ":", "if", "dash3", ":", "from", "iso639", "import", "languages", "else", ":", "from", "pycountry", "import", "languages", "if", "'_'", "in", "language", ":", "language", "=", "languag...
2175cf04b8b8cec79d99a6c4ad31295d67c22cd6
train
BaseCleanupExecutor.get_task_signature
Delete each resource using specific executor. Convert executors to task and combine all deletion task into single sequential task.
waldur_core/structure/executors.py
def get_task_signature(cls, instance, serialized_instance, **kwargs): """ Delete each resource using specific executor. Convert executors to task and combine all deletion task into single sequential task. """ cleanup_tasks = [ ProjectResourceCleanupTask().si( ...
def get_task_signature(cls, instance, serialized_instance, **kwargs): """ Delete each resource using specific executor. Convert executors to task and combine all deletion task into single sequential task. """ cleanup_tasks = [ ProjectResourceCleanupTask().si( ...
[ "Delete", "each", "resource", "using", "specific", "executor", ".", "Convert", "executors", "to", "task", "and", "combine", "all", "deletion", "task", "into", "single", "sequential", "task", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/structure/executors.py#L99-L116
[ "def", "get_task_signature", "(", "cls", ",", "instance", ",", "serialized_instance", ",", "*", "*", "kwargs", ")", ":", "cleanup_tasks", "=", "[", "ProjectResourceCleanupTask", "(", ")", ".", "si", "(", "core_utils", ".", "serialize_class", "(", "executor_cls",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
sort_dict
Return a OrderedDict ordered by key names from the :unsorted_dict:
waldur_core/core/utils.py
def sort_dict(unsorted_dict): """ Return a OrderedDict ordered by key names from the :unsorted_dict: """ sorted_dict = OrderedDict() # sort items before inserting them into a dict for key, value in sorted(unsorted_dict.items(), key=itemgetter(0)): sorted_dict[key] = value return sort...
def sort_dict(unsorted_dict): """ Return a OrderedDict ordered by key names from the :unsorted_dict: """ sorted_dict = OrderedDict() # sort items before inserting them into a dict for key, value in sorted(unsorted_dict.items(), key=itemgetter(0)): sorted_dict[key] = value return sort...
[ "Return", "a", "OrderedDict", "ordered", "by", "key", "names", "from", "the", ":", "unsorted_dict", ":" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L25-L33
[ "def", "sort_dict", "(", "unsorted_dict", ")", ":", "sorted_dict", "=", "OrderedDict", "(", ")", "# sort items before inserting them into a dict", "for", "key", ",", "value", "in", "sorted", "(", "unsorted_dict", ".", "items", "(", ")", ",", "key", "=", "itemget...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
format_time_and_value_to_segment_list
Format time_and_value_list to time segments Parameters ^^^^^^^^^^ time_and_value_list: list of tuples Have to be sorted by time Example: [(time, value), (time, value) ...] segments_count: integer How many segments will be in result Returns ^^^^^^^ List of dictionarie...
waldur_core/core/utils.py
def format_time_and_value_to_segment_list(time_and_value_list, segments_count, start_timestamp, end_timestamp, average=False): """ Format time_and_value_list to time segments Parameters ^^^^^^^^^^ time_and_value_list: list of tuples Have to be sorte...
def format_time_and_value_to_segment_list(time_and_value_list, segments_count, start_timestamp, end_timestamp, average=False): """ Format time_and_value_list to time segments Parameters ^^^^^^^^^^ time_and_value_list: list of tuples Have to be sorte...
[ "Format", "time_and_value_list", "to", "time", "segments" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L36-L71
[ "def", "format_time_and_value_to_segment_list", "(", "time_and_value_list", ",", "segments_count", ",", "start_timestamp", ",", "end_timestamp", ",", "average", "=", "False", ")", ":", "segment_list", "=", "[", "]", "time_step", "=", "(", "end_timestamp", "-", "star...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
serialize_instance
Serialize Django model instance
waldur_core/core/utils.py
def serialize_instance(instance): """ Serialize Django model instance """ model_name = force_text(instance._meta) return '{}:{}'.format(model_name, instance.pk)
def serialize_instance(instance): """ Serialize Django model instance """ model_name = force_text(instance._meta) return '{}:{}'.format(model_name, instance.pk)
[ "Serialize", "Django", "model", "instance" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L121-L124
[ "def", "serialize_instance", "(", "instance", ")", ":", "model_name", "=", "force_text", "(", "instance", ".", "_meta", ")", "return", "'{}:{}'", ".", "format", "(", "model_name", ",", "instance", ".", "pk", ")" ]
d6c17a9592bb6c49c33567542eef8d099605a46a
train
deserialize_instance
Deserialize Django model instance
waldur_core/core/utils.py
def deserialize_instance(serialized_instance): """ Deserialize Django model instance """ model_name, pk = serialized_instance.split(':') model = apps.get_model(model_name) return model._default_manager.get(pk=pk)
def deserialize_instance(serialized_instance): """ Deserialize Django model instance """ model_name, pk = serialized_instance.split(':') model = apps.get_model(model_name) return model._default_manager.get(pk=pk)
[ "Deserialize", "Django", "model", "instance" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L127-L131
[ "def", "deserialize_instance", "(", "serialized_instance", ")", ":", "model_name", ",", "pk", "=", "serialized_instance", ".", "split", "(", "':'", ")", "model", "=", "apps", ".", "get_model", "(", "model_name", ")", "return", "model", ".", "_default_manager", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
deserialize_class
Deserialize Python class
waldur_core/core/utils.py
def deserialize_class(serilalized_cls): """ Deserialize Python class """ module_name, cls_name = serilalized_cls.split(':') module = importlib.import_module(module_name) return getattr(module, cls_name)
def deserialize_class(serilalized_cls): """ Deserialize Python class """ module_name, cls_name = serilalized_cls.split(':') module = importlib.import_module(module_name) return getattr(module, cls_name)
[ "Deserialize", "Python", "class" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L139-L143
[ "def", "deserialize_class", "(", "serilalized_cls", ")", ":", "module_name", ",", "cls_name", "=", "serilalized_cls", ".", "split", "(", "':'", ")", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "return", "getattr", "(", "module", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
instance_from_url
Restore instance from URL
waldur_core/core/utils.py
def instance_from_url(url, user=None): """ Restore instance from URL """ # XXX: This circular dependency will be removed then filter_queryset_for_user # will be moved to model manager method from waldur_core.structure.managers import filter_queryset_for_user url = clear_url(url) match = resolve...
def instance_from_url(url, user=None): """ Restore instance from URL """ # XXX: This circular dependency will be removed then filter_queryset_for_user # will be moved to model manager method from waldur_core.structure.managers import filter_queryset_for_user url = clear_url(url) match = resolve...
[ "Restore", "instance", "from", "URL" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/utils.py#L161-L173
[ "def", "instance_from_url", "(", "url", ",", "user", "=", "None", ")", ":", "# XXX: This circular dependency will be removed then filter_queryset_for_user", "# will be moved to model manager method", "from", "waldur_core", ".", "structure", ".", "managers", "import", "filter_qu...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
Transaction.close
Close this transaction. If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns. This is used to cancel a Transaction without affecting the scope of an enclosing transaction.
aiosqlite3/sa/transaction.py
def close(self): """ Close this transaction. If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns. This is used to cancel a Transaction without affecting the scope of an enclosing ...
def close(self): """ Close this transaction. If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns. This is used to cancel a Transaction without affecting the scope of an enclosing ...
[ "Close", "this", "transaction", "." ]
zeromake/aiosqlite3
python
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sa/transaction.py#L50-L73
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "_connection", "or", "not", "self", ".", "_parent", ":", "return", "if", "not", "self", ".", "_parent", ".", "_is_active", ":", "# pragma: no cover", "self", ".", "_connection", "=", "None"...
1a74a062507e2df8f833a70885e69dca0ab3e7e7
train
Transaction.commit
Commit this transaction.
aiosqlite3/sa/transaction.py
def commit(self): """ Commit this transaction. """ if not self._parent._is_active: raise exc.InvalidRequestError("This transaction is inactive") yield from self._do_commit() self._is_active = False
def commit(self): """ Commit this transaction. """ if not self._parent._is_active: raise exc.InvalidRequestError("This transaction is inactive") yield from self._do_commit() self._is_active = False
[ "Commit", "this", "transaction", "." ]
zeromake/aiosqlite3
python
https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/sa/transaction.py#L90-L98
[ "def", "commit", "(", "self", ")", ":", "if", "not", "self", ".", "_parent", ".", "_is_active", ":", "raise", "exc", ".", "InvalidRequestError", "(", "\"This transaction is inactive\"", ")", "yield", "from", "self", ".", "_do_commit", "(", ")", "self", ".", ...
1a74a062507e2df8f833a70885e69dca0ab3e7e7
train
CustomIndexDashboard._get_app_config
Returns an app config for the given name, not by label.
waldur_core/server/admin/dashboard.py
def _get_app_config(self, app_name): """ Returns an app config for the given name, not by label. """ matches = [app_config for app_config in apps.get_app_configs() if app_config.name == app_name] if not matches: return return matches[0]
def _get_app_config(self, app_name): """ Returns an app config for the given name, not by label. """ matches = [app_config for app_config in apps.get_app_configs() if app_config.name == app_name] if not matches: return return matches[0]
[ "Returns", "an", "app", "config", "for", "the", "given", "name", "not", "by", "label", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L56-L65
[ "def", "_get_app_config", "(", "self", ",", "app_name", ")", ":", "matches", "=", "[", "app_config", "for", "app_config", "in", "apps", ".", "get_app_configs", "(", ")", "if", "app_config", ".", "name", "==", "app_name", "]", "if", "not", "matches", ":", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
CustomIndexDashboard._get_app_version
Some plugins ship multiple applications and extensions. However all of them have the same version, because they are released together. That's why only-top level module is used to fetch version information.
waldur_core/server/admin/dashboard.py
def _get_app_version(self, app_config): """ Some plugins ship multiple applications and extensions. However all of them have the same version, because they are released together. That's why only-top level module is used to fetch version information. """ base_name = app_c...
def _get_app_version(self, app_config): """ Some plugins ship multiple applications and extensions. However all of them have the same version, because they are released together. That's why only-top level module is used to fetch version information. """ base_name = app_c...
[ "Some", "plugins", "ship", "multiple", "applications", "and", "extensions", ".", "However", "all", "of", "them", "have", "the", "same", "version", "because", "they", "are", "released", "together", ".", "That", "s", "why", "only", "-", "top", "level", "module...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L77-L86
[ "def", "_get_app_version", "(", "self", ",", "app_config", ")", ":", "base_name", "=", "app_config", ".", "__module__", ".", "split", "(", "'.'", ")", "[", "0", "]", "module", "=", "__import__", "(", "base_name", ")", "return", "getattr", "(", "module", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
CustomIndexDashboard._get_quick_access_info
Returns a list of ListLink items to be added to Quick Access tab. Contains: - links to Organizations, Projects and Users; - a link to shared service settings; - custom configured links in admin/settings FLUENT_DASHBOARD_QUICK_ACCESS_LINKS attribute;
waldur_core/server/admin/dashboard.py
def _get_quick_access_info(self): """ Returns a list of ListLink items to be added to Quick Access tab. Contains: - links to Organizations, Projects and Users; - a link to shared service settings; - custom configured links in admin/settings FLUENT_DASHBOARD_QUICK_ACCESS_L...
def _get_quick_access_info(self): """ Returns a list of ListLink items to be added to Quick Access tab. Contains: - links to Organizations, Projects and Users; - a link to shared service settings; - custom configured links in admin/settings FLUENT_DASHBOARD_QUICK_ACCESS_L...
[ "Returns", "a", "list", "of", "ListLink", "items", "to", "be", "added", "to", "Quick", "Access", "tab", ".", "Contains", ":", "-", "links", "to", "Organizations", "Projects", "and", "Users", ";", "-", "a", "link", "to", "shared", "service", "settings", "...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L88-L107
[ "def", "_get_quick_access_info", "(", "self", ")", ":", "quick_access_links", "=", "[", "]", "# add custom links", "quick_access_links", ".", "extend", "(", "settings", ".", "FLUENT_DASHBOARD_QUICK_ACCESS_LINKS", ")", "for", "model", "in", "(", "structure_models", "."...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
CustomIndexDashboard._get_erred_shared_settings_module
Returns a LinkList based module which contains link to shared service setting instances in ERRED state.
waldur_core/server/admin/dashboard.py
def _get_erred_shared_settings_module(self): """ Returns a LinkList based module which contains link to shared service setting instances in ERRED state. """ result_module = modules.LinkList(title=_('Shared provider settings in erred state')) result_module.template = 'admin/dashbo...
def _get_erred_shared_settings_module(self): """ Returns a LinkList based module which contains link to shared service setting instances in ERRED state. """ result_module = modules.LinkList(title=_('Shared provider settings in erred state')) result_module.template = 'admin/dashbo...
[ "Returns", "a", "LinkList", "based", "module", "which", "contains", "link", "to", "shared", "service", "setting", "instances", "in", "ERRED", "state", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L135-L155
[ "def", "_get_erred_shared_settings_module", "(", "self", ")", ":", "result_module", "=", "modules", ".", "LinkList", "(", "title", "=", "_", "(", "'Shared provider settings in erred state'", ")", ")", "result_module", ".", "template", "=", "'admin/dashboard/erred_link_l...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
CustomIndexDashboard._get_erred_resources_module
Returns a list of links to resources which are in ERRED state and linked to a shared service settings.
waldur_core/server/admin/dashboard.py
def _get_erred_resources_module(self): """ Returns a list of links to resources which are in ERRED state and linked to a shared service settings. """ result_module = modules.LinkList(title=_('Resources in erred state')) erred_state = structure_models.NewResource.States.ERRED ...
def _get_erred_resources_module(self): """ Returns a list of links to resources which are in ERRED state and linked to a shared service settings. """ result_module = modules.LinkList(title=_('Resources in erred state')) erred_state = structure_models.NewResource.States.ERRED ...
[ "Returns", "a", "list", "of", "links", "to", "resources", "which", "are", "in", "ERRED", "state", "and", "linked", "to", "a", "shared", "service", "settings", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L157-L181
[ "def", "_get_erred_resources_module", "(", "self", ")", ":", "result_module", "=", "modules", ".", "LinkList", "(", "title", "=", "_", "(", "'Resources in erred state'", ")", ")", "erred_state", "=", "structure_models", ".", "NewResource", ".", "States", ".", "E...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
serve
Django adapter. It has three arguments: #. ``request`` is a Django request object, #. ``tail`` is everything that's left from an URL, which adapter is attached to, #. ``server`` is a pyws server object. First two are the context of an application, function ``serve`` transforms them into a p...
src/pyws/adapters/_django.py
def serve(request, tail, server): """ Django adapter. It has three arguments: #. ``request`` is a Django request object, #. ``tail`` is everything that's left from an URL, which adapter is attached to, #. ``server`` is a pyws server object. First two are the context of an application, f...
def serve(request, tail, server): """ Django adapter. It has three arguments: #. ``request`` is a Django request object, #. ``tail`` is everything that's left from an URL, which adapter is attached to, #. ``server`` is a pyws server object. First two are the context of an application, f...
[ "Django", "adapter", ".", "It", "has", "three", "arguments", ":" ]
stepank/pyws
python
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/adapters/_django.py#L10-L44
[ "def", "serve", "(", "request", ",", "tail", ",", "server", ")", ":", "if", "request", ".", "GET", ":", "body", "=", "''", "else", ":", "try", ":", "body", "=", "request", ".", "body", "except", "AttributeError", ":", "body", "=", "request", ".", "...
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
train
NURESTFetcher.index
Get index of the given item Args: nurest_object (bambou.NURESTObject): the NURESTObject object to verify Returns: Returns the position of the object. Raises: Raise a ValueError exception if object is not present
bambou/nurest_fetcher.py
def index(self, nurest_object): """ Get index of the given item Args: nurest_object (bambou.NURESTObject): the NURESTObject object to verify Returns: Returns the position of the object. Raises: Raise a ValueError exception if ...
def index(self, nurest_object): """ Get index of the given item Args: nurest_object (bambou.NURESTObject): the NURESTObject object to verify Returns: Returns the position of the object. Raises: Raise a ValueError exception if ...
[ "Get", "index", "of", "the", "given", "item", "Args", ":", "nurest_object", "(", "bambou", ".", "NURESTObject", ")", ":", "the", "NURESTObject", "object", "to", "verify" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L78-L93
[ "def", "index", "(", "self", ",", "nurest_object", ")", ":", "for", "index", ",", "obj", "in", "enumerate", "(", "self", ")", ":", "if", "obj", ".", "equals", "(", "nurest_object", ")", ":", "return", "index", "raise", "ValueError", "(", "\"%s is not in...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTFetcher.fetcher_with_object
Register the fetcher for a served object. This method will fill the fetcher with `managed_class` instances Args: parent_object: the instance of the parent object to serve Returns: It returns the fetcher instance.
bambou/nurest_fetcher.py
def fetcher_with_object(cls, parent_object, relationship="child"): """ Register the fetcher for a served object. This method will fill the fetcher with `managed_class` instances Args: parent_object: the instance of the parent object to serve Returns: ...
def fetcher_with_object(cls, parent_object, relationship="child"): """ Register the fetcher for a served object. This method will fill the fetcher with `managed_class` instances Args: parent_object: the instance of the parent object to serve Returns: ...
[ "Register", "the", "fetcher", "for", "a", "served", "object", "." ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L183-L202
[ "def", "fetcher_with_object", "(", "cls", ",", "parent_object", ",", "relationship", "=", "\"child\"", ")", ":", "fetcher", "=", "cls", "(", ")", "fetcher", ".", "parent_object", "=", "parent_object", "fetcher", ".", "relationship", "=", "relationship", "rest_na...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTFetcher._prepare_headers
Prepare headers for the given request Args: request: the NURESTRequest to send filter: string order_by: string group_by: list of names page: int page_size: int
bambou/nurest_fetcher.py
def _prepare_headers(self, request, filter=None, order_by=None, group_by=[], page=None, page_size=None): """ Prepare headers for the given request Args: request: the NURESTRequest to send filter: string order_by: string group_by: list ...
def _prepare_headers(self, request, filter=None, order_by=None, group_by=[], page=None, page_size=None): """ Prepare headers for the given request Args: request: the NURESTRequest to send filter: string order_by: string group_by: list ...
[ "Prepare", "headers", "for", "the", "given", "request" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L222-L249
[ "def", "_prepare_headers", "(", "self", ",", "request", ",", "filter", "=", "None", ",", "order_by", "=", "None", ",", "group_by", "=", "[", "]", ",", "page", "=", "None", ",", "page_size", "=", "None", ")", ":", "if", "filter", ":", "request", ".", ...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTFetcher.fetch
Fetch objects according to given filter and page. Note: This method fetches all managed class objects and store them in local_name of the served object. which means that the parent object will hold them in a list. You can prevent this behavior ...
bambou/nurest_fetcher.py
def fetch(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None): """ Fetch objects according to given filter and page. Note: This method fetches all managed class objects and store them ...
def fetch(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None): """ Fetch objects according to given filter and page. Note: This method fetches all managed class objects and store them ...
[ "Fetch", "objects", "according", "to", "given", "filter", "and", "page", "." ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L256-L291
[ "def", "fetch", "(", "self", ",", "filter", "=", "None", ",", "order_by", "=", "None", ",", "group_by", "=", "[", "]", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "query_parameters", "=", "None", ",", "commit", "=", "True", ",", "...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTFetcher._did_fetch
Fetching objects has been done
bambou/nurest_fetcher.py
def _did_fetch(self, connection): """ Fetching objects has been done """ self.current_connection = connection response = connection.response should_commit = 'commit' not in connection.user_info or connection.user_info['commit'] if connection.response.status_code >= 400 and Bamb...
def _did_fetch(self, connection): """ Fetching objects has been done """ self.current_connection = connection response = connection.response should_commit = 'commit' not in connection.user_info or connection.user_info['commit'] if connection.response.status_code >= 400 and Bamb...
[ "Fetching", "objects", "has", "been", "done" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L293-L351
[ "def", "_did_fetch", "(", "self", ",", "connection", ")", ":", "self", ".", "current_connection", "=", "connection", "response", "=", "connection", ".", "response", "should_commit", "=", "'commit'", "not", "in", "connection", ".", "user_info", "or", "connection"...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTFetcher.get
Fetch object and directly return them Note: `get` won't put the fetched objects in the parent's children list. You cannot override this behavior. If you want to commit them in the parent you can use :method:vsdk.NURESTFetcher.fetch or manually add the list wi...
bambou/nurest_fetcher.py
def get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None): """ Fetch object and directly return them Note: `get` won't put the fetched objects in the parent's children list. You c...
def get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None): """ Fetch object and directly return them Note: `get` won't put the fetched objects in the parent's children list. You c...
[ "Fetch", "object", "and", "directly", "return", "them" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L353-L378
[ "def", "get", "(", "self", ",", "filter", "=", "None", ",", "order_by", "=", "None", ",", "group_by", "=", "[", "]", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "query_parameters", "=", "None", ",", "commit", "=", "True", ",", "as...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTFetcher.get_first
Fetch object and directly return the first one Note: `get_first` won't put the fetched object in the parent's children list. You cannot override this behavior. If you want to commit it in the parent you can use :method:vsdk.NURESTFetcher.fetch or manually add...
bambou/nurest_fetcher.py
def get_first(self, filter=None, order_by=None, group_by=[], query_parameters=None, commit=False, async=False, callback=None): """ Fetch object and directly return the first one Note: `get_first` won't put the fetched object in the parent's children list. You cannot ...
def get_first(self, filter=None, order_by=None, group_by=[], query_parameters=None, commit=False, async=False, callback=None): """ Fetch object and directly return the first one Note: `get_first` won't put the fetched object in the parent's children list. You cannot ...
[ "Fetch", "object", "and", "directly", "return", "the", "first", "one" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L380-L406
[ "def", "get_first", "(", "self", ",", "filter", "=", "None", ",", "order_by", "=", "None", ",", "group_by", "=", "[", "]", ",", "query_parameters", "=", "None", ",", "commit", "=", "False", ",", "async", "=", "False", ",", "callback", "=", "None", ")...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTFetcher.count
Get the total count of objects that can be fetched according to filter This method can be asynchronous and trigger the callback method when result is ready. Args: filter (string): string that represents a predicate fitler (eg. name == 'x') order_by (...
bambou/nurest_fetcher.py
def count(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, async=False, callback=None): """ Get the total count of objects that can be fetched according to filter This method can be asynchronous and trigger the callback method when result ...
def count(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, async=False, callback=None): """ Get the total count of objects that can be fetched according to filter This method can be asynchronous and trigger the callback method when result ...
[ "Get", "the", "total", "count", "of", "objects", "that", "can", "be", "fetched", "according", "to", "filter" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L408-L436
[ "def", "count", "(", "self", ",", "filter", "=", "None", ",", "order_by", "=", "None", ",", "group_by", "=", "[", "]", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "query_parameters", "=", "None", ",", "async", "=", "False", ",", "...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTFetcher.get_count
Get the total count of objects that can be fetched according to filter Args: filter (string): string that represents a predicate fitler (eg. name == 'x') order_by (string): string that represents an order by clause group_by (string): list of names for groupin...
bambou/nurest_fetcher.py
def get_count(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None): """ Get the total count of objects that can be fetched according to filter Args: filter (string): string that represents a predicate fitler (eg. name == 'x') ...
def get_count(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None): """ Get the total count of objects that can be fetched according to filter Args: filter (string): string that represents a predicate fitler (eg. name == 'x') ...
[ "Get", "the", "total", "count", "of", "objects", "that", "can", "be", "fetched", "according", "to", "filter" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L438-L452
[ "def", "get_count", "(", "self", ",", "filter", "=", "None", ",", "order_by", "=", "None", ",", "group_by", "=", "[", "]", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "query_parameters", "=", "None", ")", ":", "return", "self", ".",...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTFetcher._did_count
Called when count if finished
bambou/nurest_fetcher.py
def _did_count(self, connection): """ Called when count if finished """ self.current_connection = connection response = connection.response count = 0 callback = None if 'X-Nuage-Count' in response.headers: count = int(response.headers['X-Nuage-Count']) ...
def _did_count(self, connection): """ Called when count if finished """ self.current_connection = connection response = connection.response count = 0 callback = None if 'X-Nuage-Count' in response.headers: count = int(response.headers['X-Nuage-Count']) ...
[ "Called", "when", "count", "if", "finished" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L454-L479
[ "def", "_did_count", "(", "self", ",", "connection", ")", ":", "self", ".", "current_connection", "=", "connection", "response", "=", "connection", ".", "response", "count", "=", "0", "callback", "=", "None", "if", "'X-Nuage-Count'", "in", "response", ".", "...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTFetcher._send_content
Send a content array from the connection
bambou/nurest_fetcher.py
def _send_content(self, content, connection): """ Send a content array from the connection """ if connection: if connection.async: callback = connection.callbacks['remote'] if callback: callback(self, self.parent_object, content) ...
def _send_content(self, content, connection): """ Send a content array from the connection """ if connection: if connection.async: callback = connection.callbacks['remote'] if callback: callback(self, self.parent_object, content) ...
[ "Send", "a", "content", "array", "from", "the", "connection" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L481-L495
[ "def", "_send_content", "(", "self", ",", "content", ",", "connection", ")", ":", "if", "connection", ":", "if", "connection", ".", "async", ":", "callback", "=", "connection", ".", "callbacks", "[", "'remote'", "]", "if", "callback", ":", "callback", "(",...
d334fea23e384d3df8e552fe1849ad707941c666
train
ConsumptionDetails.update_configuration
Save how much consumables were used and update current configuration. Return True if configuration changed.
waldur_core/cost_tracking/models.py
def update_configuration(self, new_configuration): """ Save how much consumables were used and update current configuration. Return True if configuration changed. """ if new_configuration == self.configuration: return False now = timezone.now() if now.mon...
def update_configuration(self, new_configuration): """ Save how much consumables were used and update current configuration. Return True if configuration changed. """ if new_configuration == self.configuration: return False now = timezone.now() if now.mon...
[ "Save", "how", "much", "consumables", "were", "used", "and", "update", "current", "configuration", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/models.py#L288-L306
[ "def", "update_configuration", "(", "self", ",", "new_configuration", ")", ":", "if", "new_configuration", "==", "self", ".", "configuration", ":", "return", "False", "now", "=", "timezone", ".", "now", "(", ")", "if", "now", ".", "month", "!=", "self", "....
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ConsumptionDetails.consumed_in_month
How many resources were (or will be) consumed until end of the month
waldur_core/cost_tracking/models.py
def consumed_in_month(self): """ How many resources were (or will be) consumed until end of the month """ month_end = core_utils.month_end(datetime.date(self.price_estimate.year, self.price_estimate.month, 1)) return self._get_consumed(month_end)
def consumed_in_month(self): """ How many resources were (or will be) consumed until end of the month """ month_end = core_utils.month_end(datetime.date(self.price_estimate.year, self.price_estimate.month, 1)) return self._get_consumed(month_end)
[ "How", "many", "resources", "were", "(", "or", "will", "be", ")", "consumed", "until", "end", "of", "the", "month" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/models.py#L309-L312
[ "def", "consumed_in_month", "(", "self", ")", ":", "month_end", "=", "core_utils", ".", "month_end", "(", "datetime", ".", "date", "(", "self", ".", "price_estimate", ".", "year", ",", "self", ".", "price_estimate", ".", "month", ",", "1", ")", ")", "ret...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ConsumptionDetails._get_consumed
How many consumables were (or will be) used by resource until given time.
waldur_core/cost_tracking/models.py
def _get_consumed(self, time): """ How many consumables were (or will be) used by resource until given time. """ minutes_from_last_update = self._get_minutes_from_last_update(time) if minutes_from_last_update < 0: raise ConsumptionDetailCalculateError('Cannot calculate consumption if...
def _get_consumed(self, time): """ How many consumables were (or will be) used by resource until given time. """ minutes_from_last_update = self._get_minutes_from_last_update(time) if minutes_from_last_update < 0: raise ConsumptionDetailCalculateError('Cannot calculate consumption if...
[ "How", "many", "consumables", "were", "(", "or", "will", "be", ")", "used", "by", "resource", "until", "given", "time", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/models.py#L319-L329
[ "def", "_get_consumed", "(", "self", ",", "time", ")", ":", "minutes_from_last_update", "=", "self", ".", "_get_minutes_from_last_update", "(", "time", ")", "if", "minutes_from_last_update", "<", "0", ":", "raise", "ConsumptionDetailCalculateError", "(", "'Cannot calc...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ConsumptionDetails._get_minutes_from_last_update
How much minutes passed from last update to given time
waldur_core/cost_tracking/models.py
def _get_minutes_from_last_update(self, time): """ How much minutes passed from last update to given time """ time_from_last_update = time - self.last_update_time return int(time_from_last_update.total_seconds() / 60)
def _get_minutes_from_last_update(self, time): """ How much minutes passed from last update to given time """ time_from_last_update = time - self.last_update_time return int(time_from_last_update.total_seconds() / 60)
[ "How", "much", "minutes", "passed", "from", "last", "update", "to", "given", "time" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/models.py#L331-L334
[ "def", "_get_minutes_from_last_update", "(", "self", ",", "time", ")", ":", "time_from_last_update", "=", "time", "-", "self", ".", "last_update_time", "return", "int", "(", "time_from_last_update", ".", "total_seconds", "(", ")", "/", "60", ")" ]
d6c17a9592bb6c49c33567542eef8d099605a46a
train
PriceListItem.get_for_resource
Get list of all price list items that should be used for resource. If price list item is defined for service - return it, otherwise - return default price list item.
waldur_core/cost_tracking/models.py
def get_for_resource(resource): """ Get list of all price list items that should be used for resource. If price list item is defined for service - return it, otherwise - return default price list item. """ resource_content_type = ContentType.objects.get_for_model(resourc...
def get_for_resource(resource): """ Get list of all price list items that should be used for resource. If price list item is defined for service - return it, otherwise - return default price list item. """ resource_content_type = ContentType.objects.get_for_model(resourc...
[ "Get", "list", "of", "all", "price", "list", "items", "that", "should", "be", "used", "for", "resource", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/models.py#L457-L469
[ "def", "get_for_resource", "(", "resource", ")", ":", "resource_content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "resource", ")", "default_items", "=", "set", "(", "DefaultPriceListItem", ".", "objects", ".", "filter", "(", "resource_c...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
WaldurExtension.get_extensions
Get a list of available extensions
waldur_core/core/__init__.py
def get_extensions(cls): """ Get a list of available extensions """ assemblies = [] for waldur_extension in pkg_resources.iter_entry_points('waldur_extensions'): extension_module = waldur_extension.load() if inspect.isclass(extension_module) and issubclass(extension_modul...
def get_extensions(cls): """ Get a list of available extensions """ assemblies = [] for waldur_extension in pkg_resources.iter_entry_points('waldur_extensions'): extension_module = waldur_extension.load() if inspect.isclass(extension_module) and issubclass(extension_modul...
[ "Get", "a", "list", "of", "available", "extensions" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/__init__.py#L50-L61
[ "def", "get_extensions", "(", "cls", ")", ":", "assemblies", "=", "[", "]", "for", "waldur_extension", "in", "pkg_resources", ".", "iter_entry_points", "(", "'waldur_extensions'", ")", ":", "extension_module", "=", "waldur_extension", ".", "load", "(", ")", "if"...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ellipsis
Truncates a string to be at most max_length long.
qcore/helpers.py
def ellipsis(source, max_length): """Truncates a string to be at most max_length long.""" if max_length == 0 or len(source) <= max_length: return source return source[: max(0, max_length - 3)] + "..."
def ellipsis(source, max_length): """Truncates a string to be at most max_length long.""" if max_length == 0 or len(source) <= max_length: return source return source[: max(0, max_length - 3)] + "..."
[ "Truncates", "a", "string", "to", "be", "at", "most", "max_length", "long", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L232-L236
[ "def", "ellipsis", "(", "source", ",", "max_length", ")", ":", "if", "max_length", "==", "0", "or", "len", "(", "source", ")", "<=", "max_length", ":", "return", "source", "return", "source", "[", ":", "max", "(", "0", ",", "max_length", "-", "3", ")...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
safe_str
Wrapper for str() that catches exceptions.
qcore/helpers.py
def safe_str(source, max_length=0): """Wrapper for str() that catches exceptions.""" try: return ellipsis(str(source), max_length) except Exception as e: return ellipsis("<n/a: str(...) raised %s>" % e, max_length)
def safe_str(source, max_length=0): """Wrapper for str() that catches exceptions.""" try: return ellipsis(str(source), max_length) except Exception as e: return ellipsis("<n/a: str(...) raised %s>" % e, max_length)
[ "Wrapper", "for", "str", "()", "that", "catches", "exceptions", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L239-L244
[ "def", "safe_str", "(", "source", ",", "max_length", "=", "0", ")", ":", "try", ":", "return", "ellipsis", "(", "str", "(", "source", ")", ",", "max_length", ")", "except", "Exception", "as", "e", ":", "return", "ellipsis", "(", "\"<n/a: str(...) raised %s...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
safe_repr
Wrapper for repr() that catches exceptions.
qcore/helpers.py
def safe_repr(source, max_length=0): """Wrapper for repr() that catches exceptions.""" try: return ellipsis(repr(source), max_length) except Exception as e: return ellipsis("<n/a: repr(...) raised %s>" % e, max_length)
def safe_repr(source, max_length=0): """Wrapper for repr() that catches exceptions.""" try: return ellipsis(repr(source), max_length) except Exception as e: return ellipsis("<n/a: repr(...) raised %s>" % e, max_length)
[ "Wrapper", "for", "repr", "()", "that", "catches", "exceptions", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L247-L252
[ "def", "safe_repr", "(", "source", ",", "max_length", "=", "0", ")", ":", "try", ":", "return", "ellipsis", "(", "repr", "(", "source", ")", ",", "max_length", ")", "except", "Exception", "as", "e", ":", "return", "ellipsis", "(", "\"<n/a: repr(...) raised...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
dict_to_object
Returns an object with the key-value pairs in source as attributes.
qcore/helpers.py
def dict_to_object(source): """Returns an object with the key-value pairs in source as attributes.""" target = inspectable_class.InspectableClass() for k, v in source.items(): setattr(target, k, v) return target
def dict_to_object(source): """Returns an object with the key-value pairs in source as attributes.""" target = inspectable_class.InspectableClass() for k, v in source.items(): setattr(target, k, v) return target
[ "Returns", "an", "object", "with", "the", "key", "-", "value", "pairs", "in", "source", "as", "attributes", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L255-L260
[ "def", "dict_to_object", "(", "source", ")", ":", "target", "=", "inspectable_class", ".", "InspectableClass", "(", ")", "for", "k", ",", "v", "in", "source", ".", "items", "(", ")", ":", "setattr", "(", "target", ",", "k", ",", "v", ")", "return", "...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
copy_public_attrs
Shallow copies all public attributes from source_obj to dest_obj. Overwrites them if they already exist.
qcore/helpers.py
def copy_public_attrs(source_obj, dest_obj): """Shallow copies all public attributes from source_obj to dest_obj. Overwrites them if they already exist. """ for name, value in inspect.getmembers(source_obj): if not any(name.startswith(x) for x in ["_", "func", "im"]): setattr(dest_...
def copy_public_attrs(source_obj, dest_obj): """Shallow copies all public attributes from source_obj to dest_obj. Overwrites them if they already exist. """ for name, value in inspect.getmembers(source_obj): if not any(name.startswith(x) for x in ["_", "func", "im"]): setattr(dest_...
[ "Shallow", "copies", "all", "public", "attributes", "from", "source_obj", "to", "dest_obj", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L263-L271
[ "def", "copy_public_attrs", "(", "source_obj", ",", "dest_obj", ")", ":", "for", "name", ",", "value", "in", "inspect", ".", "getmembers", "(", "source_obj", ")", ":", "if", "not", "any", "(", "name", ".", "startswith", "(", "x", ")", "for", "x", "in",...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
object_from_string
Creates a Python class or function from its fully qualified name. :param name: A fully qualified name of a class or a function. In Python 3 this is only allowed to be of text type (unicode). In Python 2, both bytes and unicode are allowed. :return: A function or class object. This method i...
qcore/helpers.py
def object_from_string(name): """Creates a Python class or function from its fully qualified name. :param name: A fully qualified name of a class or a function. In Python 3 this is only allowed to be of text type (unicode). In Python 2, both bytes and unicode are allowed. :return: A functio...
def object_from_string(name): """Creates a Python class or function from its fully qualified name. :param name: A fully qualified name of a class or a function. In Python 3 this is only allowed to be of text type (unicode). In Python 2, both bytes and unicode are allowed. :return: A functio...
[ "Creates", "a", "Python", "class", "or", "function", "from", "its", "fully", "qualified", "name", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L274-L313
[ "def", "object_from_string", "(", "name", ")", ":", "if", "six", ".", "PY3", ":", "if", "not", "isinstance", "(", "name", ",", "str", ")", ":", "raise", "TypeError", "(", "\"name must be str, not %r\"", "%", "type", "(", "name", ")", ")", "else", ":", ...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
catchable_exceptions
Returns True if exceptions can be caught in the except clause. The exception can be caught if it is an Exception type or a tuple of exception types.
qcore/helpers.py
def catchable_exceptions(exceptions): """Returns True if exceptions can be caught in the except clause. The exception can be caught if it is an Exception type or a tuple of exception types. """ if isinstance(exceptions, type) and issubclass(exceptions, BaseException): return True if (...
def catchable_exceptions(exceptions): """Returns True if exceptions can be caught in the except clause. The exception can be caught if it is an Exception type or a tuple of exception types. """ if isinstance(exceptions, type) and issubclass(exceptions, BaseException): return True if (...
[ "Returns", "True", "if", "exceptions", "can", "be", "caught", "in", "the", "except", "clause", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L316-L333
[ "def", "catchable_exceptions", "(", "exceptions", ")", ":", "if", "isinstance", "(", "exceptions", ",", "type", ")", "and", "issubclass", "(", "exceptions", ",", "BaseException", ")", ":", "return", "True", "if", "(", "isinstance", "(", "exceptions", ",", "t...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
ScopedValue.override
Temporarily overrides the old value with the new one.
qcore/helpers.py
def override(self, value): """Temporarily overrides the old value with the new one.""" if self._value is not value: return _ScopedValueOverrideContext(self, value) else: return empty_context
def override(self, value): """Temporarily overrides the old value with the new one.""" if self._value is not value: return _ScopedValueOverrideContext(self, value) else: return empty_context
[ "Temporarily", "overrides", "the", "old", "value", "with", "the", "new", "one", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/helpers.py#L181-L186
[ "def", "override", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_value", "is", "not", "value", ":", "return", "_ScopedValueOverrideContext", "(", "self", ",", "value", ")", "else", ":", "return", "empty_context" ]
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
ActionsViewSet.validate_object_action
Execute validation for actions that are related to particular object
waldur_core/core/views.py
def validate_object_action(self, action_name, obj=None): """ Execute validation for actions that are related to particular object """ action_method = getattr(self, action_name) if not getattr(action_method, 'detail', False) and action_name not in ('update', 'partial_update', 'destroy'): ...
def validate_object_action(self, action_name, obj=None): """ Execute validation for actions that are related to particular object """ action_method = getattr(self, action_name) if not getattr(action_method, 'detail', False) and action_name not in ('update', 'partial_update', 'destroy'): ...
[ "Execute", "validation", "for", "actions", "that", "are", "related", "to", "particular", "object" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/views.py#L290-L299
[ "def", "validate_object_action", "(", "self", ",", "action_name", ",", "obj", "=", "None", ")", ":", "action_method", "=", "getattr", "(", "self", ",", "action_name", ")", "if", "not", "getattr", "(", "action_method", ",", "'detail'", ",", "False", ")", "a...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
Parser.row_dict
returns dictionary version of row using keys from self.field_map
PyParse.py
def row_dict(self, row): """returns dictionary version of row using keys from self.field_map""" d = {} for field_name,index in self.field_map.items(): d[field_name] = self.field_value(row, field_name) return d
def row_dict(self, row): """returns dictionary version of row using keys from self.field_map""" d = {} for field_name,index in self.field_map.items(): d[field_name] = self.field_value(row, field_name) return d
[ "returns", "dictionary", "version", "of", "row", "using", "keys", "from", "self", ".", "field_map" ]
mhjohnson/PyParse
python
https://github.com/mhjohnson/PyParse/blob/4a78160255d2d9ca95728ea655dd188ef74b5075/PyParse.py#L95-L100
[ "def", "row_dict", "(", "self", ",", "row", ")", ":", "d", "=", "{", "}", "for", "field_name", ",", "index", "in", "self", ".", "field_map", ".", "items", "(", ")", ":", "d", "[", "field_name", "]", "=", "self", ".", "field_value", "(", "row", ",...
4a78160255d2d9ca95728ea655dd188ef74b5075
train
Parser._dialect
returns detected dialect of filepath and sets self.has_header if not passed in __init__ kwargs Arguments: filepath (str): filepath of target csv file
PyParse.py
def _dialect(self, filepath): """returns detected dialect of filepath and sets self.has_header if not passed in __init__ kwargs Arguments: filepath (str): filepath of target csv file """ with open(filepath, self.read_mode) as csvfile: sample = csvfile.read...
def _dialect(self, filepath): """returns detected dialect of filepath and sets self.has_header if not passed in __init__ kwargs Arguments: filepath (str): filepath of target csv file """ with open(filepath, self.read_mode) as csvfile: sample = csvfile.read...
[ "returns", "detected", "dialect", "of", "filepath", "and", "sets", "self", ".", "has_header", "if", "not", "passed", "in", "__init__", "kwargs", "Arguments", ":", "filepath", "(", "str", ")", ":", "filepath", "of", "target", "csv", "file" ]
mhjohnson/PyParse
python
https://github.com/mhjohnson/PyParse/blob/4a78160255d2d9ca95728ea655dd188ef74b5075/PyParse.py#L102-L115
[ "def", "_dialect", "(", "self", ",", "filepath", ")", ":", "with", "open", "(", "filepath", ",", "self", ".", "read_mode", ")", "as", "csvfile", ":", "sample", "=", "csvfile", ".", "read", "(", "1024", ")", "dialect", "=", "csv", ".", "Sniffer", "(",...
4a78160255d2d9ca95728ea655dd188ef74b5075
train
_get_content_type_queryset
Get list of services content types
waldur_core/cost_tracking/admin.py
def _get_content_type_queryset(models_list): """ Get list of services content types """ content_type_ids = {c.id for c in ContentType.objects.get_for_models(*models_list).values()} return ContentType.objects.filter(id__in=content_type_ids)
def _get_content_type_queryset(models_list): """ Get list of services content types """ content_type_ids = {c.id for c in ContentType.objects.get_for_models(*models_list).values()} return ContentType.objects.filter(id__in=content_type_ids)
[ "Get", "list", "of", "services", "content", "types" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/admin.py#L15-L18
[ "def", "_get_content_type_queryset", "(", "models_list", ")", ":", "content_type_ids", "=", "{", "c", ".", "id", "for", "c", "in", "ContentType", ".", "objects", ".", "get_for_models", "(", "*", "models_list", ")", ".", "values", "(", ")", "}", "return", "...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
DefaultPriceListItemAdmin.init_registered
Create default price list items for each registered resource.
waldur_core/cost_tracking/admin.py
def init_registered(self, request): """ Create default price list items for each registered resource. """ created_items = models.DefaultPriceListItem.init_from_registered_resources() if created_items: message = ungettext( _('Price item was created: %s.') % created_it...
def init_registered(self, request): """ Create default price list items for each registered resource. """ created_items = models.DefaultPriceListItem.init_from_registered_resources() if created_items: message = ungettext( _('Price item was created: %s.') % created_it...
[ "Create", "default", "price", "list", "items", "for", "each", "registered", "resource", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/admin.py#L60-L74
[ "def", "init_registered", "(", "self", ",", "request", ")", ":", "created_items", "=", "models", ".", "DefaultPriceListItem", ".", "init_from_registered_resources", "(", ")", "if", "created_items", ":", "message", "=", "ungettext", "(", "_", "(", "'Price item was ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
DefaultPriceListItemAdmin.reinit_configurations
Re-initialize configuration for resource if it has been changed. This method should be called if resource consumption strategy was changed.
waldur_core/cost_tracking/admin.py
def reinit_configurations(self, request): """ Re-initialize configuration for resource if it has been changed. This method should be called if resource consumption strategy was changed. """ now = timezone.now() # Step 1. Collect all resources with changed configuration. ...
def reinit_configurations(self, request): """ Re-initialize configuration for resource if it has been changed. This method should be called if resource consumption strategy was changed. """ now = timezone.now() # Step 1. Collect all resources with changed configuration. ...
[ "Re", "-", "initialize", "configuration", "for", "resource", "if", "it", "has", "been", "changed", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/admin.py#L106-L133
[ "def", "reinit_configurations", "(", "self", ",", "request", ")", ":", "now", "=", "timezone", ".", "now", "(", ")", "# Step 1. Collect all resources with changed configuration.", "changed_resources", "=", "[", "]", "for", "resource_model", "in", "CostTrackingRegister",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
Sha1.encrypt
Encrypt the given message
bambou/utils/sha1.py
def encrypt(self, message): """ Encrypt the given message """ if not isinstance(message, (bytes, str)): raise TypeError return hashlib.sha1(message.encode('utf-8')).hexdigest()
def encrypt(self, message): """ Encrypt the given message """ if not isinstance(message, (bytes, str)): raise TypeError return hashlib.sha1(message.encode('utf-8')).hexdigest()
[ "Encrypt", "the", "given", "message" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/utils/sha1.py#L37-L43
[ "def", "encrypt", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "(", "bytes", ",", "str", ")", ")", ":", "raise", "TypeError", "return", "hashlib", ".", "sha1", "(", "message", ".", "encode", "(", "'utf-8'", "...
d334fea23e384d3df8e552fe1849ad707941c666
train
ScheduleMixin.save
Updates next_trigger_at field if: - instance become active - instance.schedule changed - instance is new
waldur_core/core/models.py
def save(self, *args, **kwargs): """ Updates next_trigger_at field if: - instance become active - instance.schedule changed - instance is new """ try: prev_instance = self.__class__.objects.get(pk=self.pk) except self.DoesNotExist: ...
def save(self, *args, **kwargs): """ Updates next_trigger_at field if: - instance become active - instance.schedule changed - instance is new """ try: prev_instance = self.__class__.objects.get(pk=self.pk) except self.DoesNotExist: ...
[ "Updates", "next_trigger_at", "field", "if", ":", "-", "instance", "become", "active", "-", "instance", ".", "schedule", "changed", "-", "instance", "is", "new" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/models.py#L115-L131
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "prev_instance", "=", "self", ".", "__class__", ".", "objects", ".", "get", "(", "pk", "=", "self", ".", "pk", ")", "except", "self", ".", "DoesNotExist", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ReversionMixin.get_version_fields
Get field that are tracked in object history versions.
waldur_core/core/models.py
def get_version_fields(self): """ Get field that are tracked in object history versions. """ options = reversion._get_options(self) return options.fields or [f.name for f in self._meta.fields if f not in options.exclude]
def get_version_fields(self): """ Get field that are tracked in object history versions. """ options = reversion._get_options(self) return options.fields or [f.name for f in self._meta.fields if f not in options.exclude]
[ "Get", "field", "that", "are", "tracked", "in", "object", "history", "versions", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/models.py#L380-L383
[ "def", "get_version_fields", "(", "self", ")", ":", "options", "=", "reversion", ".", "_get_options", "(", "self", ")", "return", "options", ".", "fields", "or", "[", "f", ".", "name", "for", "f", "in", "self", ".", "_meta", ".", "fields", "if", "f", ...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
ReversionMixin._is_version_duplicate
Define should new version be created for object or no. Reasons to provide custom check instead of default `ignore_revision_duplicates`: - no need to compare all revisions - it is OK if right object version exists in any revision; - need to compare object attributes (not serialized...
waldur_core/core/models.py
def _is_version_duplicate(self): """ Define should new version be created for object or no. Reasons to provide custom check instead of default `ignore_revision_duplicates`: - no need to compare all revisions - it is OK if right object version exists in any revision; - need...
def _is_version_duplicate(self): """ Define should new version be created for object or no. Reasons to provide custom check instead of default `ignore_revision_duplicates`: - no need to compare all revisions - it is OK if right object version exists in any revision; - need...
[ "Define", "should", "new", "version", "be", "created", "for", "object", "or", "no", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/models.py#L385-L401
[ "def", "_is_version_duplicate", "(", "self", ")", ":", "if", "self", ".", "id", "is", "None", ":", "return", "False", "try", ":", "latest_version", "=", "Version", ".", "objects", ".", "get_for_object", "(", "self", ")", ".", "latest", "(", "'revision__dat...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
DescendantMixin.get_ancestors
Get all unique instance ancestors
waldur_core/core/models.py
def get_ancestors(self): """ Get all unique instance ancestors """ ancestors = list(self.get_parents()) ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors]) ancestors_with_parents = [a for a in ancestors if isinstance(a, DescendantMixin)] for ancestor in anc...
def get_ancestors(self): """ Get all unique instance ancestors """ ancestors = list(self.get_parents()) ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors]) ancestors_with_parents = [a for a in ancestors if isinstance(a, DescendantMixin)] for ancestor in anc...
[ "Get", "all", "unique", "instance", "ancestors" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/core/models.py#L424-L433
[ "def", "get_ancestors", "(", "self", ")", ":", "ancestors", "=", "list", "(", "self", ".", "get_parents", "(", ")", ")", "ancestor_unique_attributes", "=", "set", "(", "[", "(", "a", ".", "__class__", ",", "a", ".", "id", ")", "for", "a", "in", "ance...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
NURESTConnection.has_succeed
Check if the connection has succeed Returns: Returns True if connection has succeed. False otherwise.
bambou/nurest_connection.py
def has_succeed(self): """ Check if the connection has succeed Returns: Returns True if connection has succeed. False otherwise. """ status_code = self._response.status_code if status_code in [HTTP_CODE_ZERO, HTTP_CODE_SUCCESS, HTTP_CODE_CRE...
def has_succeed(self): """ Check if the connection has succeed Returns: Returns True if connection has succeed. False otherwise. """ status_code = self._response.status_code if status_code in [HTTP_CODE_ZERO, HTTP_CODE_SUCCESS, HTTP_CODE_CRE...
[ "Check", "if", "the", "connection", "has", "succeed" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L233-L249
[ "def", "has_succeed", "(", "self", ")", ":", "status_code", "=", "self", ".", "_response", ".", "status_code", "if", "status_code", "in", "[", "HTTP_CODE_ZERO", ",", "HTTP_CODE_SUCCESS", ",", "HTTP_CODE_CREATED", ",", "HTTP_CODE_EMPTY", ",", "HTTP_CODE_MULTIPLE_CHOI...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTConnection.handle_response_for_connection
Check if the response succeed or not. In case of error, this method also print messages and set an array of errors in the response object. Returns: Returns True if the response has succeed, False otherwise
bambou/nurest_connection.py
def handle_response_for_connection(self, should_post=False): """ Check if the response succeed or not. In case of error, this method also print messages and set an array of errors in the response object. Returns: Returns True if the response has succeed, Fal...
def handle_response_for_connection(self, should_post=False): """ Check if the response succeed or not. In case of error, this method also print messages and set an array of errors in the response object. Returns: Returns True if the response has succeed, Fal...
[ "Check", "if", "the", "response", "succeed", "or", "not", "." ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L260-L305
[ "def", "handle_response_for_connection", "(", "self", ",", "should_post", "=", "False", ")", ":", "status_code", "=", "self", ".", "_response", ".", "status_code", "data", "=", "self", ".", "_response", ".", "data", "# TODO : Get errors in response data after bug fix ...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTConnection._did_receive_response
Called when a response is received
bambou/nurest_connection.py
def _did_receive_response(self, response): """ Called when a response is received """ try: data = response.json() except: data = None self._response = NURESTResponse(status_code=response.status_code, headers=response.headers, data=data, reason=response.reason) ...
def _did_receive_response(self, response): """ Called when a response is received """ try: data = response.json() except: data = None self._response = NURESTResponse(status_code=response.status_code, headers=response.headers, data=data, reason=response.reason) ...
[ "Called", "when", "a", "response", "is", "received" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L309-L326
[ "def", "_did_receive_response", "(", "self", ",", "response", ")", ":", "try", ":", "data", "=", "response", ".", "json", "(", ")", "except", ":", "data", "=", "None", "self", ".", "_response", "=", "NURESTResponse", "(", "status_code", "=", "response", ...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTConnection._did_timeout
Called when a resquest has timeout
bambou/nurest_connection.py
def _did_timeout(self): """ Called when a resquest has timeout """ bambou_logger.debug('Bambou %s on %s has timeout (timeout=%ss)..' % (self._request.method, self._request.url, self.timeout)) self._has_timeouted = True if self.async: self._callback(self) else: ...
def _did_timeout(self): """ Called when a resquest has timeout """ bambou_logger.debug('Bambou %s on %s has timeout (timeout=%ss)..' % (self._request.method, self._request.url, self.timeout)) self._has_timeouted = True if self.async: self._callback(self) else: ...
[ "Called", "when", "a", "resquest", "has", "timeout" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L328-L337
[ "def", "_did_timeout", "(", "self", ")", ":", "bambou_logger", ".", "debug", "(", "'Bambou %s on %s has timeout (timeout=%ss)..'", "%", "(", "self", ".", "_request", ".", "method", ",", "self", ".", "_request", ".", "url", ",", "self", ".", "timeout", ")", "...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTConnection._make_request
Make a synchronous request
bambou/nurest_connection.py
def _make_request(self, session=None): """ Make a synchronous request """ if session is None: session = NURESTSession.get_current_session() self._has_timeouted = False # Add specific headers controller = session.login_controller enterprise = controller.ent...
def _make_request(self, session=None): """ Make a synchronous request """ if session is None: session = NURESTSession.get_current_session() self._has_timeouted = False # Add specific headers controller = session.login_controller enterprise = controller.ent...
[ "Make", "a", "synchronous", "request" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L339-L392
[ "def", "_make_request", "(", "self", ",", "session", "=", "None", ")", ":", "if", "session", "is", "None", ":", "session", "=", "NURESTSession", ".", "get_current_session", "(", ")", "self", ".", "_has_timeouted", "=", "False", "# Add specific headers", "contr...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTConnection.__make_request
Encapsulate requests call
bambou/nurest_connection.py
def __make_request(self, requests_session, method, url, params, data, headers, certificate): """ Encapsulate requests call """ verify = False timeout = self.timeout try: # TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.usa.alcatel.com/browse/VSD-54...
def __make_request(self, requests_session, method, url, params, data, headers, certificate): """ Encapsulate requests call """ verify = False timeout = self.timeout try: # TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.usa.alcatel.com/browse/VSD-54...
[ "Encapsulate", "requests", "call" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L394-L425
[ "def", "__make_request", "(", "self", ",", "requests_session", ",", "method", ",", "url", ",", "params", ",", "data", ",", "headers", ",", "certificate", ")", ":", "verify", "=", "False", "timeout", "=", "self", ".", "timeout", "try", ":", "# TODO : Remove...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTConnection.start
Make an HTTP request with a specific method
bambou/nurest_connection.py
def start(self): """ Make an HTTP request with a specific method """ # TODO : Use Timeout here and _ignore_request_idle from .nurest_session import NURESTSession session = NURESTSession.get_current_session() if self.async: thread = threading.Thread(target=self._make...
def start(self): """ Make an HTTP request with a specific method """ # TODO : Use Timeout here and _ignore_request_idle from .nurest_session import NURESTSession session = NURESTSession.get_current_session() if self.async: thread = threading.Thread(target=self._make...
[ "Make", "an", "HTTP", "request", "with", "a", "specific", "method" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L427-L440
[ "def", "start", "(", "self", ")", ":", "# TODO : Use Timeout here and _ignore_request_idle", "from", ".", "nurest_session", "import", "NURESTSession", "session", "=", "NURESTSession", ".", "get_current_session", "(", ")", "if", "self", ".", "async", ":", "thread", "...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTConnection.reset
Reset the connection
bambou/nurest_connection.py
def reset(self): """ Reset the connection """ self._request = None self._response = None self._transaction_id = uuid.uuid4().hex
def reset(self): """ Reset the connection """ self._request = None self._response = None self._transaction_id = uuid.uuid4().hex
[ "Reset", "the", "connection" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_connection.py#L442-L448
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_request", "=", "None", "self", ".", "_response", "=", "None", "self", ".", "_transaction_id", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex" ]
d334fea23e384d3df8e552fe1849ad707941c666
train
ConsumptionDetailsQuerySet.create
Take configuration from previous month, it it exists. Set last_update_time equals to the beginning of the month.
waldur_core/cost_tracking/managers.py
def create(self, price_estimate): """ Take configuration from previous month, it it exists. Set last_update_time equals to the beginning of the month. """ kwargs = {} try: previous_price_estimate = price_estimate.get_previous() except ObjectDoesNotExist: ...
def create(self, price_estimate): """ Take configuration from previous month, it it exists. Set last_update_time equals to the beginning of the month. """ kwargs = {} try: previous_price_estimate = price_estimate.get_previous() except ObjectDoesNotExist: ...
[ "Take", "configuration", "from", "previous", "month", "it", "it", "exists", ".", "Set", "last_update_time", "equals", "to", "the", "beginning", "of", "the", "month", "." ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/managers.py#L59-L73
[ "def", "create", "(", "self", ",", "price_estimate", ")", ":", "kwargs", "=", "{", "}", "try", ":", "previous_price_estimate", "=", "price_estimate", ".", "get_previous", "(", ")", "except", "ObjectDoesNotExist", ":", "pass", "else", ":", "configuration", "=",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
BaseHookSerializer.get_fields
When static declaration is used, event type choices are fetched too early - even before all apps are initialized. As a result, some event types are missing. When dynamic declaration is used, all valid event types are available as choices.
waldur_core/logging/serializers.py
def get_fields(self): """ When static declaration is used, event type choices are fetched too early - even before all apps are initialized. As a result, some event types are missing. When dynamic declaration is used, all valid event types are available as choices. """ fie...
def get_fields(self): """ When static declaration is used, event type choices are fetched too early - even before all apps are initialized. As a result, some event types are missing. When dynamic declaration is used, all valid event types are available as choices. """ fie...
[ "When", "static", "declaration", "is", "used", "event", "type", "choices", "are", "fetched", "too", "early", "-", "even", "before", "all", "apps", "are", "initialized", ".", "As", "a", "result", "some", "event", "types", "are", "missing", ".", "When", "dyn...
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/serializers.py#L68-L79
[ "def", "get_fields", "(", "self", ")", ":", "fields", "=", "super", "(", "BaseHookSerializer", ",", "self", ")", ".", "get_fields", "(", ")", "fields", "[", "'event_types'", "]", "=", "serializers", ".", "MultipleChoiceField", "(", "choices", "=", "loggers",...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
PriceEstimateSerializer.build_nested_field
Use PriceEstimateSerializer to serialize estimate children
waldur_core/cost_tracking/serializers.py
def build_nested_field(self, field_name, relation_info, nested_depth): """ Use PriceEstimateSerializer to serialize estimate children """ if field_name != 'children': return super(PriceEstimateSerializer, self).build_nested_field(field_name, relation_info, nested_depth) field_class =...
def build_nested_field(self, field_name, relation_info, nested_depth): """ Use PriceEstimateSerializer to serialize estimate children """ if field_name != 'children': return super(PriceEstimateSerializer, self).build_nested_field(field_name, relation_info, nested_depth) field_class =...
[ "Use", "PriceEstimateSerializer", "to", "serialize", "estimate", "children" ]
opennode/waldur-core
python
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/serializers.py#L43-L49
[ "def", "build_nested_field", "(", "self", ",", "field_name", ",", "relation_info", ",", "nested_depth", ")", ":", "if", "field_name", "!=", "'children'", ":", "return", "super", "(", "PriceEstimateSerializer", ",", "self", ")", ".", "build_nested_field", "(", "f...
d6c17a9592bb6c49c33567542eef8d099605a46a
train
prepare_for_reraise
Prepares the exception for re-raising with reraise method. This method attaches type and traceback info to the error object so that reraise can properly reraise it using this info.
qcore/errors.py
def prepare_for_reraise(error, exc_info=None): """Prepares the exception for re-raising with reraise method. This method attaches type and traceback info to the error object so that reraise can properly reraise it using this info. """ if not hasattr(error, "_type_"): if exc_info is None: ...
def prepare_for_reraise(error, exc_info=None): """Prepares the exception for re-raising with reraise method. This method attaches type and traceback info to the error object so that reraise can properly reraise it using this info. """ if not hasattr(error, "_type_"): if exc_info is None: ...
[ "Prepares", "the", "exception", "for", "re", "-", "raising", "with", "reraise", "method", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/errors.py#L72-L84
[ "def", "prepare_for_reraise", "(", "error", ",", "exc_info", "=", "None", ")", ":", "if", "not", "hasattr", "(", "error", ",", "\"_type_\"", ")", ":", "if", "exc_info", "is", "None", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "error", ".",...
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
reraise
Re-raises the error that was processed by prepare_for_reraise earlier.
qcore/errors.py
def reraise(error): """Re-raises the error that was processed by prepare_for_reraise earlier.""" if hasattr(error, "_type_"): six.reraise(type(error), error, error._traceback) raise error
def reraise(error): """Re-raises the error that was processed by prepare_for_reraise earlier.""" if hasattr(error, "_type_"): six.reraise(type(error), error, error._traceback) raise error
[ "Re", "-", "raises", "the", "error", "that", "was", "processed", "by", "prepare_for_reraise", "earlier", "." ]
quora/qcore
python
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/errors.py#L90-L94
[ "def", "reraise", "(", "error", ")", ":", "if", "hasattr", "(", "error", ",", "\"_type_\"", ")", ":", "six", ".", "reraise", "(", "type", "(", "error", ")", ",", "error", ",", "error", ".", "_traceback", ")", "raise", "error" ]
fa5cd438eea554db35fd29cbc8dfbde69f09961c
train
register
Creates a registrator that, being called with a function as the only argument, wraps a function with ``pyws.functions.NativeFunctionAdapter`` and registers it to the server. Arguments are exactly the same as for ``pyws.functions.NativeFunctionAdapter`` except that you can pass an additional keyword argu...
src/pyws/functions/register.py
def register(*args, **kwargs): """ Creates a registrator that, being called with a function as the only argument, wraps a function with ``pyws.functions.NativeFunctionAdapter`` and registers it to the server. Arguments are exactly the same as for ``pyws.functions.NativeFunctionAdapter`` except that ...
def register(*args, **kwargs): """ Creates a registrator that, being called with a function as the only argument, wraps a function with ``pyws.functions.NativeFunctionAdapter`` and registers it to the server. Arguments are exactly the same as for ``pyws.functions.NativeFunctionAdapter`` except that ...
[ "Creates", "a", "registrator", "that", "being", "called", "with", "a", "function", "as", "the", "only", "argument", "wraps", "a", "function", "with", "pyws", ".", "functions", ".", "NativeFunctionAdapter", "and", "registers", "it", "to", "the", "server", ".", ...
stepank/pyws
python
https://github.com/stepank/pyws/blob/ff39133aabeb56bbb08d66286ac0cc8731eda7dd/src/pyws/functions/register.py#L9-L47
[ "def", "register", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "callable", "(", "args", "[", "0", "]", ")", ":", "raise", "ConfigurationError", "(", "'You might have tried to decorate a function directly with '", "'@register which is ...
ff39133aabeb56bbb08d66286ac0cc8731eda7dd
train
NUMetaRESTObject.rest_name
Represents a singular REST name
bambou/nurest_object.py
def rest_name(cls): """ Represents a singular REST name """ if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject": return "Not Implemented" if cls.__rest_name__ is None: raise NotImplementedError('%s has no defined name. Implement rest_name prop...
def rest_name(cls): """ Represents a singular REST name """ if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject": return "Not Implemented" if cls.__rest_name__ is None: raise NotImplementedError('%s has no defined name. Implement rest_name prop...
[ "Represents", "a", "singular", "REST", "name" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L51-L60
[ "def", "rest_name", "(", "cls", ")", ":", "if", "cls", ".", "__name__", "==", "\"NURESTRootObject\"", "or", "cls", ".", "__name__", "==", "\"NURESTObject\"", ":", "return", "\"Not Implemented\"", "if", "cls", ".", "__rest_name__", "is", "None", ":", "raise", ...
d334fea23e384d3df8e552fe1849ad707941c666
train
NUMetaRESTObject.resource_name
Represents the resource name
bambou/nurest_object.py
def resource_name(cls): """ Represents the resource name """ if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject": return "Not Implemented" if cls.__resource_name__ is None: raise NotImplementedError('%s has no defined resource name. Implement ...
def resource_name(cls): """ Represents the resource name """ if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject": return "Not Implemented" if cls.__resource_name__ is None: raise NotImplementedError('%s has no defined resource name. Implement ...
[ "Represents", "the", "resource", "name" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L63-L72
[ "def", "resource_name", "(", "cls", ")", ":", "if", "cls", ".", "__name__", "==", "\"NURESTRootObject\"", "or", "cls", ".", "__name__", "==", "\"NURESTObject\"", ":", "return", "\"Not Implemented\"", "if", "cls", ".", "__resource_name__", "is", "None", ":", "r...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTObject._compute_args
Compute the arguments Try to import attributes from data. Otherwise compute kwargs arguments. Args: data: a dict() kwargs: a list of arguments
bambou/nurest_object.py
def _compute_args(self, data=dict(), **kwargs): """ Compute the arguments Try to import attributes from data. Otherwise compute kwargs arguments. Args: data: a dict() kwargs: a list of arguments """ for name, remote_attribute...
def _compute_args(self, data=dict(), **kwargs): """ Compute the arguments Try to import attributes from data. Otherwise compute kwargs arguments. Args: data: a dict() kwargs: a list of arguments """ for name, remote_attribute...
[ "Compute", "the", "arguments" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L116-L136
[ "def", "_compute_args", "(", "self", ",", "data", "=", "dict", "(", ")", ",", "*", "*", "kwargs", ")", ":", "for", "name", ",", "remote_attribute", "in", "self", ".", "_attributes", ".", "items", "(", ")", ":", "default_value", "=", "BambouConfig", "."...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTObject.children_rest_names
Gets the list of all possible children ReST names. Returns: list: list containing all possible rest names as string Example: >>> entity = NUEntity() >>> entity.children_rest_names ["foo", "bar"]
bambou/nurest_object.py
def children_rest_names(self): """ Gets the list of all possible children ReST names. Returns: list: list containing all possible rest names as string Example: >>> entity = NUEntity() >>> entity.children_rest_names ["foo",...
def children_rest_names(self): """ Gets the list of all possible children ReST names. Returns: list: list containing all possible rest names as string Example: >>> entity = NUEntity() >>> entity.children_rest_names ["foo",...
[ "Gets", "the", "list", "of", "all", "possible", "children", "ReST", "names", "." ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L266-L283
[ "def", "children_rest_names", "(", "self", ")", ":", "names", "=", "[", "]", "for", "fetcher", "in", "self", ".", "fetchers", ":", "names", ".", "append", "(", "fetcher", ".", "__class__", ".", "managed_object_rest_name", "(", ")", ")", "return", "names" ]
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTObject.get_resource_url
Get resource complete url
bambou/nurest_object.py
def get_resource_url(self): """ Get resource complete url """ name = self.__class__.resource_name url = self.__class__.rest_base_url() if self.id is not None: return "%s/%s/%s" % (url, name, self.id) return "%s/%s" % (url, name)
def get_resource_url(self): """ Get resource complete url """ name = self.__class__.resource_name url = self.__class__.rest_base_url() if self.id is not None: return "%s/%s/%s" % (url, name, self.id) return "%s/%s" % (url, name)
[ "Get", "resource", "complete", "url" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L309-L318
[ "def", "get_resource_url", "(", "self", ")", ":", "name", "=", "self", ".", "__class__", ".", "resource_name", "url", "=", "self", ".", "__class__", ".", "rest_base_url", "(", ")", "if", "self", ".", "id", "is", "not", "None", ":", "return", "\"%s/%s/%s\...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTObject.validate
Validate the current object attributes. Check all attributes and store errors Returns: Returns True if all attibutes of the object respect contraints. Returns False otherwise and store error in errors dict.
bambou/nurest_object.py
def validate(self): """ Validate the current object attributes. Check all attributes and store errors Returns: Returns True if all attibutes of the object respect contraints. Returns False otherwise and store error in errors dict. ...
def validate(self): """ Validate the current object attributes. Check all attributes and store errors Returns: Returns True if all attibutes of the object respect contraints. Returns False otherwise and store error in errors dict. ...
[ "Validate", "the", "current", "object", "attributes", "." ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L330-L379
[ "def", "validate", "(", "self", ")", ":", "self", ".", "_attribute_errors", "=", "dict", "(", ")", "# Reset validation errors", "for", "local_name", ",", "attribute", "in", "self", ".", "_attributes", ".", "items", "(", ")", ":", "value", "=", "getattr", "...
d334fea23e384d3df8e552fe1849ad707941c666
train
NURESTObject.expose_attribute
Expose local_name as remote_name An exposed attribute `local_name` will be sent within the HTTP request as a `remote_name`
bambou/nurest_object.py
def expose_attribute(self, local_name, attribute_type, remote_name=None, display_name=None, is_required=False, is_readonly=False, max_length=None, min_length=None, is_identifier=False, choices=None, is_unique=False, is_email=False, is_login=False, is_editable=True, is_password=False, can_order=False, can_search=False, ...
def expose_attribute(self, local_name, attribute_type, remote_name=None, display_name=None, is_required=False, is_readonly=False, max_length=None, min_length=None, is_identifier=False, choices=None, is_unique=False, is_email=False, is_login=False, is_editable=True, is_password=False, can_order=False, can_search=False, ...
[ "Expose", "local_name", "as", "remote_name" ]
nuagenetworks/bambou
python
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_object.py#L432-L464
[ "def", "expose_attribute", "(", "self", ",", "local_name", ",", "attribute_type", ",", "remote_name", "=", "None", ",", "display_name", "=", "None", ",", "is_required", "=", "False", ",", "is_readonly", "=", "False", ",", "max_length", "=", "None", ",", "min...
d334fea23e384d3df8e552fe1849ad707941c666