repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
openstack/horizon
openstack_dashboard/dashboards/admin/flavors/tables.py
FlavorFilterAction.filter
def filter(self, table, flavors, filter_string): """Really naive case-insensitive search.""" q = filter_string.lower() def comp(flavor): return q in flavor.name.lower() return filter(comp, flavors)
python
def filter(self, table, flavors, filter_string): """Really naive case-insensitive search.""" q = filter_string.lower() def comp(flavor): return q in flavor.name.lower() return filter(comp, flavors)
[ "def", "filter", "(", "self", ",", "table", ",", "flavors", ",", "filter_string", ")", ":", "q", "=", "filter_string", ".", "lower", "(", ")", "def", "comp", "(", "flavor", ")", ":", "return", "q", "in", "flavor", ".", "name", ".", "lower", "(", ")...
Really naive case-insensitive search.
[ "Really", "naive", "case", "-", "insensitive", "search", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/admin/flavors/tables.py#L104-L111
train
216,000
openstack/horizon
horizon/middleware/operation_log.py
OperationLogMiddleware._process_response
def _process_response(self, request, response): """Log user operation.""" log_format = self._get_log_format(request) if not log_format: return response params = self._get_parameters_from_request(request) # log a message displayed to user messages = django_messages.get_messages(request) result_message = None if messages: result_message = ', '.join('%s: %s' % (message.tags, message) for message in messages) elif 'action' in request.POST: result_message = request.POST['action'] params['message'] = result_message params['http_status'] = response.status_code self.OPERATION_LOG.info(log_format, params) return response
python
def _process_response(self, request, response): """Log user operation.""" log_format = self._get_log_format(request) if not log_format: return response params = self._get_parameters_from_request(request) # log a message displayed to user messages = django_messages.get_messages(request) result_message = None if messages: result_message = ', '.join('%s: %s' % (message.tags, message) for message in messages) elif 'action' in request.POST: result_message = request.POST['action'] params['message'] = result_message params['http_status'] = response.status_code self.OPERATION_LOG.info(log_format, params) return response
[ "def", "_process_response", "(", "self", ",", "request", ",", "response", ")", ":", "log_format", "=", "self", ".", "_get_log_format", "(", "request", ")", "if", "not", "log_format", ":", "return", "response", "params", "=", "self", ".", "_get_parameters_from_...
Log user operation.
[ "Log", "user", "operation", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/operation_log.py#L87-L107
train
216,001
openstack/horizon
horizon/middleware/operation_log.py
OperationLogMiddleware.process_exception
def process_exception(self, request, exception): """Log error info when exception occurred.""" log_format = self._get_log_format(request) if log_format is None: return params = self._get_parameters_from_request(request, True) params['message'] = exception params['http_status'] = '-' self.OPERATION_LOG.info(log_format, params)
python
def process_exception(self, request, exception): """Log error info when exception occurred.""" log_format = self._get_log_format(request) if log_format is None: return params = self._get_parameters_from_request(request, True) params['message'] = exception params['http_status'] = '-' self.OPERATION_LOG.info(log_format, params)
[ "def", "process_exception", "(", "self", ",", "request", ",", "exception", ")", ":", "log_format", "=", "self", ".", "_get_log_format", "(", "request", ")", "if", "log_format", "is", "None", ":", "return", "params", "=", "self", ".", "_get_parameters_from_requ...
Log error info when exception occurred.
[ "Log", "error", "info", "when", "exception", "occurred", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/operation_log.py#L109-L119
train
216,002
openstack/horizon
horizon/middleware/operation_log.py
OperationLogMiddleware._get_log_format
def _get_log_format(self, request): """Return operation log format.""" user = getattr(request, 'user', None) if not user: return if not request.user.is_authenticated: return method = request.method.upper() if not (method in self.target_methods): return request_url = urlparse.unquote(request.path) for rule in self._ignored_urls: if rule.search(request_url): return return self.format
python
def _get_log_format(self, request): """Return operation log format.""" user = getattr(request, 'user', None) if not user: return if not request.user.is_authenticated: return method = request.method.upper() if not (method in self.target_methods): return request_url = urlparse.unquote(request.path) for rule in self._ignored_urls: if rule.search(request_url): return return self.format
[ "def", "_get_log_format", "(", "self", ",", "request", ")", ":", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "if", "not", "user", ":", "return", "if", "not", "request", ".", "user", ".", "is_authenticated", ":", "return", "...
Return operation log format.
[ "Return", "operation", "log", "format", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/operation_log.py#L121-L135
train
216,003
openstack/horizon
horizon/middleware/operation_log.py
OperationLogMiddleware._get_parameters_from_request
def _get_parameters_from_request(self, request, exception=False): """Get parameters to log in OPERATION_LOG.""" user = request.user referer_url = None try: referer_dic = urlparse.urlsplit( urlparse.unquote(request.META.get('HTTP_REFERER'))) referer_url = referer_dic[2] if referer_dic[3]: referer_url += "?" + referer_dic[3] if isinstance(referer_url, str): referer_url = referer_url.decode('utf-8') except Exception: pass request_url = urlparse.unquote(request.path) if request.META['QUERY_STRING']: request_url += '?' + request.META['QUERY_STRING'] return { 'client_ip': request.META.get('REMOTE_ADDR', None), 'domain_name': getattr(user, 'domain_name', None), 'domain_id': getattr(user, 'domain_id', None), 'project_name': getattr(user, 'project_name', None), 'project_id': getattr(user, 'project_id', None), 'user_name': getattr(user, 'username', None), 'user_id': request.session.get('user_id', None), 'request_scheme': request.scheme, 'referer_url': referer_url, 'request_url': request_url, 'method': request.method if not exception else None, 'param': self._get_request_param(request), }
python
def _get_parameters_from_request(self, request, exception=False): """Get parameters to log in OPERATION_LOG.""" user = request.user referer_url = None try: referer_dic = urlparse.urlsplit( urlparse.unquote(request.META.get('HTTP_REFERER'))) referer_url = referer_dic[2] if referer_dic[3]: referer_url += "?" + referer_dic[3] if isinstance(referer_url, str): referer_url = referer_url.decode('utf-8') except Exception: pass request_url = urlparse.unquote(request.path) if request.META['QUERY_STRING']: request_url += '?' + request.META['QUERY_STRING'] return { 'client_ip': request.META.get('REMOTE_ADDR', None), 'domain_name': getattr(user, 'domain_name', None), 'domain_id': getattr(user, 'domain_id', None), 'project_name': getattr(user, 'project_name', None), 'project_id': getattr(user, 'project_id', None), 'user_name': getattr(user, 'username', None), 'user_id': request.session.get('user_id', None), 'request_scheme': request.scheme, 'referer_url': referer_url, 'request_url': request_url, 'method': request.method if not exception else None, 'param': self._get_request_param(request), }
[ "def", "_get_parameters_from_request", "(", "self", ",", "request", ",", "exception", "=", "False", ")", ":", "user", "=", "request", ".", "user", "referer_url", "=", "None", "try", ":", "referer_dic", "=", "urlparse", ".", "urlsplit", "(", "urlparse", ".", ...
Get parameters to log in OPERATION_LOG.
[ "Get", "parameters", "to", "log", "in", "OPERATION_LOG", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/operation_log.py#L137-L167
train
216,004
openstack/horizon
horizon/middleware/operation_log.py
OperationLogMiddleware._get_request_param
def _get_request_param(self, request): """Change POST data to JSON string and mask data.""" params = {} try: params = request.POST.copy() if not params: params = json.loads(request.body) except Exception: pass for key in params: # replace a value to a masked characters if key in self.mask_fields: params[key] = '*' * 8 # when a file uploaded (E.g create image) files = request.FILES.values() if list(files): filenames = ', '.join( [up_file.name for up_file in files]) params['file_name'] = filenames try: return json.dumps(params, ensure_ascii=False) except Exception: return 'Unserializable Object'
python
def _get_request_param(self, request): """Change POST data to JSON string and mask data.""" params = {} try: params = request.POST.copy() if not params: params = json.loads(request.body) except Exception: pass for key in params: # replace a value to a masked characters if key in self.mask_fields: params[key] = '*' * 8 # when a file uploaded (E.g create image) files = request.FILES.values() if list(files): filenames = ', '.join( [up_file.name for up_file in files]) params['file_name'] = filenames try: return json.dumps(params, ensure_ascii=False) except Exception: return 'Unserializable Object'
[ "def", "_get_request_param", "(", "self", ",", "request", ")", ":", "params", "=", "{", "}", "try", ":", "params", "=", "request", ".", "POST", ".", "copy", "(", ")", "if", "not", "params", ":", "params", "=", "json", ".", "loads", "(", "request", ...
Change POST data to JSON string and mask data.
[ "Change", "POST", "data", "to", "JSON", "string", "and", "mask", "data", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/operation_log.py#L169-L193
train
216,005
openstack/horizon
openstack_dashboard/dashboards/identity/projects/workflows.py
UpdateProject._update_project
def _update_project(self, request, data): """Update project info""" domain_id = identity.get_domain_id_for_operation(request) try: project_id = data['project_id'] # add extra information if keystone.VERSIONS.active >= 3: EXTRA_INFO = getattr(settings, 'PROJECT_TABLE_EXTRA_INFO', {}) kwargs = dict((key, data.get(key)) for key in EXTRA_INFO) else: kwargs = {} return api.keystone.tenant_update( request, project_id, name=data['name'], description=data['description'], enabled=data['enabled'], domain=domain_id, **kwargs) except exceptions.Conflict: msg = _('Project name "%s" is already used.') % data['name'] self.failure_message = msg return except Exception as e: LOG.debug('Project update failed: %s', e) exceptions.handle(request, ignore=True) return
python
def _update_project(self, request, data): """Update project info""" domain_id = identity.get_domain_id_for_operation(request) try: project_id = data['project_id'] # add extra information if keystone.VERSIONS.active >= 3: EXTRA_INFO = getattr(settings, 'PROJECT_TABLE_EXTRA_INFO', {}) kwargs = dict((key, data.get(key)) for key in EXTRA_INFO) else: kwargs = {} return api.keystone.tenant_update( request, project_id, name=data['name'], description=data['description'], enabled=data['enabled'], domain=domain_id, **kwargs) except exceptions.Conflict: msg = _('Project name "%s" is already used.') % data['name'] self.failure_message = msg return except Exception as e: LOG.debug('Project update failed: %s', e) exceptions.handle(request, ignore=True) return
[ "def", "_update_project", "(", "self", ",", "request", ",", "data", ")", ":", "domain_id", "=", "identity", ".", "get_domain_id_for_operation", "(", "request", ")", "try", ":", "project_id", "=", "data", "[", "'project_id'", "]", "# add extra information", "if",...
Update project info
[ "Update", "project", "info" ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/identity/projects/workflows.py#L683-L711
train
216,006
openstack/horizon
horizon/tables/formset.py
FormsetDataTableMixin.get_required_columns
def get_required_columns(self): """Lists names of columns that have required fields.""" required_columns = [] if self.formset_class: empty_form = self.get_formset().empty_form for column in self.columns.values(): field = empty_form.fields.get(column.name) if field and field.required: required_columns.append(column.name) return required_columns
python
def get_required_columns(self): """Lists names of columns that have required fields.""" required_columns = [] if self.formset_class: empty_form = self.get_formset().empty_form for column in self.columns.values(): field = empty_form.fields.get(column.name) if field and field.required: required_columns.append(column.name) return required_columns
[ "def", "get_required_columns", "(", "self", ")", ":", "required_columns", "=", "[", "]", "if", "self", ".", "formset_class", ":", "empty_form", "=", "self", ".", "get_formset", "(", ")", ".", "empty_form", "for", "column", "in", "self", ".", "columns", "."...
Lists names of columns that have required fields.
[ "Lists", "names", "of", "columns", "that", "have", "required", "fields", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/formset.py#L87-L96
train
216,007
openstack/horizon
horizon/tables/formset.py
FormsetDataTableMixin._get_formset_data
def _get_formset_data(self): """Formats the self.filtered_data in a way suitable for a formset.""" data = [] for datum in self.filtered_data: form_data = {} for column in self.columns.values(): value = column.get_data(datum) form_data[column.name] = value form_data['id'] = self.get_object_id(datum) data.append(form_data) return data
python
def _get_formset_data(self): """Formats the self.filtered_data in a way suitable for a formset.""" data = [] for datum in self.filtered_data: form_data = {} for column in self.columns.values(): value = column.get_data(datum) form_data[column.name] = value form_data['id'] = self.get_object_id(datum) data.append(form_data) return data
[ "def", "_get_formset_data", "(", "self", ")", ":", "data", "=", "[", "]", "for", "datum", "in", "self", ".", "filtered_data", ":", "form_data", "=", "{", "}", "for", "column", "in", "self", ".", "columns", ".", "values", "(", ")", ":", "value", "=", ...
Formats the self.filtered_data in a way suitable for a formset.
[ "Formats", "the", "self", ".", "filtered_data", "in", "a", "way", "suitable", "for", "a", "formset", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/formset.py#L98-L108
train
216,008
openstack/horizon
horizon/tables/formset.py
FormsetDataTableMixin.get_rows
def get_rows(self): """Return the row data for this table broken out by columns. The row objects get an additional ``form`` parameter, with the formset form corresponding to that row. """ try: rows = [] if self.formset_class is None: formset = [] else: formset = self.get_formset() formset.is_valid() for datum, form in six.moves.zip_longest(self.filtered_data, formset): row = self._meta.row_class(self, datum, form) if self.get_object_id(datum) == self.current_item_id: self.selected = True row.classes.append('current_selected') rows.append(row) except Exception: # Exceptions can be swallowed at the template level here, # re-raising as a TemplateSyntaxError makes them visible. LOG.exception("Error while rendering table rows.") exc_info = sys.exc_info() raise six.reraise(template.TemplateSyntaxError, exc_info[1], exc_info[2]) return rows
python
def get_rows(self): """Return the row data for this table broken out by columns. The row objects get an additional ``form`` parameter, with the formset form corresponding to that row. """ try: rows = [] if self.formset_class is None: formset = [] else: formset = self.get_formset() formset.is_valid() for datum, form in six.moves.zip_longest(self.filtered_data, formset): row = self._meta.row_class(self, datum, form) if self.get_object_id(datum) == self.current_item_id: self.selected = True row.classes.append('current_selected') rows.append(row) except Exception: # Exceptions can be swallowed at the template level here, # re-raising as a TemplateSyntaxError makes them visible. LOG.exception("Error while rendering table rows.") exc_info = sys.exc_info() raise six.reraise(template.TemplateSyntaxError, exc_info[1], exc_info[2]) return rows
[ "def", "get_rows", "(", "self", ")", ":", "try", ":", "rows", "=", "[", "]", "if", "self", ".", "formset_class", "is", "None", ":", "formset", "=", "[", "]", "else", ":", "formset", "=", "self", ".", "get_formset", "(", ")", "formset", ".", "is_val...
Return the row data for this table broken out by columns. The row objects get an additional ``form`` parameter, with the formset form corresponding to that row.
[ "Return", "the", "row", "data", "for", "this", "table", "broken", "out", "by", "columns", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/formset.py#L126-L153
train
216,009
openstack/horizon
openstack_dashboard/api/keystone.py
keystoneclient
def keystoneclient(request, admin=False): """Returns a client connected to the Keystone backend. Several forms of authentication are supported: * Username + password -> Unscoped authentication * Username + password + tenant id -> Scoped authentication * Unscoped token -> Unscoped authentication * Unscoped token + tenant id -> Scoped authentication * Scoped token -> Scoped authentication Available services and data from the backend will vary depending on whether the authentication was scoped or unscoped. Lazy authentication if an ``endpoint`` parameter is provided. Calls requiring the admin endpoint should have ``admin=True`` passed in as a keyword argument. The client is cached so that subsequent API calls during the same request/response cycle don't have to be re-authenticated. """ client_version = VERSIONS.get_active_version() user = request.user token_id = user.token.id if is_multi_domain_enabled(): # Cloud Admin, Domain Admin or Mixed Domain Admin if is_domain_admin(request): domain_token = request.session.get('domain_token') if domain_token: token_id = getattr(domain_token, 'auth_token', None) if admin: if not policy.check((("identity", "admin_required"),), request): raise exceptions.NotAuthorized endpoint_type = 'adminURL' else: endpoint_type = getattr(settings, 'OPENSTACK_ENDPOINT_TYPE', 'publicURL') # Take care of client connection caching/fetching a new client. # Admin vs. non-admin clients are cached separately for token matching. cache_attr = "_keystoneclient_admin" if admin \ else backend.KEYSTONE_CLIENT_ATTR if (hasattr(request, cache_attr) and (not user.token.id or getattr(request, cache_attr).auth_token == user.token.id)): conn = getattr(request, cache_attr) else: endpoint = _get_endpoint_url(request, endpoint_type) verify = not getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False) cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None) verify = verify and cacert LOG.debug("Creating a new keystoneclient connection to %s.", endpoint) remote_addr = request.environ.get('REMOTE_ADDR', '') token_auth = token_endpoint.Token(endpoint=endpoint, token=token_id) keystone_session = session.Session(auth=token_auth, original_ip=remote_addr, verify=verify) conn = client_version['client'].Client(session=keystone_session, debug=settings.DEBUG) setattr(request, cache_attr, conn) return conn
python
def keystoneclient(request, admin=False): """Returns a client connected to the Keystone backend. Several forms of authentication are supported: * Username + password -> Unscoped authentication * Username + password + tenant id -> Scoped authentication * Unscoped token -> Unscoped authentication * Unscoped token + tenant id -> Scoped authentication * Scoped token -> Scoped authentication Available services and data from the backend will vary depending on whether the authentication was scoped or unscoped. Lazy authentication if an ``endpoint`` parameter is provided. Calls requiring the admin endpoint should have ``admin=True`` passed in as a keyword argument. The client is cached so that subsequent API calls during the same request/response cycle don't have to be re-authenticated. """ client_version = VERSIONS.get_active_version() user = request.user token_id = user.token.id if is_multi_domain_enabled(): # Cloud Admin, Domain Admin or Mixed Domain Admin if is_domain_admin(request): domain_token = request.session.get('domain_token') if domain_token: token_id = getattr(domain_token, 'auth_token', None) if admin: if not policy.check((("identity", "admin_required"),), request): raise exceptions.NotAuthorized endpoint_type = 'adminURL' else: endpoint_type = getattr(settings, 'OPENSTACK_ENDPOINT_TYPE', 'publicURL') # Take care of client connection caching/fetching a new client. # Admin vs. non-admin clients are cached separately for token matching. cache_attr = "_keystoneclient_admin" if admin \ else backend.KEYSTONE_CLIENT_ATTR if (hasattr(request, cache_attr) and (not user.token.id or getattr(request, cache_attr).auth_token == user.token.id)): conn = getattr(request, cache_attr) else: endpoint = _get_endpoint_url(request, endpoint_type) verify = not getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False) cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None) verify = verify and cacert LOG.debug("Creating a new keystoneclient connection to %s.", endpoint) remote_addr = request.environ.get('REMOTE_ADDR', '') token_auth = token_endpoint.Token(endpoint=endpoint, token=token_id) keystone_session = session.Session(auth=token_auth, original_ip=remote_addr, verify=verify) conn = client_version['client'].Client(session=keystone_session, debug=settings.DEBUG) setattr(request, cache_attr, conn) return conn
[ "def", "keystoneclient", "(", "request", ",", "admin", "=", "False", ")", ":", "client_version", "=", "VERSIONS", ".", "get_active_version", "(", ")", "user", "=", "request", ".", "user", "token_id", "=", "user", ".", "token", ".", "id", "if", "is_multi_do...
Returns a client connected to the Keystone backend. Several forms of authentication are supported: * Username + password -> Unscoped authentication * Username + password + tenant id -> Scoped authentication * Unscoped token -> Unscoped authentication * Unscoped token + tenant id -> Scoped authentication * Scoped token -> Scoped authentication Available services and data from the backend will vary depending on whether the authentication was scoped or unscoped. Lazy authentication if an ``endpoint`` parameter is provided. Calls requiring the admin endpoint should have ``admin=True`` passed in as a keyword argument. The client is cached so that subsequent API calls during the same request/response cycle don't have to be re-authenticated.
[ "Returns", "a", "client", "connected", "to", "the", "Keystone", "backend", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L141-L206
train
216,010
openstack/horizon
openstack_dashboard/api/keystone.py
get_default_domain
def get_default_domain(request, get_name=True): """Gets the default domain object to use when creating Identity object. Returns the domain context if is set, otherwise return the domain of the logon user. :param get_name: Whether to get the domain name from Keystone if the context isn't set. Setting this to False prevents an unnecessary call to Keystone if only the domain ID is needed. """ domain_id = request.session.get("domain_context", None) domain_name = request.session.get("domain_context_name", None) # if running in Keystone V3 or later if VERSIONS.active >= 3 and domain_id is None: # if no domain context set, default to user's domain domain_id = request.user.user_domain_id domain_name = request.user.user_domain_name if get_name and not request.user.is_federated: try: domain = domain_get(request, domain_id) domain_name = domain.name except exceptions.NotAuthorized: # NOTE (knasim-wrs): Retrieving domain information # is an admin URL operation. As a pre-check, such # operations would be Forbidden if the logon user does # not have an 'admin' role on the current project. # # Since this can be a common occurence and can cause # incessant warning logging in the horizon logs, # we recognize this condition and return the user's # domain information instead. LOG.debug("Cannot retrieve domain information for " "user (%(user)s) that does not have an admin role " "on project (%(project)s)", {'user': request.user.username, 'project': request.user.project_name}) except Exception: LOG.warning("Unable to retrieve Domain: %s", domain_id) domain = base.APIDictWrapper({"id": domain_id, "name": domain_name}) return domain
python
def get_default_domain(request, get_name=True): """Gets the default domain object to use when creating Identity object. Returns the domain context if is set, otherwise return the domain of the logon user. :param get_name: Whether to get the domain name from Keystone if the context isn't set. Setting this to False prevents an unnecessary call to Keystone if only the domain ID is needed. """ domain_id = request.session.get("domain_context", None) domain_name = request.session.get("domain_context_name", None) # if running in Keystone V3 or later if VERSIONS.active >= 3 and domain_id is None: # if no domain context set, default to user's domain domain_id = request.user.user_domain_id domain_name = request.user.user_domain_name if get_name and not request.user.is_federated: try: domain = domain_get(request, domain_id) domain_name = domain.name except exceptions.NotAuthorized: # NOTE (knasim-wrs): Retrieving domain information # is an admin URL operation. As a pre-check, such # operations would be Forbidden if the logon user does # not have an 'admin' role on the current project. # # Since this can be a common occurence and can cause # incessant warning logging in the horizon logs, # we recognize this condition and return the user's # domain information instead. LOG.debug("Cannot retrieve domain information for " "user (%(user)s) that does not have an admin role " "on project (%(project)s)", {'user': request.user.username, 'project': request.user.project_name}) except Exception: LOG.warning("Unable to retrieve Domain: %s", domain_id) domain = base.APIDictWrapper({"id": domain_id, "name": domain_name}) return domain
[ "def", "get_default_domain", "(", "request", ",", "get_name", "=", "True", ")", ":", "domain_id", "=", "request", ".", "session", ".", "get", "(", "\"domain_context\"", ",", "None", ")", "domain_name", "=", "request", ".", "session", ".", "get", "(", "\"do...
Gets the default domain object to use when creating Identity object. Returns the domain context if is set, otherwise return the domain of the logon user. :param get_name: Whether to get the domain name from Keystone if the context isn't set. Setting this to False prevents an unnecessary call to Keystone if only the domain ID is needed.
[ "Gets", "the", "default", "domain", "object", "to", "use", "when", "creating", "Identity", "object", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L284-L324
train
216,011
openstack/horizon
openstack_dashboard/api/keystone.py
get_effective_domain_id
def get_effective_domain_id(request): """Gets the id of the default domain. If the requests default domain is the same as DEFAULT_DOMAIN, return None. """ default_domain = get_default_domain(request) domain_id = default_domain.get('id') domain_name = default_domain.get('name') return None if domain_name == DEFAULT_DOMAIN else domain_id
python
def get_effective_domain_id(request): """Gets the id of the default domain. If the requests default domain is the same as DEFAULT_DOMAIN, return None. """ default_domain = get_default_domain(request) domain_id = default_domain.get('id') domain_name = default_domain.get('name') return None if domain_name == DEFAULT_DOMAIN else domain_id
[ "def", "get_effective_domain_id", "(", "request", ")", ":", "default_domain", "=", "get_default_domain", "(", "request", ")", "domain_id", "=", "default_domain", ".", "get", "(", "'id'", ")", "domain_name", "=", "default_domain", ".", "get", "(", "'name'", ")", ...
Gets the id of the default domain. If the requests default domain is the same as DEFAULT_DOMAIN, return None.
[ "Gets", "the", "id", "of", "the", "default", "domain", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L327-L336
train
216,012
openstack/horizon
openstack_dashboard/api/keystone.py
get_project_groups_roles
def get_project_groups_roles(request, project): """Gets the groups roles in a given project. :param request: the request entity containing the login user information :param project: the project to filter the groups roles. It accepts both project object resource or project ID :returns group_roles: a dictionary mapping the groups and their roles in given project """ groups_roles = collections.defaultdict(list) project_role_assignments = role_assignments_list(request, project=project) for role_assignment in project_role_assignments: if not hasattr(role_assignment, 'group'): continue group_id = role_assignment.group['id'] role_id = role_assignment.role['id'] # filter by project_id if ('project' in role_assignment.scope and role_assignment.scope['project']['id'] == project): groups_roles[group_id].append(role_id) return groups_roles
python
def get_project_groups_roles(request, project): """Gets the groups roles in a given project. :param request: the request entity containing the login user information :param project: the project to filter the groups roles. It accepts both project object resource or project ID :returns group_roles: a dictionary mapping the groups and their roles in given project """ groups_roles = collections.defaultdict(list) project_role_assignments = role_assignments_list(request, project=project) for role_assignment in project_role_assignments: if not hasattr(role_assignment, 'group'): continue group_id = role_assignment.group['id'] role_id = role_assignment.role['id'] # filter by project_id if ('project' in role_assignment.scope and role_assignment.scope['project']['id'] == project): groups_roles[group_id].append(role_id) return groups_roles
[ "def", "get_project_groups_roles", "(", "request", ",", "project", ")", ":", "groups_roles", "=", "collections", ".", "defaultdict", "(", "list", ")", "project_role_assignments", "=", "role_assignments_list", "(", "request", ",", "project", "=", "project", ")", "f...
Gets the groups roles in a given project. :param request: the request entity containing the login user information :param project: the project to filter the groups roles. It accepts both project object resource or project ID :returns group_roles: a dictionary mapping the groups and their roles in given project
[ "Gets", "the", "groups", "roles", "in", "a", "given", "project", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L671-L696
train
216,013
openstack/horizon
openstack_dashboard/api/keystone.py
role_list
def role_list(request, filters=None): """Returns a global list of available roles.""" manager = keystoneclient(request, admin=True).roles roles = [] kwargs = {} if filters is not None: kwargs.update(filters) if 'id' in kwargs: try: roles = [manager.get(kwargs['id'])] except keystone_exceptions.NotFound: roles = [] except Exception: exceptions.handle(request) else: roles = manager.list(**kwargs) return roles
python
def role_list(request, filters=None): """Returns a global list of available roles.""" manager = keystoneclient(request, admin=True).roles roles = [] kwargs = {} if filters is not None: kwargs.update(filters) if 'id' in kwargs: try: roles = [manager.get(kwargs['id'])] except keystone_exceptions.NotFound: roles = [] except Exception: exceptions.handle(request) else: roles = manager.list(**kwargs) return roles
[ "def", "role_list", "(", "request", ",", "filters", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", ".", "roles", "roles", "=", "[", "]", "kwargs", "=", "{", "}", "if", "filters", "is", "not", ...
Returns a global list of available roles.
[ "Returns", "a", "global", "list", "of", "available", "roles", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L742-L758
train
216,014
openstack/horizon
openstack_dashboard/api/keystone.py
roles_for_user
def roles_for_user(request, user, project=None, domain=None): """Returns a list of user roles scoped to a project or domain.""" manager = keystoneclient(request, admin=True).roles if VERSIONS.active < 3: return manager.roles_for_user(user, project) else: return manager.list(user=user, domain=domain, project=project)
python
def roles_for_user(request, user, project=None, domain=None): """Returns a list of user roles scoped to a project or domain.""" manager = keystoneclient(request, admin=True).roles if VERSIONS.active < 3: return manager.roles_for_user(user, project) else: return manager.list(user=user, domain=domain, project=project)
[ "def", "roles_for_user", "(", "request", ",", "user", ",", "project", "=", "None", ",", "domain", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", ".", "roles", "if", "VERSIONS", ".", "active", "<...
Returns a list of user roles scoped to a project or domain.
[ "Returns", "a", "list", "of", "user", "roles", "scoped", "to", "a", "project", "or", "domain", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L762-L768
train
216,015
openstack/horizon
openstack_dashboard/api/keystone.py
add_domain_user_role
def add_domain_user_role(request, user, role, domain): """Adds a role for a user on a domain.""" manager = keystoneclient(request, admin=True).roles return manager.grant(role, user=user, domain=domain)
python
def add_domain_user_role(request, user, role, domain): """Adds a role for a user on a domain.""" manager = keystoneclient(request, admin=True).roles return manager.grant(role, user=user, domain=domain)
[ "def", "add_domain_user_role", "(", "request", ",", "user", ",", "role", ",", "domain", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", ".", "roles", "return", "manager", ".", "grant", "(", "role", ",", "user",...
Adds a role for a user on a domain.
[ "Adds", "a", "role", "for", "a", "user", "on", "a", "domain", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L791-L794
train
216,016
openstack/horizon
openstack_dashboard/api/keystone.py
remove_domain_user_role
def remove_domain_user_role(request, user, role, domain=None): """Removes a given single role for a user from a domain.""" manager = keystoneclient(request, admin=True).roles return manager.revoke(role, user=user, domain=domain)
python
def remove_domain_user_role(request, user, role, domain=None): """Removes a given single role for a user from a domain.""" manager = keystoneclient(request, admin=True).roles return manager.revoke(role, user=user, domain=domain)
[ "def", "remove_domain_user_role", "(", "request", ",", "user", ",", "role", ",", "domain", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", ".", "roles", "return", "manager", ".", "revoke", "(", "ro...
Removes a given single role for a user from a domain.
[ "Removes", "a", "given", "single", "role", "for", "a", "user", "from", "a", "domain", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L798-L801
train
216,017
openstack/horizon
openstack_dashboard/api/keystone.py
add_tenant_user_role
def add_tenant_user_role(request, project=None, user=None, role=None, group=None, domain=None): """Adds a role for a user on a tenant.""" manager = keystoneclient(request, admin=True).roles if VERSIONS.active < 3: manager.add_user_role(user, role, project) else: manager.grant(role, user=user, project=project, group=group, domain=domain)
python
def add_tenant_user_role(request, project=None, user=None, role=None, group=None, domain=None): """Adds a role for a user on a tenant.""" manager = keystoneclient(request, admin=True).roles if VERSIONS.active < 3: manager.add_user_role(user, role, project) else: manager.grant(role, user=user, project=project, group=group, domain=domain)
[ "def", "add_tenant_user_role", "(", "request", ",", "project", "=", "None", ",", "user", "=", "None", ",", "role", "=", "None", ",", "group", "=", "None", ",", "domain", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "adm...
Adds a role for a user on a tenant.
[ "Adds", "a", "role", "for", "a", "user", "on", "a", "tenant", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L831-L839
train
216,018
openstack/horizon
openstack_dashboard/api/keystone.py
remove_tenant_user_role
def remove_tenant_user_role(request, project=None, user=None, role=None, group=None, domain=None): """Removes a given single role for a user from a tenant.""" manager = keystoneclient(request, admin=True).roles if VERSIONS.active < 3: return manager.remove_user_role(user, role, project) else: return manager.revoke(role, user=user, project=project, group=group, domain=domain)
python
def remove_tenant_user_role(request, project=None, user=None, role=None, group=None, domain=None): """Removes a given single role for a user from a tenant.""" manager = keystoneclient(request, admin=True).roles if VERSIONS.active < 3: return manager.remove_user_role(user, role, project) else: return manager.revoke(role, user=user, project=project, group=group, domain=domain)
[ "def", "remove_tenant_user_role", "(", "request", ",", "project", "=", "None", ",", "user", "=", "None", ",", "role", "=", "None", ",", "group", "=", "None", ",", "domain", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "...
Removes a given single role for a user from a tenant.
[ "Removes", "a", "given", "single", "role", "for", "a", "user", "from", "a", "tenant", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L843-L851
train
216,019
openstack/horizon
openstack_dashboard/api/keystone.py
remove_tenant_user
def remove_tenant_user(request, project=None, user=None, domain=None): """Removes all roles from a user on a tenant, removing them from it.""" client = keystoneclient(request, admin=True) roles = client.roles.roles_for_user(user, project) for role in roles: remove_tenant_user_role(request, user=user, role=role.id, project=project, domain=domain)
python
def remove_tenant_user(request, project=None, user=None, domain=None): """Removes all roles from a user on a tenant, removing them from it.""" client = keystoneclient(request, admin=True) roles = client.roles.roles_for_user(user, project) for role in roles: remove_tenant_user_role(request, user=user, role=role.id, project=project, domain=domain)
[ "def", "remove_tenant_user", "(", "request", ",", "project", "=", "None", ",", "user", "=", "None", ",", "domain", "=", "None", ")", ":", "client", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", "roles", "=", "client", ".", "rol...
Removes all roles from a user on a tenant, removing them from it.
[ "Removes", "all", "roles", "from", "a", "user", "on", "a", "tenant", "removing", "them", "from", "it", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L854-L860
train
216,020
openstack/horizon
openstack_dashboard/api/keystone.py
add_group_role
def add_group_role(request, role, group, domain=None, project=None): """Adds a role for a group on a domain or project.""" manager = keystoneclient(request, admin=True).roles return manager.grant(role=role, group=group, domain=domain, project=project)
python
def add_group_role(request, role, group, domain=None, project=None): """Adds a role for a group on a domain or project.""" manager = keystoneclient(request, admin=True).roles return manager.grant(role=role, group=group, domain=domain, project=project)
[ "def", "add_group_role", "(", "request", ",", "role", ",", "group", ",", "domain", "=", "None", ",", "project", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", ".", "roles", "return", "manager", ...
Adds a role for a group on a domain or project.
[ "Adds", "a", "role", "for", "a", "group", "on", "a", "domain", "or", "project", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L870-L874
train
216,021
openstack/horizon
openstack_dashboard/api/keystone.py
remove_group_role
def remove_group_role(request, role, group, domain=None, project=None): """Removes a given single role for a group from a domain or project.""" manager = keystoneclient(request, admin=True).roles return manager.revoke(role=role, group=group, project=project, domain=domain)
python
def remove_group_role(request, role, group, domain=None, project=None): """Removes a given single role for a group from a domain or project.""" manager = keystoneclient(request, admin=True).roles return manager.revoke(role=role, group=group, project=project, domain=domain)
[ "def", "remove_group_role", "(", "request", ",", "role", ",", "group", ",", "domain", "=", "None", ",", "project", "=", "None", ")", ":", "manager", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", ".", "roles", "return", "manager",...
Removes a given single role for a group from a domain or project.
[ "Removes", "a", "given", "single", "role", "for", "a", "group", "from", "a", "domain", "or", "project", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L878-L882
train
216,022
openstack/horizon
openstack_dashboard/api/keystone.py
remove_group_roles
def remove_group_roles(request, group, domain=None, project=None): """Removes all roles from a group on a domain or project.""" client = keystoneclient(request, admin=True) roles = client.roles.list(group=group, domain=domain, project=project) for role in roles: remove_group_role(request, role=role.id, group=group, domain=domain, project=project)
python
def remove_group_roles(request, group, domain=None, project=None): """Removes all roles from a group on a domain or project.""" client = keystoneclient(request, admin=True) roles = client.roles.list(group=group, domain=domain, project=project) for role in roles: remove_group_role(request, role=role.id, group=group, domain=domain, project=project)
[ "def", "remove_group_roles", "(", "request", ",", "group", ",", "domain", "=", "None", ",", "project", "=", "None", ")", ":", "client", "=", "keystoneclient", "(", "request", ",", "admin", "=", "True", ")", "roles", "=", "client", ".", "roles", ".", "l...
Removes all roles from a group on a domain or project.
[ "Removes", "all", "roles", "from", "a", "group", "on", "a", "domain", "or", "project", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L886-L892
train
216,023
openstack/horizon
openstack_dashboard/api/keystone.py
get_default_role
def get_default_role(request): """Gets the default role object from Keystone and saves it as a global. Since this is configured in settings and should not change from request to request. Supports lookup by name or id. """ global DEFAULT_ROLE default = getattr(settings, "OPENSTACK_KEYSTONE_DEFAULT_ROLE", None) if default and DEFAULT_ROLE is None: try: roles = keystoneclient(request, admin=True).roles.list() except Exception: roles = [] exceptions.handle(request) for role in roles: if default in (role.id, role.name): DEFAULT_ROLE = role break return DEFAULT_ROLE
python
def get_default_role(request): """Gets the default role object from Keystone and saves it as a global. Since this is configured in settings and should not change from request to request. Supports lookup by name or id. """ global DEFAULT_ROLE default = getattr(settings, "OPENSTACK_KEYSTONE_DEFAULT_ROLE", None) if default and DEFAULT_ROLE is None: try: roles = keystoneclient(request, admin=True).roles.list() except Exception: roles = [] exceptions.handle(request) for role in roles: if default in (role.id, role.name): DEFAULT_ROLE = role break return DEFAULT_ROLE
[ "def", "get_default_role", "(", "request", ")", ":", "global", "DEFAULT_ROLE", "default", "=", "getattr", "(", "settings", ",", "\"OPENSTACK_KEYSTONE_DEFAULT_ROLE\"", ",", "None", ")", "if", "default", "and", "DEFAULT_ROLE", "is", "None", ":", "try", ":", "roles...
Gets the default role object from Keystone and saves it as a global. Since this is configured in settings and should not change from request to request. Supports lookup by name or id.
[ "Gets", "the", "default", "role", "object", "from", "Keystone", "and", "saves", "it", "as", "a", "global", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L895-L913
train
216,024
openstack/horizon
horizon/browsers/breadcrumb.py
Breadcrumb.render
def render(self): """Renders the table using the template from the table options.""" breadcrumb_template = template.loader.get_template(self.template) extra_context = {"breadcrumb": self} return breadcrumb_template.render(extra_context, self.request)
python
def render(self): """Renders the table using the template from the table options.""" breadcrumb_template = template.loader.get_template(self.template) extra_context = {"breadcrumb": self} return breadcrumb_template.render(extra_context, self.request)
[ "def", "render", "(", "self", ")", ":", "breadcrumb_template", "=", "template", ".", "loader", ".", "get_template", "(", "self", ".", "template", ")", "extra_context", "=", "{", "\"breadcrumb\"", ":", "self", "}", "return", "breadcrumb_template", ".", "render"...
Renders the table using the template from the table options.
[ "Renders", "the", "table", "using", "the", "template", "from", "the", "table", "options", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/browsers/breadcrumb.py#L41-L45
train
216,025
openstack/horizon
horizon/tabs/base.py
TabGroup.load_tab_data
def load_tab_data(self): """Preload all data that for the tabs that will be displayed.""" for tab in self._tabs.values(): if tab.load and not tab.data_loaded: try: tab._data = tab.get_context_data(self.request) except Exception: tab._data = False exceptions.handle(self.request)
python
def load_tab_data(self): """Preload all data that for the tabs that will be displayed.""" for tab in self._tabs.values(): if tab.load and not tab.data_loaded: try: tab._data = tab.get_context_data(self.request) except Exception: tab._data = False exceptions.handle(self.request)
[ "def", "load_tab_data", "(", "self", ")", ":", "for", "tab", "in", "self", ".", "_tabs", ".", "values", "(", ")", ":", "if", "tab", ".", "load", "and", "not", "tab", ".", "data_loaded", ":", "try", ":", "tab", ".", "_data", "=", "tab", ".", "get_...
Preload all data that for the tabs that will be displayed.
[ "Preload", "all", "data", "that", "for", "the", "tabs", "that", "will", "be", "displayed", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L170-L178
train
216,026
openstack/horizon
horizon/tabs/base.py
TabGroup.get_default_classes
def get_default_classes(self): """Returns a list of the default classes for the tab group. Defaults to ``["nav", "nav-tabs", "ajax-tabs"]``. """ default_classes = super(TabGroup, self).get_default_classes() default_classes.extend(CSS_TAB_GROUP_CLASSES) return default_classes
python
def get_default_classes(self): """Returns a list of the default classes for the tab group. Defaults to ``["nav", "nav-tabs", "ajax-tabs"]``. """ default_classes = super(TabGroup, self).get_default_classes() default_classes.extend(CSS_TAB_GROUP_CLASSES) return default_classes
[ "def", "get_default_classes", "(", "self", ")", ":", "default_classes", "=", "super", "(", "TabGroup", ",", "self", ")", ".", "get_default_classes", "(", ")", "default_classes", ".", "extend", "(", "CSS_TAB_GROUP_CLASSES", ")", "return", "default_classes" ]
Returns a list of the default classes for the tab group. Defaults to ``["nav", "nav-tabs", "ajax-tabs"]``.
[ "Returns", "a", "list", "of", "the", "default", "classes", "for", "the", "tab", "group", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L188-L195
train
216,027
openstack/horizon
horizon/tabs/base.py
TabGroup.get_tab
def get_tab(self, tab_name, allow_disabled=False): """Returns a specific tab from this tab group. If the tab is not allowed or not enabled this method returns ``None``. If the tab is disabled but you wish to return it anyway, you can pass ``True`` to the allow_disabled argument. """ tab = self._tabs.get(tab_name, None) if tab and tab._allowed and (tab._enabled or allow_disabled): return tab return None
python
def get_tab(self, tab_name, allow_disabled=False): """Returns a specific tab from this tab group. If the tab is not allowed or not enabled this method returns ``None``. If the tab is disabled but you wish to return it anyway, you can pass ``True`` to the allow_disabled argument. """ tab = self._tabs.get(tab_name, None) if tab and tab._allowed and (tab._enabled or allow_disabled): return tab return None
[ "def", "get_tab", "(", "self", ",", "tab_name", ",", "allow_disabled", "=", "False", ")", ":", "tab", "=", "self", ".", "_tabs", ".", "get", "(", "tab_name", ",", "None", ")", "if", "tab", "and", "tab", ".", "_allowed", "and", "(", "tab", ".", "_en...
Returns a specific tab from this tab group. If the tab is not allowed or not enabled this method returns ``None``. If the tab is disabled but you wish to return it anyway, you can pass ``True`` to the allow_disabled argument.
[ "Returns", "a", "specific", "tab", "from", "this", "tab", "group", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L236-L247
train
216,028
openstack/horizon
horizon/tabs/base.py
TabGroup.get_selected_tab
def get_selected_tab(self): """Returns the tab specific by the GET request parameter. In the event that there is no GET request parameter, the value of the query parameter is invalid, or the tab is not allowed/enabled, the return value of this function is None. """ selected = self.request.GET.get(self.param_name, None) if selected: try: tab_group, tab_name = selected.split(SEPARATOR) except ValueError: return None if tab_group == self.get_id(): self._selected = self.get_tab(tab_name) return self._selected
python
def get_selected_tab(self): """Returns the tab specific by the GET request parameter. In the event that there is no GET request parameter, the value of the query parameter is invalid, or the tab is not allowed/enabled, the return value of this function is None. """ selected = self.request.GET.get(self.param_name, None) if selected: try: tab_group, tab_name = selected.split(SEPARATOR) except ValueError: return None if tab_group == self.get_id(): self._selected = self.get_tab(tab_name) return self._selected
[ "def", "get_selected_tab", "(", "self", ")", ":", "selected", "=", "self", ".", "request", ".", "GET", ".", "get", "(", "self", ".", "param_name", ",", "None", ")", "if", "selected", ":", "try", ":", "tab_group", ",", "tab_name", "=", "selected", ".", ...
Returns the tab specific by the GET request parameter. In the event that there is no GET request parameter, the value of the query parameter is invalid, or the tab is not allowed/enabled, the return value of this function is None.
[ "Returns", "the", "tab", "specific", "by", "the", "GET", "request", "parameter", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L252-L267
train
216,029
openstack/horizon
horizon/tabs/base.py
Tab.render
def render(self): """Renders the tab to HTML. :meth:`~horizon.tabs.Tab.get_context_data` method and the :meth:`~horizon.tabs.Tab.get_template_name` method are called. If :attr:`~horizon.tabs.Tab.preload` is ``False`` and ``force_load`` is not ``True``, or either :meth:`~horizon.tabs.Tab.allowed` or :meth:`~horizon.tabs.Tab.enabled` returns ``False`` this method will return an empty string. """ if not self.load: return '' try: context = self.data except exceptions.Http302: raise except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() raise six.reraise(TemplateSyntaxError, exc_value, exc_traceback) return render_to_string(self.get_template_name(self.request), context)
python
def render(self): """Renders the tab to HTML. :meth:`~horizon.tabs.Tab.get_context_data` method and the :meth:`~horizon.tabs.Tab.get_template_name` method are called. If :attr:`~horizon.tabs.Tab.preload` is ``False`` and ``force_load`` is not ``True``, or either :meth:`~horizon.tabs.Tab.allowed` or :meth:`~horizon.tabs.Tab.enabled` returns ``False`` this method will return an empty string. """ if not self.load: return '' try: context = self.data except exceptions.Http302: raise except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() raise six.reraise(TemplateSyntaxError, exc_value, exc_traceback) return render_to_string(self.get_template_name(self.request), context)
[ "def", "render", "(", "self", ")", ":", "if", "not", "self", ".", "load", ":", "return", "''", "try", ":", "context", "=", "self", ".", "data", "except", "exceptions", ".", "Http302", ":", "raise", "except", "Exception", ":", "exc_type", ",", "exc_valu...
Renders the tab to HTML. :meth:`~horizon.tabs.Tab.get_context_data` method and the :meth:`~horizon.tabs.Tab.get_template_name` method are called. If :attr:`~horizon.tabs.Tab.preload` is ``False`` and ``force_load`` is not ``True``, or either :meth:`~horizon.tabs.Tab.allowed` or :meth:`~horizon.tabs.Tab.enabled` returns ``False`` this method will return an empty string.
[ "Renders", "the", "tab", "to", "HTML", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L356-L377
train
216,030
openstack/horizon
horizon/tabs/base.py
Tab.get_default_classes
def get_default_classes(self): """Returns a list of the default classes for the tab. Defaults to and empty list (``[]``), however additional classes may be added depending on the state of the tab as follows: If the tab is the active tab for the tab group, in which the class ``"active"`` will be added. If the tab is not enabled, the classes the class ``"disabled"`` will be added. """ default_classes = super(Tab, self).get_default_classes() if self.is_active(): default_classes.extend(CSS_ACTIVE_TAB_CLASSES) if not self._enabled: default_classes.extend(CSS_DISABLED_TAB_CLASSES) return default_classes
python
def get_default_classes(self): """Returns a list of the default classes for the tab. Defaults to and empty list (``[]``), however additional classes may be added depending on the state of the tab as follows: If the tab is the active tab for the tab group, in which the class ``"active"`` will be added. If the tab is not enabled, the classes the class ``"disabled"`` will be added. """ default_classes = super(Tab, self).get_default_classes() if self.is_active(): default_classes.extend(CSS_ACTIVE_TAB_CLASSES) if not self._enabled: default_classes.extend(CSS_DISABLED_TAB_CLASSES) return default_classes
[ "def", "get_default_classes", "(", "self", ")", ":", "default_classes", "=", "super", "(", "Tab", ",", "self", ")", ".", "get_default_classes", "(", ")", "if", "self", ".", "is_active", "(", ")", ":", "default_classes", ".", "extend", "(", "CSS_ACTIVE_TAB_CL...
Returns a list of the default classes for the tab. Defaults to and empty list (``[]``), however additional classes may be added depending on the state of the tab as follows: If the tab is the active tab for the tab group, in which the class ``"active"`` will be added. If the tab is not enabled, the classes the class ``"disabled"`` will be added.
[ "Returns", "a", "list", "of", "the", "default", "classes", "for", "the", "tab", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L389-L406
train
216,031
openstack/horizon
horizon/tabs/base.py
Tab.get_template_name
def get_template_name(self, request): """Returns the name of the template to be used for rendering this tab. By default it returns the value of the ``template_name`` attribute on the ``Tab`` class. """ if not hasattr(self, "template_name"): raise AttributeError("%s must have a template_name attribute or " "override the get_template_name method." % self.__class__.__name__) return self.template_name
python
def get_template_name(self, request): """Returns the name of the template to be used for rendering this tab. By default it returns the value of the ``template_name`` attribute on the ``Tab`` class. """ if not hasattr(self, "template_name"): raise AttributeError("%s must have a template_name attribute or " "override the get_template_name method." % self.__class__.__name__) return self.template_name
[ "def", "get_template_name", "(", "self", ",", "request", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"template_name\"", ")", ":", "raise", "AttributeError", "(", "\"%s must have a template_name attribute or \"", "\"override the get_template_name method.\"", "%",...
Returns the name of the template to be used for rendering this tab. By default it returns the value of the ``template_name`` attribute on the ``Tab`` class.
[ "Returns", "the", "name", "of", "the", "template", "to", "be", "used", "for", "rendering", "this", "tab", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L408-L418
train
216,032
openstack/horizon
horizon/templatetags/breadcrumb_nav.py
breadcrumb_nav
def breadcrumb_nav(context): """A logic heavy function for automagically creating a breadcrumb. It uses the dashboard, panel group(if it exists), then current panel. Can also use a "custom_breadcrumb" context item to add extra items. """ breadcrumb = [] dashboard = context.request.horizon['dashboard'] try: panel_groups = dashboard.get_panel_groups() except KeyError: panel_groups = None panel_group = None panel = context.request.horizon['panel'] # Add panel group, if there is one if panel_groups: for group in panel_groups.values(): if panel.slug in group.panels and group.slug != 'default': panel_group = group break # Remove panel reference if that is the current page if panel.get_absolute_url() == context.request.path: panel = None # Get custom breadcrumb, if there is one. custom_breadcrumb = context.get('custom_breadcrumb') # Build list of tuples (name, optional url) breadcrumb.append((dashboard.name, None)) if panel_group: breadcrumb.append((panel_group.name, None)) if panel: breadcrumb.append((panel.name, panel.get_absolute_url())) if custom_breadcrumb: breadcrumb.extend(custom_breadcrumb) breadcrumb.append((context.get('page_title'), None)) return {'breadcrumb': breadcrumb}
python
def breadcrumb_nav(context): """A logic heavy function for automagically creating a breadcrumb. It uses the dashboard, panel group(if it exists), then current panel. Can also use a "custom_breadcrumb" context item to add extra items. """ breadcrumb = [] dashboard = context.request.horizon['dashboard'] try: panel_groups = dashboard.get_panel_groups() except KeyError: panel_groups = None panel_group = None panel = context.request.horizon['panel'] # Add panel group, if there is one if panel_groups: for group in panel_groups.values(): if panel.slug in group.panels and group.slug != 'default': panel_group = group break # Remove panel reference if that is the current page if panel.get_absolute_url() == context.request.path: panel = None # Get custom breadcrumb, if there is one. custom_breadcrumb = context.get('custom_breadcrumb') # Build list of tuples (name, optional url) breadcrumb.append((dashboard.name, None)) if panel_group: breadcrumb.append((panel_group.name, None)) if panel: breadcrumb.append((panel.name, panel.get_absolute_url())) if custom_breadcrumb: breadcrumb.extend(custom_breadcrumb) breadcrumb.append((context.get('page_title'), None)) return {'breadcrumb': breadcrumb}
[ "def", "breadcrumb_nav", "(", "context", ")", ":", "breadcrumb", "=", "[", "]", "dashboard", "=", "context", ".", "request", ".", "horizon", "[", "'dashboard'", "]", "try", ":", "panel_groups", "=", "dashboard", ".", "get_panel_groups", "(", ")", "except", ...
A logic heavy function for automagically creating a breadcrumb. It uses the dashboard, panel group(if it exists), then current panel. Can also use a "custom_breadcrumb" context item to add extra items.
[ "A", "logic", "heavy", "function", "for", "automagically", "creating", "a", "breadcrumb", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/breadcrumb_nav.py#L22-L61
train
216,033
openstack/horizon
horizon/utils/html.py
HTMLElement.get_final_attrs
def get_final_attrs(self, classes=True): """Returns a dict containing the final attributes to be rendered.""" final_attrs = copy.copy(self.get_default_attrs()) final_attrs.update(self.attrs) if classes: final_attrs['class'] = self.get_final_css() else: final_attrs.pop('class', None) return final_attrs
python
def get_final_attrs(self, classes=True): """Returns a dict containing the final attributes to be rendered.""" final_attrs = copy.copy(self.get_default_attrs()) final_attrs.update(self.attrs) if classes: final_attrs['class'] = self.get_final_css() else: final_attrs.pop('class', None) return final_attrs
[ "def", "get_final_attrs", "(", "self", ",", "classes", "=", "True", ")", ":", "final_attrs", "=", "copy", ".", "copy", "(", "self", ".", "get_default_attrs", "(", ")", ")", "final_attrs", ".", "update", "(", "self", ".", "attrs", ")", "if", "classes", ...
Returns a dict containing the final attributes to be rendered.
[ "Returns", "a", "dict", "containing", "the", "final", "attributes", "to", "be", "rendered", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/html.py#L38-L47
train
216,034
openstack/horizon
horizon/utils/html.py
HTMLElement.get_final_css
def get_final_css(self): """Returns a final css class concatenated string.""" default = " ".join(self.get_default_classes()) defined = self.attrs.get('class', '') additional = " ".join(getattr(self, "classes", [])) non_empty = [test for test in (defined, default, additional) if test] final_classes = " ".join(non_empty).strip() return final_classes
python
def get_final_css(self): """Returns a final css class concatenated string.""" default = " ".join(self.get_default_classes()) defined = self.attrs.get('class', '') additional = " ".join(getattr(self, "classes", [])) non_empty = [test for test in (defined, default, additional) if test] final_classes = " ".join(non_empty).strip() return final_classes
[ "def", "get_final_css", "(", "self", ")", ":", "default", "=", "\" \"", ".", "join", "(", "self", ".", "get_default_classes", "(", ")", ")", "defined", "=", "self", ".", "attrs", ".", "get", "(", "'class'", ",", "''", ")", "additional", "=", "\" \"", ...
Returns a final css class concatenated string.
[ "Returns", "a", "final", "css", "class", "concatenated", "string", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/html.py#L49-L56
train
216,035
openstack/horizon
openstack_dashboard/dashboards/project/instances/utils.py
flavor_list
def flavor_list(request): """Utility method to retrieve a list of flavors.""" try: return api.nova.flavor_list(request) except Exception: exceptions.handle(request, _('Unable to retrieve instance flavors.')) return []
python
def flavor_list(request): """Utility method to retrieve a list of flavors.""" try: return api.nova.flavor_list(request) except Exception: exceptions.handle(request, _('Unable to retrieve instance flavors.')) return []
[ "def", "flavor_list", "(", "request", ")", ":", "try", ":", "return", "api", ".", "nova", ".", "flavor_list", "(", "request", ")", "except", "Exception", ":", "exceptions", ".", "handle", "(", "request", ",", "_", "(", "'Unable to retrieve instance flavors.'",...
Utility method to retrieve a list of flavors.
[ "Utility", "method", "to", "retrieve", "a", "list", "of", "flavors", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L27-L34
train
216,036
openstack/horizon
openstack_dashboard/dashboards/project/instances/utils.py
sort_flavor_list
def sort_flavor_list(request, flavors, with_menu_label=True): """Utility method to sort a list of flavors. By default, returns the available flavors, sorted by RAM usage (ascending). Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict in ``local_settings.py``. """ def get_key(flavor, sort_key): try: return getattr(flavor, sort_key) except AttributeError: LOG.warning('Could not find sort key "%s". Using the default ' '"ram" instead.', sort_key) return getattr(flavor, 'ram') try: flavor_sort = getattr(settings, 'CREATE_INSTANCE_FLAVOR_SORT', {}) sort_key = flavor_sort.get('key', 'ram') rev = flavor_sort.get('reverse', False) if not callable(sort_key): def key(flavor): return get_key(flavor, sort_key) else: key = sort_key if with_menu_label: flavor_list = [(flavor.id, '%s' % flavor.name) for flavor in sorted(flavors, key=key, reverse=rev)] else: flavor_list = sorted(flavors, key=key, reverse=rev) return flavor_list except Exception: exceptions.handle(request, _('Unable to sort instance flavors.')) return []
python
def sort_flavor_list(request, flavors, with_menu_label=True): """Utility method to sort a list of flavors. By default, returns the available flavors, sorted by RAM usage (ascending). Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict in ``local_settings.py``. """ def get_key(flavor, sort_key): try: return getattr(flavor, sort_key) except AttributeError: LOG.warning('Could not find sort key "%s". Using the default ' '"ram" instead.', sort_key) return getattr(flavor, 'ram') try: flavor_sort = getattr(settings, 'CREATE_INSTANCE_FLAVOR_SORT', {}) sort_key = flavor_sort.get('key', 'ram') rev = flavor_sort.get('reverse', False) if not callable(sort_key): def key(flavor): return get_key(flavor, sort_key) else: key = sort_key if with_menu_label: flavor_list = [(flavor.id, '%s' % flavor.name) for flavor in sorted(flavors, key=key, reverse=rev)] else: flavor_list = sorted(flavors, key=key, reverse=rev) return flavor_list except Exception: exceptions.handle(request, _('Unable to sort instance flavors.')) return []
[ "def", "sort_flavor_list", "(", "request", ",", "flavors", ",", "with_menu_label", "=", "True", ")", ":", "def", "get_key", "(", "flavor", ",", "sort_key", ")", ":", "try", ":", "return", "getattr", "(", "flavor", ",", "sort_key", ")", "except", "Attribute...
Utility method to sort a list of flavors. By default, returns the available flavors, sorted by RAM usage (ascending). Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict in ``local_settings.py``.
[ "Utility", "method", "to", "sort", "a", "list", "of", "flavors", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L37-L70
train
216,037
openstack/horizon
openstack_dashboard/dashboards/project/instances/utils.py
server_group_list
def server_group_list(request): """Utility method to retrieve a list of server groups.""" try: return api.nova.server_group_list(request) except Exception: exceptions.handle(request, _('Unable to retrieve Nova server groups.')) return []
python
def server_group_list(request): """Utility method to retrieve a list of server groups.""" try: return api.nova.server_group_list(request) except Exception: exceptions.handle(request, _('Unable to retrieve Nova server groups.')) return []
[ "def", "server_group_list", "(", "request", ")", ":", "try", ":", "return", "api", ".", "nova", ".", "server_group_list", "(", "request", ")", "except", "Exception", ":", "exceptions", ".", "handle", "(", "request", ",", "_", "(", "'Unable to retrieve Nova ser...
Utility method to retrieve a list of server groups.
[ "Utility", "method", "to", "retrieve", "a", "list", "of", "server", "groups", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L83-L90
train
216,038
openstack/horizon
openstack_dashboard/dashboards/project/instances/utils.py
network_field_data
def network_field_data(request, include_empty_option=False, with_cidr=False, for_launch=False): """Returns a list of tuples of all networks. Generates a list of networks available to the user (request). And returns a list of (id, name) tuples. :param request: django http request object :param include_empty_option: flag to include a empty tuple in the front of the list :param with_cidr: flag to include subnets cidr in field name :return: list of (id, name) tuples """ tenant_id = request.user.tenant_id networks = [] if api.base.is_service_enabled(request, 'network'): extra_params = {} if for_launch: extra_params['include_pre_auto_allocate'] = True try: networks = api.neutron.network_list_for_tenant( request, tenant_id, **extra_params) except Exception as e: msg = _('Failed to get network list {0}').format(six.text_type(e)) exceptions.handle(request, msg) _networks = [] for n in networks: if not n['subnets']: continue v = n.name_or_id if with_cidr: cidrs = ([subnet.cidr for subnet in n['subnets'] if subnet.ip_version == 4] + [subnet.cidr for subnet in n['subnets'] if subnet.ip_version == 6]) v += ' (%s)' % ', '.join(cidrs) _networks.append((n.id, v)) networks = sorted(_networks, key=itemgetter(1)) if not networks: if include_empty_option: return [("", _("No networks available")), ] return [] if include_empty_option: return [("", _("Select Network")), ] + networks return networks
python
def network_field_data(request, include_empty_option=False, with_cidr=False, for_launch=False): """Returns a list of tuples of all networks. Generates a list of networks available to the user (request). And returns a list of (id, name) tuples. :param request: django http request object :param include_empty_option: flag to include a empty tuple in the front of the list :param with_cidr: flag to include subnets cidr in field name :return: list of (id, name) tuples """ tenant_id = request.user.tenant_id networks = [] if api.base.is_service_enabled(request, 'network'): extra_params = {} if for_launch: extra_params['include_pre_auto_allocate'] = True try: networks = api.neutron.network_list_for_tenant( request, tenant_id, **extra_params) except Exception as e: msg = _('Failed to get network list {0}').format(six.text_type(e)) exceptions.handle(request, msg) _networks = [] for n in networks: if not n['subnets']: continue v = n.name_or_id if with_cidr: cidrs = ([subnet.cidr for subnet in n['subnets'] if subnet.ip_version == 4] + [subnet.cidr for subnet in n['subnets'] if subnet.ip_version == 6]) v += ' (%s)' % ', '.join(cidrs) _networks.append((n.id, v)) networks = sorted(_networks, key=itemgetter(1)) if not networks: if include_empty_option: return [("", _("No networks available")), ] return [] if include_empty_option: return [("", _("Select Network")), ] + networks return networks
[ "def", "network_field_data", "(", "request", ",", "include_empty_option", "=", "False", ",", "with_cidr", "=", "False", ",", "for_launch", "=", "False", ")", ":", "tenant_id", "=", "request", ".", "user", ".", "tenant_id", "networks", "=", "[", "]", "if", ...
Returns a list of tuples of all networks. Generates a list of networks available to the user (request). And returns a list of (id, name) tuples. :param request: django http request object :param include_empty_option: flag to include a empty tuple in the front of the list :param with_cidr: flag to include subnets cidr in field name :return: list of (id, name) tuples
[ "Returns", "a", "list", "of", "tuples", "of", "all", "networks", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L93-L140
train
216,039
openstack/horizon
openstack_dashboard/dashboards/project/instances/utils.py
keypair_field_data
def keypair_field_data(request, include_empty_option=False): """Returns a list of tuples of all keypairs. Generates a list of keypairs available to the user (request). And returns a list of (id, name) tuples. :param request: django http request object :param include_empty_option: flag to include a empty tuple in the front of the list :return: list of (id, name) tuples """ keypair_list = [] try: keypairs = api.nova.keypair_list(request) keypair_list = [(kp.name, kp.name) for kp in keypairs] except Exception: exceptions.handle(request, _('Unable to retrieve key pairs.')) if not keypair_list: if include_empty_option: return [("", _("No key pairs available")), ] return [] if include_empty_option: return [("", _("Select a key pair")), ] + keypair_list return keypair_list
python
def keypair_field_data(request, include_empty_option=False): """Returns a list of tuples of all keypairs. Generates a list of keypairs available to the user (request). And returns a list of (id, name) tuples. :param request: django http request object :param include_empty_option: flag to include a empty tuple in the front of the list :return: list of (id, name) tuples """ keypair_list = [] try: keypairs = api.nova.keypair_list(request) keypair_list = [(kp.name, kp.name) for kp in keypairs] except Exception: exceptions.handle(request, _('Unable to retrieve key pairs.')) if not keypair_list: if include_empty_option: return [("", _("No key pairs available")), ] return [] if include_empty_option: return [("", _("Select a key pair")), ] + keypair_list return keypair_list
[ "def", "keypair_field_data", "(", "request", ",", "include_empty_option", "=", "False", ")", ":", "keypair_list", "=", "[", "]", "try", ":", "keypairs", "=", "api", ".", "nova", ".", "keypair_list", "(", "request", ")", "keypair_list", "=", "[", "(", "kp",...
Returns a list of tuples of all keypairs. Generates a list of keypairs available to the user (request). And returns a list of (id, name) tuples. :param request: django http request object :param include_empty_option: flag to include a empty tuple in the front of the list :return: list of (id, name) tuples
[ "Returns", "a", "list", "of", "tuples", "of", "all", "keypairs", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L143-L168
train
216,040
openstack/horizon
openstack_dashboard/dashboards/project/instances/utils.py
flavor_field_data
def flavor_field_data(request, include_empty_option=False): """Returns a list of tuples of all image flavors. Generates a list of image flavors available. And returns a list of (id, name) tuples. :param request: django http request object :param include_empty_option: flag to include a empty tuple in the front of the list :return: list of (id, name) tuples """ flavors = flavor_list(request) if flavors: flavors_list = sort_flavor_list(request, flavors) if include_empty_option: return [("", _("Select Flavor")), ] + flavors_list return flavors_list if include_empty_option: return [("", _("No flavors available")), ] return []
python
def flavor_field_data(request, include_empty_option=False): """Returns a list of tuples of all image flavors. Generates a list of image flavors available. And returns a list of (id, name) tuples. :param request: django http request object :param include_empty_option: flag to include a empty tuple in the front of the list :return: list of (id, name) tuples """ flavors = flavor_list(request) if flavors: flavors_list = sort_flavor_list(request, flavors) if include_empty_option: return [("", _("Select Flavor")), ] + flavors_list return flavors_list if include_empty_option: return [("", _("No flavors available")), ] return []
[ "def", "flavor_field_data", "(", "request", ",", "include_empty_option", "=", "False", ")", ":", "flavors", "=", "flavor_list", "(", "request", ")", "if", "flavors", ":", "flavors_list", "=", "sort_flavor_list", "(", "request", ",", "flavors", ")", "if", "incl...
Returns a list of tuples of all image flavors. Generates a list of image flavors available. And returns a list of (id, name) tuples. :param request: django http request object :param include_empty_option: flag to include a empty tuple in the front of the list :return: list of (id, name) tuples
[ "Returns", "a", "list", "of", "tuples", "of", "all", "image", "flavors", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L171-L191
train
216,041
openstack/horizon
openstack_dashboard/dashboards/project/instances/utils.py
port_field_data
def port_field_data(request, with_network=False): """Returns a list of tuples of all ports available for the tenant. Generates a list of ports that have no device_owner based on the networks available to the tenant doing the request. :param request: django http request object :param with_network: include network name in field name :return: list of (id, name) tuples """ def add_more_info_port_name(port, network): # add more info to the port for the display port_name = "{} ({})".format( port.name_or_id, ",".join( [ip['ip_address'] for ip in port['fixed_ips']])) if with_network and network: port_name += " - {}".format(network.name_or_id) return port_name ports = [] if api.base.is_service_enabled(request, 'network'): network_list = api.neutron.network_list_for_tenant( request, request.user.tenant_id) for network in network_list: ports.extend( [(port.id, add_more_info_port_name(port, network)) for port in api.neutron.port_list_with_trunk_types( request, network_id=network.id, tenant_id=request.user.tenant_id) if (not port.device_owner and not isinstance(port, api.neutron.PortTrunkSubport))]) ports.sort(key=lambda obj: obj[1]) return ports
python
def port_field_data(request, with_network=False): """Returns a list of tuples of all ports available for the tenant. Generates a list of ports that have no device_owner based on the networks available to the tenant doing the request. :param request: django http request object :param with_network: include network name in field name :return: list of (id, name) tuples """ def add_more_info_port_name(port, network): # add more info to the port for the display port_name = "{} ({})".format( port.name_or_id, ",".join( [ip['ip_address'] for ip in port['fixed_ips']])) if with_network and network: port_name += " - {}".format(network.name_or_id) return port_name ports = [] if api.base.is_service_enabled(request, 'network'): network_list = api.neutron.network_list_for_tenant( request, request.user.tenant_id) for network in network_list: ports.extend( [(port.id, add_more_info_port_name(port, network)) for port in api.neutron.port_list_with_trunk_types( request, network_id=network.id, tenant_id=request.user.tenant_id) if (not port.device_owner and not isinstance(port, api.neutron.PortTrunkSubport))]) ports.sort(key=lambda obj: obj[1]) return ports
[ "def", "port_field_data", "(", "request", ",", "with_network", "=", "False", ")", ":", "def", "add_more_info_port_name", "(", "port", ",", "network", ")", ":", "# add more info to the port for the display", "port_name", "=", "\"{} ({})\"", ".", "format", "(", "port"...
Returns a list of tuples of all ports available for the tenant. Generates a list of ports that have no device_owner based on the networks available to the tenant doing the request. :param request: django http request object :param with_network: include network name in field name :return: list of (id, name) tuples
[ "Returns", "a", "list", "of", "tuples", "of", "all", "ports", "available", "for", "the", "tenant", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L194-L227
train
216,042
openstack/horizon
openstack_dashboard/dashboards/project/instances/utils.py
server_group_field_data
def server_group_field_data(request): """Returns a list of tuples of all server groups. Generates a list of server groups available. And returns a list of (id, name) tuples. :param request: django http request object :return: list of (id, name) tuples """ server_groups = server_group_list(request) if server_groups: server_groups_list = [(sg.id, sg.name) for sg in server_groups] server_groups_list.sort(key=lambda obj: obj[1]) return [("", _("Select Server Group")), ] + server_groups_list return [("", _("No server groups available")), ]
python
def server_group_field_data(request): """Returns a list of tuples of all server groups. Generates a list of server groups available. And returns a list of (id, name) tuples. :param request: django http request object :return: list of (id, name) tuples """ server_groups = server_group_list(request) if server_groups: server_groups_list = [(sg.id, sg.name) for sg in server_groups] server_groups_list.sort(key=lambda obj: obj[1]) return [("", _("Select Server Group")), ] + server_groups_list return [("", _("No server groups available")), ]
[ "def", "server_group_field_data", "(", "request", ")", ":", "server_groups", "=", "server_group_list", "(", "request", ")", "if", "server_groups", ":", "server_groups_list", "=", "[", "(", "sg", ".", "id", ",", "sg", ".", "name", ")", "for", "sg", "in", "s...
Returns a list of tuples of all server groups. Generates a list of server groups available. And returns a list of (id, name) tuples. :param request: django http request object :return: list of (id, name) tuples
[ "Returns", "a", "list", "of", "tuples", "of", "all", "server", "groups", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L230-L245
train
216,043
openstack/horizon
openstack_dashboard/dashboards/project/routers/extensions/extraroutes/tables.py
ExtraRoutesTable.get_object_display
def get_object_display(self, datum): """Display ExtraRoutes when deleted.""" return (super(ExtraRoutesTable, self).get_object_display(datum) or datum.destination + " -> " + datum.nexthop)
python
def get_object_display(self, datum): """Display ExtraRoutes when deleted.""" return (super(ExtraRoutesTable, self).get_object_display(datum) or datum.destination + " -> " + datum.nexthop)
[ "def", "get_object_display", "(", "self", ",", "datum", ")", ":", "return", "(", "super", "(", "ExtraRoutesTable", ",", "self", ")", ".", "get_object_display", "(", "datum", ")", "or", "datum", ".", "destination", "+", "\" -> \"", "+", "datum", ".", "nexth...
Display ExtraRoutes when deleted.
[ "Display", "ExtraRoutes", "when", "deleted", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/routers/extensions/extraroutes/tables.py#L68-L71
train
216,044
openstack/horizon
openstack_dashboard/api/rest/json_encoder.py
NaNJSONEncoder.iterencode
def iterencode(self, o, _one_shot=False): """JSON encoder with NaN and float inf support. The sole purpose of defining a custom JSONEncoder class is to override floatstr() inner function, or more specifically the representation of NaN and +/-float('inf') values in a JSON. Although Infinity values are not supported by JSON standard, we still can convince Javascript JSON.parse() to create a Javascript Infinity object if we feed a token `1e+999` to it. """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encoder.encode_basestring_ascii else: _encoder = encoder.encode_basestring # On Python 3, JSONEncoder has no more encoding attribute, it produces # an Unicode string if six.PY2 and self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=float.__repr__, _inf=encoder.INFINITY, _neginf=-encoder.INFINITY): # Check for specials. Note that this type of test is processor # and/or platform-specific, so do tests which don't depend on the # internals. # NOTE: In Python, NaN == NaN returns False and it can be used # to detect NaN. # pylint: disable=comparison-with-itself if o != o: text = self.nan_str elif o == _inf: text = self.inf_str elif o == _neginf: text = '-' + self.inf_str else: return _repr(o) if not allow_nan: raise ValueError( _("Out of range float values are not JSON compliant: %r") % o) return text _iterencode = json.encoder._make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot) return _iterencode(o, 0)
python
def iterencode(self, o, _one_shot=False): """JSON encoder with NaN and float inf support. The sole purpose of defining a custom JSONEncoder class is to override floatstr() inner function, or more specifically the representation of NaN and +/-float('inf') values in a JSON. Although Infinity values are not supported by JSON standard, we still can convince Javascript JSON.parse() to create a Javascript Infinity object if we feed a token `1e+999` to it. """ if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encoder.encode_basestring_ascii else: _encoder = encoder.encode_basestring # On Python 3, JSONEncoder has no more encoding attribute, it produces # an Unicode string if six.PY2 and self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): if isinstance(o, str): o = o.decode(_encoding) return _orig_encoder(o) def floatstr(o, allow_nan=self.allow_nan, _repr=float.__repr__, _inf=encoder.INFINITY, _neginf=-encoder.INFINITY): # Check for specials. Note that this type of test is processor # and/or platform-specific, so do tests which don't depend on the # internals. # NOTE: In Python, NaN == NaN returns False and it can be used # to detect NaN. # pylint: disable=comparison-with-itself if o != o: text = self.nan_str elif o == _inf: text = self.inf_str elif o == _neginf: text = '-' + self.inf_str else: return _repr(o) if not allow_nan: raise ValueError( _("Out of range float values are not JSON compliant: %r") % o) return text _iterencode = json.encoder._make_iterencode( markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot) return _iterencode(o, 0)
[ "def", "iterencode", "(", "self", ",", "o", ",", "_one_shot", "=", "False", ")", ":", "if", "self", ".", "check_circular", ":", "markers", "=", "{", "}", "else", ":", "markers", "=", "None", "if", "self", ".", "ensure_ascii", ":", "_encoder", "=", "e...
JSON encoder with NaN and float inf support. The sole purpose of defining a custom JSONEncoder class is to override floatstr() inner function, or more specifically the representation of NaN and +/-float('inf') values in a JSON. Although Infinity values are not supported by JSON standard, we still can convince Javascript JSON.parse() to create a Javascript Infinity object if we feed a token `1e+999` to it.
[ "JSON", "encoder", "with", "NaN", "and", "float", "inf", "support", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/rest/json_encoder.py#L27-L84
train
216,045
openstack/horizon
openstack_dashboard/templatetags/context_selection.py
get_project_name
def get_project_name(project_id, projects): """Retrieves project name for given project id Args: projects: List of projects project_id: project id Returns: Project name or None if there is no match """ for project in projects: if project_id == project.id: return project.name
python
def get_project_name(project_id, projects): """Retrieves project name for given project id Args: projects: List of projects project_id: project id Returns: Project name or None if there is no match """ for project in projects: if project_id == project.id: return project.name
[ "def", "get_project_name", "(", "project_id", ",", "projects", ")", ":", "for", "project", "in", "projects", ":", "if", "project_id", "==", "project", ".", "id", ":", "return", "project", ".", "name" ]
Retrieves project name for given project id Args: projects: List of projects project_id: project id Returns: Project name or None if there is no match
[ "Retrieves", "project", "name", "for", "given", "project", "id" ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/templatetags/context_selection.py#L120-L131
train
216,046
openstack/horizon
horizon/templatetags/parse_date.py
ParseDateNode.render
def render(self, datestring): """Parses a date-like string into a timezone aware Python datetime.""" formats = ["%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"] if datestring: for format in formats: try: parsed = datetime.strptime(datestring, format) if not timezone.is_aware(parsed): parsed = timezone.make_aware(parsed, timezone.utc) return parsed except Exception: pass return None
python
def render(self, datestring): """Parses a date-like string into a timezone aware Python datetime.""" formats = ["%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"] if datestring: for format in formats: try: parsed = datetime.strptime(datestring, format) if not timezone.is_aware(parsed): parsed = timezone.make_aware(parsed, timezone.utc) return parsed except Exception: pass return None
[ "def", "render", "(", "self", ",", "datestring", ")", ":", "formats", "=", "[", "\"%Y-%m-%dT%H:%M:%S.%f\"", ",", "\"%Y-%m-%d %H:%M:%S.%f\"", ",", "\"%Y-%m-%dT%H:%M:%S\"", ",", "\"%Y-%m-%d %H:%M:%S\"", "]", "if", "datestring", ":", "for", "format", "in", "formats", ...
Parses a date-like string into a timezone aware Python datetime.
[ "Parses", "a", "date", "-", "like", "string", "into", "a", "timezone", "aware", "Python", "datetime", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/parse_date.py#L33-L46
train
216,047
openstack/horizon
horizon/utils/memoized.py
_try_weakref
def _try_weakref(arg, remove_callback): """Return a weak reference to arg if possible, or arg itself if not.""" try: arg = weakref.ref(arg, remove_callback) except TypeError: # Not all types can have a weakref. That includes strings # and floats and such, so just pass them through directly. pass return arg
python
def _try_weakref(arg, remove_callback): """Return a weak reference to arg if possible, or arg itself if not.""" try: arg = weakref.ref(arg, remove_callback) except TypeError: # Not all types can have a weakref. That includes strings # and floats and such, so just pass them through directly. pass return arg
[ "def", "_try_weakref", "(", "arg", ",", "remove_callback", ")", ":", "try", ":", "arg", "=", "weakref", ".", "ref", "(", "arg", ",", "remove_callback", ")", "except", "TypeError", ":", "# Not all types can have a weakref. That includes strings", "# and floats and such...
Return a weak reference to arg if possible, or arg itself if not.
[ "Return", "a", "weak", "reference", "to", "arg", "if", "possible", "or", "arg", "itself", "if", "not", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/memoized.py#L28-L36
train
216,048
openstack/horizon
horizon/utils/memoized.py
_get_key
def _get_key(args, kwargs, remove_callback): """Calculate the cache key, using weak references where possible.""" # Use tuples, because lists are not hashable. weak_args = tuple(_try_weakref(arg, remove_callback) for arg in args) # Use a tuple of (key, values) pairs, because dict is not hashable. # Sort it, so that we don't depend on the order of keys. weak_kwargs = tuple(sorted( (key, _try_weakref(value, remove_callback)) for (key, value) in kwargs.items())) return weak_args, weak_kwargs
python
def _get_key(args, kwargs, remove_callback): """Calculate the cache key, using weak references where possible.""" # Use tuples, because lists are not hashable. weak_args = tuple(_try_weakref(arg, remove_callback) for arg in args) # Use a tuple of (key, values) pairs, because dict is not hashable. # Sort it, so that we don't depend on the order of keys. weak_kwargs = tuple(sorted( (key, _try_weakref(value, remove_callback)) for (key, value) in kwargs.items())) return weak_args, weak_kwargs
[ "def", "_get_key", "(", "args", ",", "kwargs", ",", "remove_callback", ")", ":", "# Use tuples, because lists are not hashable.", "weak_args", "=", "tuple", "(", "_try_weakref", "(", "arg", ",", "remove_callback", ")", "for", "arg", "in", "args", ")", "# Use a tup...
Calculate the cache key, using weak references where possible.
[ "Calculate", "the", "cache", "key", "using", "weak", "references", "where", "possible", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/memoized.py#L39-L48
train
216,049
openstack/horizon
horizon/utils/memoized.py
memoized
def memoized(func=None, max_size=None): """Decorator that caches function calls. Caches the decorated function's return value the first time it is called with the given arguments. If called later with the same arguments, the cached value is returned instead of calling the decorated function again. It operates as a LRU cache and keeps up to the max_size value of cached items, always clearing oldest items first. The cache uses weak references to the passed arguments, so it doesn't keep them alive in memory forever. """ def decorate(func): # The dictionary in which all the data will be cached. This is a # separate instance for every decorated function, and it's stored in a # closure of the wrapped function. cache = collections.OrderedDict() locks = collections.defaultdict(threading.Lock) if max_size: max_cache_size = max_size else: max_cache_size = getattr(settings, 'MEMOIZED_MAX_SIZE_DEFAULT', 25) @functools.wraps(func) def wrapped(*args, **kwargs): # We need to have defined key early, to be able to use it in the # remove() function, but we calculate the actual value of the key # later on, because we need the remove() function for that. key = None def remove(ref): """A callback to remove outdated items from cache.""" try: # The key here is from closure, and is calculated later. del cache[key] del locks[key] except KeyError: # Some other weak reference might have already removed that # key -- in that case we don't need to do anything. pass key = _get_key(args, kwargs, remove) try: with locks[key]: try: # We want cache hit to be as fast as possible, and # don't really care much about the speed of a cache # miss, because it will only happen once and likely # calls some external API, database, or some other slow # thing. That's why the hit is in straightforward code, # and the miss is in an exception. # We also want to pop the key and reset it to make sure # the position it has in the order updates. value = cache[key] = cache.pop(key) except KeyError: value = cache[key] = func(*args, **kwargs) except TypeError: # The calculated key may be unhashable when an unhashable # object, such as a list, is passed as one of the arguments. In # that case, we can't cache anything and simply always call the # decorated function. warnings.warn( "The key of %s %s is not hashable and cannot be memoized: " "%r\n" % (func.__module__, func.__name__, key), UnhashableKeyWarning, 2) value = func(*args, **kwargs) while len(cache) > max_cache_size: try: popped_tuple = cache.popitem(last=False) locks.pop(popped_tuple[0], None) except KeyError: pass return value return wrapped if func and callable(func): return decorate(func) return decorate
python
def memoized(func=None, max_size=None): """Decorator that caches function calls. Caches the decorated function's return value the first time it is called with the given arguments. If called later with the same arguments, the cached value is returned instead of calling the decorated function again. It operates as a LRU cache and keeps up to the max_size value of cached items, always clearing oldest items first. The cache uses weak references to the passed arguments, so it doesn't keep them alive in memory forever. """ def decorate(func): # The dictionary in which all the data will be cached. This is a # separate instance for every decorated function, and it's stored in a # closure of the wrapped function. cache = collections.OrderedDict() locks = collections.defaultdict(threading.Lock) if max_size: max_cache_size = max_size else: max_cache_size = getattr(settings, 'MEMOIZED_MAX_SIZE_DEFAULT', 25) @functools.wraps(func) def wrapped(*args, **kwargs): # We need to have defined key early, to be able to use it in the # remove() function, but we calculate the actual value of the key # later on, because we need the remove() function for that. key = None def remove(ref): """A callback to remove outdated items from cache.""" try: # The key here is from closure, and is calculated later. del cache[key] del locks[key] except KeyError: # Some other weak reference might have already removed that # key -- in that case we don't need to do anything. pass key = _get_key(args, kwargs, remove) try: with locks[key]: try: # We want cache hit to be as fast as possible, and # don't really care much about the speed of a cache # miss, because it will only happen once and likely # calls some external API, database, or some other slow # thing. That's why the hit is in straightforward code, # and the miss is in an exception. # We also want to pop the key and reset it to make sure # the position it has in the order updates. value = cache[key] = cache.pop(key) except KeyError: value = cache[key] = func(*args, **kwargs) except TypeError: # The calculated key may be unhashable when an unhashable # object, such as a list, is passed as one of the arguments. In # that case, we can't cache anything and simply always call the # decorated function. warnings.warn( "The key of %s %s is not hashable and cannot be memoized: " "%r\n" % (func.__module__, func.__name__, key), UnhashableKeyWarning, 2) value = func(*args, **kwargs) while len(cache) > max_cache_size: try: popped_tuple = cache.popitem(last=False) locks.pop(popped_tuple[0], None) except KeyError: pass return value return wrapped if func and callable(func): return decorate(func) return decorate
[ "def", "memoized", "(", "func", "=", "None", ",", "max_size", "=", "None", ")", ":", "def", "decorate", "(", "func", ")", ":", "# The dictionary in which all the data will be cached. This is a", "# separate instance for every decorated function, and it's stored in a", "# clos...
Decorator that caches function calls. Caches the decorated function's return value the first time it is called with the given arguments. If called later with the same arguments, the cached value is returned instead of calling the decorated function again. It operates as a LRU cache and keeps up to the max_size value of cached items, always clearing oldest items first. The cache uses weak references to the passed arguments, so it doesn't keep them alive in memory forever.
[ "Decorator", "that", "caches", "function", "calls", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/memoized.py#L51-L132
train
216,050
openstack/horizon
openstack_dashboard/management/commands/make_web_conf.py
_getattr
def _getattr(obj, name, default): """Like getattr but return `default` if None or False. By default, getattr(obj, name, default) returns default only if attr does not exist, here, we return `default` even if attr evaluates to None or False. """ value = getattr(obj, name, default) if value: return value else: return default
python
def _getattr(obj, name, default): """Like getattr but return `default` if None or False. By default, getattr(obj, name, default) returns default only if attr does not exist, here, we return `default` even if attr evaluates to None or False. """ value = getattr(obj, name, default) if value: return value else: return default
[ "def", "_getattr", "(", "obj", ",", "name", ",", "default", ")", ":", "value", "=", "getattr", "(", "obj", ",", "name", ",", "default", ")", "if", "value", ":", "return", "value", "else", ":", "return", "default" ]
Like getattr but return `default` if None or False. By default, getattr(obj, name, default) returns default only if attr does not exist, here, we return `default` even if attr evaluates to None or False.
[ "Like", "getattr", "but", "return", "default", "if", "None", "or", "False", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/management/commands/make_web_conf.py#L56-L67
train
216,051
openstack/horizon
openstack_dashboard/api/neutron.py
list_resources_with_long_filters
def list_resources_with_long_filters(list_method, filter_attr, filter_values, **params): """List neutron resources with handling RequestURITooLong exception. If filter parameters are long, list resources API request leads to 414 error (URL is too long). For such case, this method split list parameters specified by a list_field argument into chunks and call the specified list_method repeatedly. :param list_method: Method used to retrieve resource list. :param filter_attr: attribute name to be filtered. The value corresponding to this attribute is specified by "filter_values". If you want to specify more attributes for a filter condition, pass them as keyword arguments like "attr2=values2". :param filter_values: values of "filter_attr" to be filtered. If filter_values are too long and the total URI length exceed the maximum length supported by the neutron server, filter_values will be split into sub lists if filter_values is a list. :param params: parameters to pass a specified listing API call without any changes. You can specify more filter conditions in addition to a pair of filter_attr and filter_values. """ try: params[filter_attr] = filter_values return list_method(**params) except neutron_exc.RequestURITooLong as uri_len_exc: # The URI is too long because of too many filter values. # Use the excess attribute of the exception to know how many # filter values can be inserted into a single request. # We consider only the filter condition from (filter_attr, # filter_values) and do not consider other filter conditions # which may be specified in **params. if not isinstance(filter_values, (list, tuple, set, frozenset)): filter_values = [filter_values] # Length of each query filter is: # <key>=<value>& (e.g., id=<uuid>) # The length will be key_len + value_maxlen + 2 all_filter_len = sum(len(filter_attr) + len(val) + 2 for val in filter_values) allowed_filter_len = all_filter_len - uri_len_exc.excess val_maxlen = max(len(val) for val in filter_values) filter_maxlen = len(filter_attr) + val_maxlen + 2 chunk_size = allowed_filter_len // filter_maxlen resources = [] for i in range(0, len(filter_values), chunk_size): params[filter_attr] = filter_values[i:i + chunk_size] resources.extend(list_method(**params)) return resources
python
def list_resources_with_long_filters(list_method, filter_attr, filter_values, **params): """List neutron resources with handling RequestURITooLong exception. If filter parameters are long, list resources API request leads to 414 error (URL is too long). For such case, this method split list parameters specified by a list_field argument into chunks and call the specified list_method repeatedly. :param list_method: Method used to retrieve resource list. :param filter_attr: attribute name to be filtered. The value corresponding to this attribute is specified by "filter_values". If you want to specify more attributes for a filter condition, pass them as keyword arguments like "attr2=values2". :param filter_values: values of "filter_attr" to be filtered. If filter_values are too long and the total URI length exceed the maximum length supported by the neutron server, filter_values will be split into sub lists if filter_values is a list. :param params: parameters to pass a specified listing API call without any changes. You can specify more filter conditions in addition to a pair of filter_attr and filter_values. """ try: params[filter_attr] = filter_values return list_method(**params) except neutron_exc.RequestURITooLong as uri_len_exc: # The URI is too long because of too many filter values. # Use the excess attribute of the exception to know how many # filter values can be inserted into a single request. # We consider only the filter condition from (filter_attr, # filter_values) and do not consider other filter conditions # which may be specified in **params. if not isinstance(filter_values, (list, tuple, set, frozenset)): filter_values = [filter_values] # Length of each query filter is: # <key>=<value>& (e.g., id=<uuid>) # The length will be key_len + value_maxlen + 2 all_filter_len = sum(len(filter_attr) + len(val) + 2 for val in filter_values) allowed_filter_len = all_filter_len - uri_len_exc.excess val_maxlen = max(len(val) for val in filter_values) filter_maxlen = len(filter_attr) + val_maxlen + 2 chunk_size = allowed_filter_len // filter_maxlen resources = [] for i in range(0, len(filter_values), chunk_size): params[filter_attr] = filter_values[i:i + chunk_size] resources.extend(list_method(**params)) return resources
[ "def", "list_resources_with_long_filters", "(", "list_method", ",", "filter_attr", ",", "filter_values", ",", "*", "*", "params", ")", ":", "try", ":", "params", "[", "filter_attr", "]", "=", "filter_values", "return", "list_method", "(", "*", "*", "params", "...
List neutron resources with handling RequestURITooLong exception. If filter parameters are long, list resources API request leads to 414 error (URL is too long). For such case, this method split list parameters specified by a list_field argument into chunks and call the specified list_method repeatedly. :param list_method: Method used to retrieve resource list. :param filter_attr: attribute name to be filtered. The value corresponding to this attribute is specified by "filter_values". If you want to specify more attributes for a filter condition, pass them as keyword arguments like "attr2=values2". :param filter_values: values of "filter_attr" to be filtered. If filter_values are too long and the total URI length exceed the maximum length supported by the neutron server, filter_values will be split into sub lists if filter_values is a list. :param params: parameters to pass a specified listing API call without any changes. You can specify more filter conditions in addition to a pair of filter_attr and filter_values.
[ "List", "neutron", "resources", "with", "handling", "RequestURITooLong", "exception", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L821-L872
train
216,052
openstack/horizon
openstack_dashboard/api/neutron.py
network_list_for_tenant
def network_list_for_tenant(request, tenant_id, include_external=False, include_pre_auto_allocate=False, **params): """Return a network list available for the tenant. The list contains networks owned by the tenant and public networks. If requested_networks specified, it searches requested_networks only. """ LOG.debug("network_list_for_tenant(): tenant_id=%(tenant_id)s, " "params=%(params)s", {'tenant_id': tenant_id, 'params': params}) networks = [] shared = params.get('shared') if shared is not None: del params['shared'] if shared in (None, False): # If a user has admin role, network list returned by Neutron API # contains networks that do not belong to that tenant. # So we need to specify tenant_id when calling network_list(). networks += network_list(request, tenant_id=tenant_id, shared=False, **params) if shared in (None, True): # In the current Neutron API, there is no way to retrieve # both owner networks and public networks in a single API call. networks += network_list(request, shared=True, **params) # Hack for auto allocated network if include_pre_auto_allocate and not networks: if _is_auto_allocated_network_supported(request): networks.append(PreAutoAllocateNetwork(request)) params['router:external'] = params.get('router:external', True) if params['router:external'] and include_external: if shared is not None: params['shared'] = shared fetched_net_ids = [n.id for n in networks] # Retrieves external networks when router:external is not specified # in (filtering) params or router:external=True filter is specified. # When router:external=False is specified there is no need to query # networking API because apparently nothing will match the filter. ext_nets = network_list(request, **params) networks += [n for n in ext_nets if n.id not in fetched_net_ids] return networks
python
def network_list_for_tenant(request, tenant_id, include_external=False, include_pre_auto_allocate=False, **params): """Return a network list available for the tenant. The list contains networks owned by the tenant and public networks. If requested_networks specified, it searches requested_networks only. """ LOG.debug("network_list_for_tenant(): tenant_id=%(tenant_id)s, " "params=%(params)s", {'tenant_id': tenant_id, 'params': params}) networks = [] shared = params.get('shared') if shared is not None: del params['shared'] if shared in (None, False): # If a user has admin role, network list returned by Neutron API # contains networks that do not belong to that tenant. # So we need to specify tenant_id when calling network_list(). networks += network_list(request, tenant_id=tenant_id, shared=False, **params) if shared in (None, True): # In the current Neutron API, there is no way to retrieve # both owner networks and public networks in a single API call. networks += network_list(request, shared=True, **params) # Hack for auto allocated network if include_pre_auto_allocate and not networks: if _is_auto_allocated_network_supported(request): networks.append(PreAutoAllocateNetwork(request)) params['router:external'] = params.get('router:external', True) if params['router:external'] and include_external: if shared is not None: params['shared'] = shared fetched_net_ids = [n.id for n in networks] # Retrieves external networks when router:external is not specified # in (filtering) params or router:external=True filter is specified. # When router:external=False is specified there is no need to query # networking API because apparently nothing will match the filter. ext_nets = network_list(request, **params) networks += [n for n in ext_nets if n.id not in fetched_net_ids] return networks
[ "def", "network_list_for_tenant", "(", "request", ",", "tenant_id", ",", "include_external", "=", "False", ",", "include_pre_auto_allocate", "=", "False", ",", "*", "*", "params", ")", ":", "LOG", ".", "debug", "(", "\"network_list_for_tenant(): tenant_id=%(tenant_id)...
Return a network list available for the tenant. The list contains networks owned by the tenant and public networks. If requested_networks specified, it searches requested_networks only.
[ "Return", "a", "network", "list", "available", "for", "the", "tenant", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1052-L1098
train
216,053
openstack/horizon
openstack_dashboard/api/neutron.py
network_create
def network_create(request, **kwargs): """Create a network object. :param request: request context :param tenant_id: (optional) tenant id of the network created :param name: (optional) name of the network created :returns: Network object """ LOG.debug("network_create(): kwargs = %s", kwargs) if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body = {'network': kwargs} network = neutronclient(request).create_network(body=body).get('network') return Network(network)
python
def network_create(request, **kwargs): """Create a network object. :param request: request context :param tenant_id: (optional) tenant id of the network created :param name: (optional) name of the network created :returns: Network object """ LOG.debug("network_create(): kwargs = %s", kwargs) if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body = {'network': kwargs} network = neutronclient(request).create_network(body=body).get('network') return Network(network)
[ "def", "network_create", "(", "request", ",", "*", "*", "kwargs", ")", ":", "LOG", ".", "debug", "(", "\"network_create(): kwargs = %s\"", ",", "kwargs", ")", "if", "'tenant_id'", "not", "in", "kwargs", ":", "kwargs", "[", "'tenant_id'", "]", "=", "request",...
Create a network object. :param request: request context :param tenant_id: (optional) tenant id of the network created :param name: (optional) name of the network created :returns: Network object
[ "Create", "a", "network", "object", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1129-L1142
train
216,054
openstack/horizon
openstack_dashboard/api/neutron.py
subnet_create
def subnet_create(request, network_id, **kwargs): """Create a subnet on a specified network. :param request: request context :param network_id: network id a subnet is created on :param cidr: (optional) subnet IP address range :param ip_version: (optional) IP version (4 or 6) :param gateway_ip: (optional) IP address of gateway :param tenant_id: (optional) tenant id of the subnet created :param name: (optional) name of the subnet created :param subnetpool_id: (optional) subnetpool to allocate prefix from :param prefixlen: (optional) length of prefix to allocate :returns: Subnet object Although both cidr+ip_version and subnetpool_id+preifxlen is listed as optional you MUST pass along one of the combinations to get a successful result. """ LOG.debug("subnet_create(): netid=%(network_id)s, kwargs=%(kwargs)s", {'network_id': network_id, 'kwargs': kwargs}) body = {'subnet': {'network_id': network_id}} if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body['subnet'].update(kwargs) subnet = neutronclient(request).create_subnet(body=body).get('subnet') return Subnet(subnet)
python
def subnet_create(request, network_id, **kwargs): """Create a subnet on a specified network. :param request: request context :param network_id: network id a subnet is created on :param cidr: (optional) subnet IP address range :param ip_version: (optional) IP version (4 or 6) :param gateway_ip: (optional) IP address of gateway :param tenant_id: (optional) tenant id of the subnet created :param name: (optional) name of the subnet created :param subnetpool_id: (optional) subnetpool to allocate prefix from :param prefixlen: (optional) length of prefix to allocate :returns: Subnet object Although both cidr+ip_version and subnetpool_id+preifxlen is listed as optional you MUST pass along one of the combinations to get a successful result. """ LOG.debug("subnet_create(): netid=%(network_id)s, kwargs=%(kwargs)s", {'network_id': network_id, 'kwargs': kwargs}) body = {'subnet': {'network_id': network_id}} if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body['subnet'].update(kwargs) subnet = neutronclient(request).create_subnet(body=body).get('subnet') return Subnet(subnet)
[ "def", "subnet_create", "(", "request", ",", "network_id", ",", "*", "*", "kwargs", ")", ":", "LOG", ".", "debug", "(", "\"subnet_create(): netid=%(network_id)s, kwargs=%(kwargs)s\"", ",", "{", "'network_id'", ":", "network_id", ",", "'kwargs'", ":", "kwargs", "}"...
Create a subnet on a specified network. :param request: request context :param network_id: network id a subnet is created on :param cidr: (optional) subnet IP address range :param ip_version: (optional) IP version (4 or 6) :param gateway_ip: (optional) IP address of gateway :param tenant_id: (optional) tenant id of the subnet created :param name: (optional) name of the subnet created :param subnetpool_id: (optional) subnetpool to allocate prefix from :param prefixlen: (optional) length of prefix to allocate :returns: Subnet object Although both cidr+ip_version and subnetpool_id+preifxlen is listed as optional you MUST pass along one of the combinations to get a successful result.
[ "Create", "a", "subnet", "on", "a", "specified", "network", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1179-L1204
train
216,055
openstack/horizon
openstack_dashboard/api/neutron.py
subnetpool_create
def subnetpool_create(request, name, prefixes, **kwargs): """Create a subnetpool. ip_version is auto-detected in back-end. Parameters: request -- Request context name -- Name for subnetpool prefixes -- List of prefixes for pool Keyword Arguments (optional): min_prefixlen -- Minimum prefix length for allocations from pool max_prefixlen -- Maximum prefix length for allocations from pool default_prefixlen -- Default prefix length for allocations from pool default_quota -- Default quota for allocations from pool shared -- Subnetpool should be shared (Admin-only) tenant_id -- Owner of subnetpool Returns: SubnetPool object """ LOG.debug("subnetpool_create(): name=%(name)s, prefixes=%(prefixes)s, " "kwargs=%(kwargs)s", {'name': name, 'prefixes': prefixes, 'kwargs': kwargs}) body = {'subnetpool': {'name': name, 'prefixes': prefixes, } } if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body['subnetpool'].update(kwargs) subnetpool = \ neutronclient(request).create_subnetpool(body=body).get('subnetpool') return SubnetPool(subnetpool)
python
def subnetpool_create(request, name, prefixes, **kwargs): """Create a subnetpool. ip_version is auto-detected in back-end. Parameters: request -- Request context name -- Name for subnetpool prefixes -- List of prefixes for pool Keyword Arguments (optional): min_prefixlen -- Minimum prefix length for allocations from pool max_prefixlen -- Maximum prefix length for allocations from pool default_prefixlen -- Default prefix length for allocations from pool default_quota -- Default quota for allocations from pool shared -- Subnetpool should be shared (Admin-only) tenant_id -- Owner of subnetpool Returns: SubnetPool object """ LOG.debug("subnetpool_create(): name=%(name)s, prefixes=%(prefixes)s, " "kwargs=%(kwargs)s", {'name': name, 'prefixes': prefixes, 'kwargs': kwargs}) body = {'subnetpool': {'name': name, 'prefixes': prefixes, } } if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body['subnetpool'].update(kwargs) subnetpool = \ neutronclient(request).create_subnetpool(body=body).get('subnetpool') return SubnetPool(subnetpool)
[ "def", "subnetpool_create", "(", "request", ",", "name", ",", "prefixes", ",", "*", "*", "kwargs", ")", ":", "LOG", ".", "debug", "(", "\"subnetpool_create(): name=%(name)s, prefixes=%(prefixes)s, \"", "\"kwargs=%(kwargs)s\"", ",", "{", "'name'", ":", "name", ",", ...
Create a subnetpool. ip_version is auto-detected in back-end. Parameters: request -- Request context name -- Name for subnetpool prefixes -- List of prefixes for pool Keyword Arguments (optional): min_prefixlen -- Minimum prefix length for allocations from pool max_prefixlen -- Maximum prefix length for allocations from pool default_prefixlen -- Default prefix length for allocations from pool default_quota -- Default quota for allocations from pool shared -- Subnetpool should be shared (Admin-only) tenant_id -- Owner of subnetpool Returns: SubnetPool object
[ "Create", "a", "subnetpool", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1243-L1277
train
216,056
openstack/horizon
openstack_dashboard/api/neutron.py
port_list_with_trunk_types
def port_list_with_trunk_types(request, **params): """List neutron Ports for this tenant with possible TrunkPort indicated :param request: request context NOTE Performing two API calls is not atomic, but this is not worse than the original idea when we call port_list repeatedly for each network to perform identification run-time. We should handle the inconsistencies caused by non-atomic API requests gracefully. """ LOG.debug("port_list_with_trunk_types(): params=%s", params) # When trunk feature is disabled in neutron, we have no need to fetch # trunk information and port_list() is enough. if not is_extension_supported(request, 'trunk'): return port_list(request, **params) ports = neutronclient(request).list_ports(**params)['ports'] trunk_filters = {} if 'tenant_id' in params: trunk_filters['tenant_id'] = params['tenant_id'] trunks = neutronclient(request).list_trunks(**trunk_filters)['trunks'] parent_ports = set(t['port_id'] for t in trunks) # Create a dict map for child ports (port ID to trunk info) child_ports = dict((s['port_id'], {'trunk_id': t['id'], 'segmentation_type': s['segmentation_type'], 'segmentation_id': s['segmentation_id']}) for t in trunks for s in t['sub_ports']) def _get_port_info(port): if port['id'] in parent_ports: return PortTrunkParent(port) elif port['id'] in child_ports: return PortTrunkSubport(port, child_ports[port['id']]) else: return Port(port) return [_get_port_info(p) for p in ports]
python
def port_list_with_trunk_types(request, **params): """List neutron Ports for this tenant with possible TrunkPort indicated :param request: request context NOTE Performing two API calls is not atomic, but this is not worse than the original idea when we call port_list repeatedly for each network to perform identification run-time. We should handle the inconsistencies caused by non-atomic API requests gracefully. """ LOG.debug("port_list_with_trunk_types(): params=%s", params) # When trunk feature is disabled in neutron, we have no need to fetch # trunk information and port_list() is enough. if not is_extension_supported(request, 'trunk'): return port_list(request, **params) ports = neutronclient(request).list_ports(**params)['ports'] trunk_filters = {} if 'tenant_id' in params: trunk_filters['tenant_id'] = params['tenant_id'] trunks = neutronclient(request).list_trunks(**trunk_filters)['trunks'] parent_ports = set(t['port_id'] for t in trunks) # Create a dict map for child ports (port ID to trunk info) child_ports = dict((s['port_id'], {'trunk_id': t['id'], 'segmentation_type': s['segmentation_type'], 'segmentation_id': s['segmentation_id']}) for t in trunks for s in t['sub_ports']) def _get_port_info(port): if port['id'] in parent_ports: return PortTrunkParent(port) elif port['id'] in child_ports: return PortTrunkSubport(port, child_ports[port['id']]) else: return Port(port) return [_get_port_info(p) for p in ports]
[ "def", "port_list_with_trunk_types", "(", "request", ",", "*", "*", "params", ")", ":", "LOG", ".", "debug", "(", "\"port_list_with_trunk_types(): params=%s\"", ",", "params", ")", "# When trunk feature is disabled in neutron, we have no need to fetch", "# trunk information and...
List neutron Ports for this tenant with possible TrunkPort indicated :param request: request context NOTE Performing two API calls is not atomic, but this is not worse than the original idea when we call port_list repeatedly for each network to perform identification run-time. We should handle the inconsistencies caused by non-atomic API requests gracefully.
[ "List", "neutron", "Ports", "for", "this", "tenant", "with", "possible", "TrunkPort", "indicated" ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1308-L1348
train
216,057
openstack/horizon
openstack_dashboard/api/neutron.py
port_create
def port_create(request, network_id, **kwargs): """Create a port on a specified network. :param request: request context :param network_id: network id a subnet is created on :param device_id: (optional) device id attached to the port :param tenant_id: (optional) tenant id of the port created :param name: (optional) name of the port created :returns: Port object """ LOG.debug("port_create(): netid=%(network_id)s, kwargs=%(kwargs)s", {'network_id': network_id, 'kwargs': kwargs}) kwargs = unescape_port_kwargs(**kwargs) body = {'port': {'network_id': network_id}} if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body['port'].update(kwargs) port = neutronclient(request).create_port(body=body).get('port') return Port(port)
python
def port_create(request, network_id, **kwargs): """Create a port on a specified network. :param request: request context :param network_id: network id a subnet is created on :param device_id: (optional) device id attached to the port :param tenant_id: (optional) tenant id of the port created :param name: (optional) name of the port created :returns: Port object """ LOG.debug("port_create(): netid=%(network_id)s, kwargs=%(kwargs)s", {'network_id': network_id, 'kwargs': kwargs}) kwargs = unescape_port_kwargs(**kwargs) body = {'port': {'network_id': network_id}} if 'tenant_id' not in kwargs: kwargs['tenant_id'] = request.user.project_id body['port'].update(kwargs) port = neutronclient(request).create_port(body=body).get('port') return Port(port)
[ "def", "port_create", "(", "request", ",", "network_id", ",", "*", "*", "kwargs", ")", ":", "LOG", ".", "debug", "(", "\"port_create(): netid=%(network_id)s, kwargs=%(kwargs)s\"", ",", "{", "'network_id'", ":", "network_id", ",", "'kwargs'", ":", "kwargs", "}", ...
Create a port on a specified network. :param request: request context :param network_id: network id a subnet is created on :param device_id: (optional) device id attached to the port :param tenant_id: (optional) tenant id of the port created :param name: (optional) name of the port created :returns: Port object
[ "Create", "a", "port", "on", "a", "specified", "network", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1367-L1385
train
216,058
openstack/horizon
openstack_dashboard/api/neutron.py
list_extensions
def list_extensions(request): """List neutron extensions. :param request: django request object """ neutron_api = neutronclient(request) try: extensions_list = neutron_api.list_extensions() except exceptions.ServiceCatalogException: return {} if 'extensions' in extensions_list: return tuple(extensions_list['extensions']) else: return ()
python
def list_extensions(request): """List neutron extensions. :param request: django request object """ neutron_api = neutronclient(request) try: extensions_list = neutron_api.list_extensions() except exceptions.ServiceCatalogException: return {} if 'extensions' in extensions_list: return tuple(extensions_list['extensions']) else: return ()
[ "def", "list_extensions", "(", "request", ")", ":", "neutron_api", "=", "neutronclient", "(", "request", ")", "try", ":", "extensions_list", "=", "neutron_api", ".", "list_extensions", "(", ")", "except", "exceptions", ".", "ServiceCatalogException", ":", "return"...
List neutron extensions. :param request: django request object
[ "List", "neutron", "extensions", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1795-L1808
train
216,059
openstack/horizon
openstack_dashboard/api/neutron.py
is_extension_supported
def is_extension_supported(request, extension_alias): """Check if a specified extension is supported. :param request: django request object :param extension_alias: neutron extension alias """ extensions = list_extensions(request) for extension in extensions: if extension['alias'] == extension_alias: return True else: return False
python
def is_extension_supported(request, extension_alias): """Check if a specified extension is supported. :param request: django request object :param extension_alias: neutron extension alias """ extensions = list_extensions(request) for extension in extensions: if extension['alias'] == extension_alias: return True else: return False
[ "def", "is_extension_supported", "(", "request", ",", "extension_alias", ")", ":", "extensions", "=", "list_extensions", "(", "request", ")", "for", "extension", "in", "extensions", ":", "if", "extension", "[", "'alias'", "]", "==", "extension_alias", ":", "retu...
Check if a specified extension is supported. :param request: django request object :param extension_alias: neutron extension alias
[ "Check", "if", "a", "specified", "extension", "is", "supported", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1812-L1823
train
216,060
openstack/horizon
openstack_dashboard/api/neutron.py
get_feature_permission
def get_feature_permission(request, feature, operation=None): """Check if a feature-specific field can be displayed. This method check a permission for a feature-specific field. Such field is usually provided through Neutron extension. :param request: Request Object :param feature: feature name defined in FEATURE_MAP :param operation (optional): Operation type. The valid value should be defined in FEATURE_MAP[feature]['policies'] It must be specified if FEATURE_MAP[feature] has 'policies'. """ network_config = getattr(settings, 'OPENSTACK_NEUTRON_NETWORK', {}) feature_info = FEATURE_MAP.get(feature) if not feature_info: raise ValueError("The requested feature '%(feature)s' is unknown. " "Please make sure to specify a feature defined " "in FEATURE_MAP.") # Check dashboard settings feature_config = feature_info.get('config') if feature_config: if not network_config.get(feature_config['name'], feature_config['default']): return False # Check policy feature_policies = feature_info.get('policies') if feature_policies: policy_name = feature_policies.get(operation) if not policy_name: raise ValueError("The 'operation' parameter for " "get_feature_permission '%(feature)s' " "is invalid. It should be one of %(allowed)s" % {'feature': feature, 'allowed': ' '.join(feature_policies.keys())}) role = (('network', policy_name),) if not policy.check(role, request): return False # Check if a required extension is enabled feature_extension = feature_info.get('extension') if feature_extension: try: return is_extension_supported(request, feature_extension) except Exception: LOG.info("Failed to check Neutron '%s' extension is not supported", feature_extension) return False # If all checks are passed, now a given feature is allowed. return True
python
def get_feature_permission(request, feature, operation=None): """Check if a feature-specific field can be displayed. This method check a permission for a feature-specific field. Such field is usually provided through Neutron extension. :param request: Request Object :param feature: feature name defined in FEATURE_MAP :param operation (optional): Operation type. The valid value should be defined in FEATURE_MAP[feature]['policies'] It must be specified if FEATURE_MAP[feature] has 'policies'. """ network_config = getattr(settings, 'OPENSTACK_NEUTRON_NETWORK', {}) feature_info = FEATURE_MAP.get(feature) if not feature_info: raise ValueError("The requested feature '%(feature)s' is unknown. " "Please make sure to specify a feature defined " "in FEATURE_MAP.") # Check dashboard settings feature_config = feature_info.get('config') if feature_config: if not network_config.get(feature_config['name'], feature_config['default']): return False # Check policy feature_policies = feature_info.get('policies') if feature_policies: policy_name = feature_policies.get(operation) if not policy_name: raise ValueError("The 'operation' parameter for " "get_feature_permission '%(feature)s' " "is invalid. It should be one of %(allowed)s" % {'feature': feature, 'allowed': ' '.join(feature_policies.keys())}) role = (('network', policy_name),) if not policy.check(role, request): return False # Check if a required extension is enabled feature_extension = feature_info.get('extension') if feature_extension: try: return is_extension_supported(request, feature_extension) except Exception: LOG.info("Failed to check Neutron '%s' extension is not supported", feature_extension) return False # If all checks are passed, now a given feature is allowed. return True
[ "def", "get_feature_permission", "(", "request", ",", "feature", ",", "operation", "=", "None", ")", ":", "network_config", "=", "getattr", "(", "settings", ",", "'OPENSTACK_NEUTRON_NETWORK'", ",", "{", "}", ")", "feature_info", "=", "FEATURE_MAP", ".", "get", ...
Check if a feature-specific field can be displayed. This method check a permission for a feature-specific field. Such field is usually provided through Neutron extension. :param request: Request Object :param feature: feature name defined in FEATURE_MAP :param operation (optional): Operation type. The valid value should be defined in FEATURE_MAP[feature]['policies'] It must be specified if FEATURE_MAP[feature] has 'policies'.
[ "Check", "if", "a", "feature", "-", "specific", "field", "can", "be", "displayed", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1889-L1940
train
216,061
openstack/horizon
openstack_dashboard/api/neutron.py
policy_create
def policy_create(request, **kwargs): """Create a QoS Policy. :param request: request context :param name: name of the policy :param description: description of policy :param shared: boolean (true or false) :return: QoSPolicy object """ body = {'policy': kwargs} policy = neutronclient(request).create_qos_policy(body=body).get('policy') return QoSPolicy(policy)
python
def policy_create(request, **kwargs): """Create a QoS Policy. :param request: request context :param name: name of the policy :param description: description of policy :param shared: boolean (true or false) :return: QoSPolicy object """ body = {'policy': kwargs} policy = neutronclient(request).create_qos_policy(body=body).get('policy') return QoSPolicy(policy)
[ "def", "policy_create", "(", "request", ",", "*", "*", "kwargs", ")", ":", "body", "=", "{", "'policy'", ":", "kwargs", "}", "policy", "=", "neutronclient", "(", "request", ")", ".", "create_qos_policy", "(", "body", "=", "body", ")", ".", "get", "(", ...
Create a QoS Policy. :param request: request context :param name: name of the policy :param description: description of policy :param shared: boolean (true or false) :return: QoSPolicy object
[ "Create", "a", "QoS", "Policy", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1950-L1961
train
216,062
openstack/horizon
openstack_dashboard/api/neutron.py
policy_list
def policy_list(request, **kwargs): """List of QoS Policies.""" policies = neutronclient(request).list_qos_policies( **kwargs).get('policies') return [QoSPolicy(p) for p in policies]
python
def policy_list(request, **kwargs): """List of QoS Policies.""" policies = neutronclient(request).list_qos_policies( **kwargs).get('policies') return [QoSPolicy(p) for p in policies]
[ "def", "policy_list", "(", "request", ",", "*", "*", "kwargs", ")", ":", "policies", "=", "neutronclient", "(", "request", ")", ".", "list_qos_policies", "(", "*", "*", "kwargs", ")", ".", "get", "(", "'policies'", ")", "return", "[", "QoSPolicy", "(", ...
List of QoS Policies.
[ "List", "of", "QoS", "Policies", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1964-L1968
train
216,063
openstack/horizon
openstack_dashboard/api/neutron.py
policy_get
def policy_get(request, policy_id, **kwargs): """Get QoS policy for a given policy id.""" policy = neutronclient(request).show_qos_policy( policy_id, **kwargs).get('policy') return QoSPolicy(policy)
python
def policy_get(request, policy_id, **kwargs): """Get QoS policy for a given policy id.""" policy = neutronclient(request).show_qos_policy( policy_id, **kwargs).get('policy') return QoSPolicy(policy)
[ "def", "policy_get", "(", "request", ",", "policy_id", ",", "*", "*", "kwargs", ")", ":", "policy", "=", "neutronclient", "(", "request", ")", ".", "show_qos_policy", "(", "policy_id", ",", "*", "*", "kwargs", ")", ".", "get", "(", "'policy'", ")", "re...
Get QoS policy for a given policy id.
[ "Get", "QoS", "policy", "for", "a", "given", "policy", "id", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L1972-L1976
train
216,064
openstack/horizon
openstack_dashboard/api/neutron.py
rbac_policy_create
def rbac_policy_create(request, **kwargs): """Create a RBAC Policy. :param request: request context :param target_tenant: target tenant of the policy :param tenant_id: owner tenant of the policy(Not recommended) :param object_type: network or qos_policy :param object_id: object id of policy :param action: access_as_shared or access_as_external :return: RBACPolicy object """ body = {'rbac_policy': kwargs} rbac_policy = neutronclient(request).create_rbac_policy( body=body).get('rbac_policy') return RBACPolicy(rbac_policy)
python
def rbac_policy_create(request, **kwargs): """Create a RBAC Policy. :param request: request context :param target_tenant: target tenant of the policy :param tenant_id: owner tenant of the policy(Not recommended) :param object_type: network or qos_policy :param object_id: object id of policy :param action: access_as_shared or access_as_external :return: RBACPolicy object """ body = {'rbac_policy': kwargs} rbac_policy = neutronclient(request).create_rbac_policy( body=body).get('rbac_policy') return RBACPolicy(rbac_policy)
[ "def", "rbac_policy_create", "(", "request", ",", "*", "*", "kwargs", ")", ":", "body", "=", "{", "'rbac_policy'", ":", "kwargs", "}", "rbac_policy", "=", "neutronclient", "(", "request", ")", ".", "create_rbac_policy", "(", "body", "=", "body", ")", ".", ...
Create a RBAC Policy. :param request: request context :param target_tenant: target tenant of the policy :param tenant_id: owner tenant of the policy(Not recommended) :param object_type: network or qos_policy :param object_id: object id of policy :param action: access_as_shared or access_as_external :return: RBACPolicy object
[ "Create", "a", "RBAC", "Policy", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L2001-L2015
train
216,065
openstack/horizon
openstack_dashboard/api/neutron.py
rbac_policy_list
def rbac_policy_list(request, **kwargs): """List of RBAC Policies.""" policies = neutronclient(request).list_rbac_policies( **kwargs).get('rbac_policies') return [RBACPolicy(p) for p in policies]
python
def rbac_policy_list(request, **kwargs): """List of RBAC Policies.""" policies = neutronclient(request).list_rbac_policies( **kwargs).get('rbac_policies') return [RBACPolicy(p) for p in policies]
[ "def", "rbac_policy_list", "(", "request", ",", "*", "*", "kwargs", ")", ":", "policies", "=", "neutronclient", "(", "request", ")", ".", "list_rbac_policies", "(", "*", "*", "kwargs", ")", ".", "get", "(", "'rbac_policies'", ")", "return", "[", "RBACPolic...
List of RBAC Policies.
[ "List", "of", "RBAC", "Policies", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L2018-L2022
train
216,066
openstack/horizon
openstack_dashboard/api/neutron.py
rbac_policy_update
def rbac_policy_update(request, policy_id, **kwargs): """Update a RBAC Policy. :param request: request context :param policy_id: target policy id :param target_tenant: target tenant of the policy :return: RBACPolicy object """ body = {'rbac_policy': kwargs} rbac_policy = neutronclient(request).update_rbac_policy( policy_id, body=body).get('rbac_policy') return RBACPolicy(rbac_policy)
python
def rbac_policy_update(request, policy_id, **kwargs): """Update a RBAC Policy. :param request: request context :param policy_id: target policy id :param target_tenant: target tenant of the policy :return: RBACPolicy object """ body = {'rbac_policy': kwargs} rbac_policy = neutronclient(request).update_rbac_policy( policy_id, body=body).get('rbac_policy') return RBACPolicy(rbac_policy)
[ "def", "rbac_policy_update", "(", "request", ",", "policy_id", ",", "*", "*", "kwargs", ")", ":", "body", "=", "{", "'rbac_policy'", ":", "kwargs", "}", "rbac_policy", "=", "neutronclient", "(", "request", ")", ".", "update_rbac_policy", "(", "policy_id", ",...
Update a RBAC Policy. :param request: request context :param policy_id: target policy id :param target_tenant: target tenant of the policy :return: RBACPolicy object
[ "Update", "a", "RBAC", "Policy", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L2025-L2036
train
216,067
openstack/horizon
openstack_dashboard/api/neutron.py
rbac_policy_get
def rbac_policy_get(request, policy_id, **kwargs): """Get RBAC policy for a given policy id.""" policy = neutronclient(request).show_rbac_policy( policy_id, **kwargs).get('rbac_policy') return RBACPolicy(policy)
python
def rbac_policy_get(request, policy_id, **kwargs): """Get RBAC policy for a given policy id.""" policy = neutronclient(request).show_rbac_policy( policy_id, **kwargs).get('rbac_policy') return RBACPolicy(policy)
[ "def", "rbac_policy_get", "(", "request", ",", "policy_id", ",", "*", "*", "kwargs", ")", ":", "policy", "=", "neutronclient", "(", "request", ")", ".", "show_rbac_policy", "(", "policy_id", ",", "*", "*", "kwargs", ")", ".", "get", "(", "'rbac_policy'", ...
Get RBAC policy for a given policy id.
[ "Get", "RBAC", "policy", "for", "a", "given", "policy", "id", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L2040-L2044
train
216,068
openstack/horizon
openstack_dashboard/api/neutron.py
SecurityGroupManager.list
def list(self, **params): """Fetches a list all security groups. :returns: List of SecurityGroup objects """ # This is to ensure tenant_id key is not populated # if tenant_id=None is specified. tenant_id = params.pop('tenant_id', self.request.user.tenant_id) if tenant_id: params['tenant_id'] = tenant_id return self._list(**params)
python
def list(self, **params): """Fetches a list all security groups. :returns: List of SecurityGroup objects """ # This is to ensure tenant_id key is not populated # if tenant_id=None is specified. tenant_id = params.pop('tenant_id', self.request.user.tenant_id) if tenant_id: params['tenant_id'] = tenant_id return self._list(**params)
[ "def", "list", "(", "self", ",", "*", "*", "params", ")", ":", "# This is to ensure tenant_id key is not populated", "# if tenant_id=None is specified.", "tenant_id", "=", "params", ".", "pop", "(", "'tenant_id'", ",", "self", ".", "request", ".", "user", ".", "te...
Fetches a list all security groups. :returns: List of SecurityGroup objects
[ "Fetches", "a", "list", "all", "security", "groups", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L361-L371
train
216,069
openstack/horizon
openstack_dashboard/api/neutron.py
SecurityGroupManager._sg_name_dict
def _sg_name_dict(self, sg_id, rules): """Create a mapping dict from secgroup id to its name.""" related_ids = set([sg_id]) related_ids |= set(filter(None, [r['remote_group_id'] for r in rules])) related_sgs = self.client.list_security_groups(id=related_ids, fields=['id', 'name']) related_sgs = related_sgs.get('security_groups') return dict((sg['id'], sg['name']) for sg in related_sgs)
python
def _sg_name_dict(self, sg_id, rules): """Create a mapping dict from secgroup id to its name.""" related_ids = set([sg_id]) related_ids |= set(filter(None, [r['remote_group_id'] for r in rules])) related_sgs = self.client.list_security_groups(id=related_ids, fields=['id', 'name']) related_sgs = related_sgs.get('security_groups') return dict((sg['id'], sg['name']) for sg in related_sgs)
[ "def", "_sg_name_dict", "(", "self", ",", "sg_id", ",", "rules", ")", ":", "related_ids", "=", "set", "(", "[", "sg_id", "]", ")", "related_ids", "|=", "set", "(", "filter", "(", "None", ",", "[", "r", "[", "'remote_group_id'", "]", "for", "r", "in",...
Create a mapping dict from secgroup id to its name.
[ "Create", "a", "mapping", "dict", "from", "secgroup", "id", "to", "its", "name", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L373-L380
train
216,070
openstack/horizon
openstack_dashboard/api/neutron.py
SecurityGroupManager.get
def get(self, sg_id): """Fetches the security group. :returns: SecurityGroup object corresponding to sg_id """ secgroup = self.client.show_security_group(sg_id).get('security_group') sg_dict = self._sg_name_dict(sg_id, secgroup['security_group_rules']) return SecurityGroup(secgroup, sg_dict)
python
def get(self, sg_id): """Fetches the security group. :returns: SecurityGroup object corresponding to sg_id """ secgroup = self.client.show_security_group(sg_id).get('security_group') sg_dict = self._sg_name_dict(sg_id, secgroup['security_group_rules']) return SecurityGroup(secgroup, sg_dict)
[ "def", "get", "(", "self", ",", "sg_id", ")", ":", "secgroup", "=", "self", ".", "client", ".", "show_security_group", "(", "sg_id", ")", ".", "get", "(", "'security_group'", ")", "sg_dict", "=", "self", ".", "_sg_name_dict", "(", "sg_id", ",", "secgroup...
Fetches the security group. :returns: SecurityGroup object corresponding to sg_id
[ "Fetches", "the", "security", "group", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L383-L390
train
216,071
openstack/horizon
openstack_dashboard/api/neutron.py
SecurityGroupManager.rule_create
def rule_create(self, parent_group_id, direction=None, ethertype=None, ip_protocol=None, from_port=None, to_port=None, cidr=None, group_id=None, description=None): """Create a new security group rule. :param parent_group_id: security group id a rule is created to :param direction: ``ingress`` or ``egress`` :param ethertype: ``IPv4`` or ``IPv6`` :param ip_protocol: tcp, udp, icmp :param from_port: L4 port range min :param to_port: L4 port range max :param cidr: Remote IP CIDR :param group_id: ID of Source Security Group :returns: SecurityGroupRule object """ if not cidr: cidr = None if isinstance(from_port, int) and from_port < 0: from_port = None if isinstance(to_port, int) and to_port < 0: to_port = None if isinstance(ip_protocol, int) and ip_protocol < 0: ip_protocol = None params = {'security_group_id': parent_group_id, 'direction': direction, 'ethertype': ethertype, 'protocol': ip_protocol, 'port_range_min': from_port, 'port_range_max': to_port, 'remote_ip_prefix': cidr, 'remote_group_id': group_id} if description is not None: params['description'] = description body = {'security_group_rule': params} try: rule = self.client.create_security_group_rule(body) except neutron_exc.OverQuotaClient: raise exceptions.Conflict( _('Security group rule quota exceeded.')) except neutron_exc.Conflict: raise exceptions.Conflict( _('Security group rule already exists.')) rule = rule.get('security_group_rule') sg_dict = self._sg_name_dict(parent_group_id, [rule]) return SecurityGroupRule(rule, sg_dict)
python
def rule_create(self, parent_group_id, direction=None, ethertype=None, ip_protocol=None, from_port=None, to_port=None, cidr=None, group_id=None, description=None): """Create a new security group rule. :param parent_group_id: security group id a rule is created to :param direction: ``ingress`` or ``egress`` :param ethertype: ``IPv4`` or ``IPv6`` :param ip_protocol: tcp, udp, icmp :param from_port: L4 port range min :param to_port: L4 port range max :param cidr: Remote IP CIDR :param group_id: ID of Source Security Group :returns: SecurityGroupRule object """ if not cidr: cidr = None if isinstance(from_port, int) and from_port < 0: from_port = None if isinstance(to_port, int) and to_port < 0: to_port = None if isinstance(ip_protocol, int) and ip_protocol < 0: ip_protocol = None params = {'security_group_id': parent_group_id, 'direction': direction, 'ethertype': ethertype, 'protocol': ip_protocol, 'port_range_min': from_port, 'port_range_max': to_port, 'remote_ip_prefix': cidr, 'remote_group_id': group_id} if description is not None: params['description'] = description body = {'security_group_rule': params} try: rule = self.client.create_security_group_rule(body) except neutron_exc.OverQuotaClient: raise exceptions.Conflict( _('Security group rule quota exceeded.')) except neutron_exc.Conflict: raise exceptions.Conflict( _('Security group rule already exists.')) rule = rule.get('security_group_rule') sg_dict = self._sg_name_dict(parent_group_id, [rule]) return SecurityGroupRule(rule, sg_dict)
[ "def", "rule_create", "(", "self", ",", "parent_group_id", ",", "direction", "=", "None", ",", "ethertype", "=", "None", ",", "ip_protocol", "=", "None", ",", "from_port", "=", "None", ",", "to_port", "=", "None", ",", "cidr", "=", "None", ",", "group_id...
Create a new security group rule. :param parent_group_id: security group id a rule is created to :param direction: ``ingress`` or ``egress`` :param ethertype: ``IPv4`` or ``IPv6`` :param ip_protocol: tcp, udp, icmp :param from_port: L4 port range min :param to_port: L4 port range max :param cidr: Remote IP CIDR :param group_id: ID of Source Security Group :returns: SecurityGroupRule object
[ "Create", "a", "new", "security", "group", "rule", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L417-L463
train
216,072
openstack/horizon
openstack_dashboard/api/neutron.py
SecurityGroupManager.list_by_instance
def list_by_instance(self, instance_id): """Gets security groups of an instance. :returns: List of SecurityGroup objects associated with the instance """ ports = port_list(self.request, device_id=instance_id) sg_ids = [] for p in ports: sg_ids += p.security_groups return self._list(id=set(sg_ids)) if sg_ids else []
python
def list_by_instance(self, instance_id): """Gets security groups of an instance. :returns: List of SecurityGroup objects associated with the instance """ ports = port_list(self.request, device_id=instance_id) sg_ids = [] for p in ports: sg_ids += p.security_groups return self._list(id=set(sg_ids)) if sg_ids else []
[ "def", "list_by_instance", "(", "self", ",", "instance_id", ")", ":", "ports", "=", "port_list", "(", "self", ".", "request", ",", "device_id", "=", "instance_id", ")", "sg_ids", "=", "[", "]", "for", "p", "in", "ports", ":", "sg_ids", "+=", "p", ".", ...
Gets security groups of an instance. :returns: List of SecurityGroup objects associated with the instance
[ "Gets", "security", "groups", "of", "an", "instance", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L471-L480
train
216,073
openstack/horizon
openstack_dashboard/api/neutron.py
SecurityGroupManager.update_instance_security_group
def update_instance_security_group(self, instance_id, new_security_group_ids): """Update security groups of a specified instance.""" ports = port_list(self.request, device_id=instance_id) for p in ports: params = {'security_groups': new_security_group_ids} port_update(self.request, p.id, **params)
python
def update_instance_security_group(self, instance_id, new_security_group_ids): """Update security groups of a specified instance.""" ports = port_list(self.request, device_id=instance_id) for p in ports: params = {'security_groups': new_security_group_ids} port_update(self.request, p.id, **params)
[ "def", "update_instance_security_group", "(", "self", ",", "instance_id", ",", "new_security_group_ids", ")", ":", "ports", "=", "port_list", "(", "self", ".", "request", ",", "device_id", "=", "instance_id", ")", "for", "p", "in", "ports", ":", "params", "=",...
Update security groups of a specified instance.
[ "Update", "security", "groups", "of", "a", "specified", "instance", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L483-L489
train
216,074
openstack/horizon
openstack_dashboard/api/neutron.py
FloatingIpManager.list_pools
def list_pools(self): """Fetches a list of all floating IP pools. :returns: List of FloatingIpPool objects """ search_opts = {'router:external': True} return [FloatingIpPool(pool) for pool in self.client.list_networks(**search_opts).get('networks')]
python
def list_pools(self): """Fetches a list of all floating IP pools. :returns: List of FloatingIpPool objects """ search_opts = {'router:external': True} return [FloatingIpPool(pool) for pool in self.client.list_networks(**search_opts).get('networks')]
[ "def", "list_pools", "(", "self", ")", ":", "search_opts", "=", "{", "'router:external'", ":", "True", "}", "return", "[", "FloatingIpPool", "(", "pool", ")", "for", "pool", "in", "self", ".", "client", ".", "list_networks", "(", "*", "*", "search_opts", ...
Fetches a list of all floating IP pools. :returns: List of FloatingIpPool objects
[ "Fetches", "a", "list", "of", "all", "floating", "IP", "pools", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L553-L560
train
216,075
openstack/horizon
openstack_dashboard/api/neutron.py
FloatingIpManager.list
def list(self, all_tenants=False, **search_opts): """Fetches a list of all floating IPs. :returns: List of FloatingIp object """ if not all_tenants: tenant_id = self.request.user.tenant_id # In Neutron, list_floatingips returns Floating IPs from # all tenants when the API is called with admin role, so # we need to filter them with tenant_id. search_opts['tenant_id'] = tenant_id port_search_opts = {'tenant_id': tenant_id} else: port_search_opts = {} fips = self.client.list_floatingips(**search_opts) fips = fips.get('floatingips') # Get port list to add instance_id to floating IP list # instance_id is stored in device_id attribute ports = port_list(self.request, **port_search_opts) port_dict = collections.OrderedDict([(p['id'], p) for p in ports]) for fip in fips: self._set_instance_info(fip, port_dict.get(fip['port_id'])) return [FloatingIp(fip) for fip in fips]
python
def list(self, all_tenants=False, **search_opts): """Fetches a list of all floating IPs. :returns: List of FloatingIp object """ if not all_tenants: tenant_id = self.request.user.tenant_id # In Neutron, list_floatingips returns Floating IPs from # all tenants when the API is called with admin role, so # we need to filter them with tenant_id. search_opts['tenant_id'] = tenant_id port_search_opts = {'tenant_id': tenant_id} else: port_search_opts = {} fips = self.client.list_floatingips(**search_opts) fips = fips.get('floatingips') # Get port list to add instance_id to floating IP list # instance_id is stored in device_id attribute ports = port_list(self.request, **port_search_opts) port_dict = collections.OrderedDict([(p['id'], p) for p in ports]) for fip in fips: self._set_instance_info(fip, port_dict.get(fip['port_id'])) return [FloatingIp(fip) for fip in fips]
[ "def", "list", "(", "self", ",", "all_tenants", "=", "False", ",", "*", "*", "search_opts", ")", ":", "if", "not", "all_tenants", ":", "tenant_id", "=", "self", ".", "request", ".", "user", ".", "tenant_id", "# In Neutron, list_floatingips returns Floating IPs f...
Fetches a list of all floating IPs. :returns: List of FloatingIp object
[ "Fetches", "a", "list", "of", "all", "floating", "IPs", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L580-L602
train
216,076
openstack/horizon
openstack_dashboard/api/neutron.py
FloatingIpManager.get
def get(self, floating_ip_id): """Fetches the floating IP. :returns: FloatingIp object corresponding to floating_ip_id """ fip = self.client.show_floatingip(floating_ip_id).get('floatingip') self._set_instance_info(fip) return FloatingIp(fip)
python
def get(self, floating_ip_id): """Fetches the floating IP. :returns: FloatingIp object corresponding to floating_ip_id """ fip = self.client.show_floatingip(floating_ip_id).get('floatingip') self._set_instance_info(fip) return FloatingIp(fip)
[ "def", "get", "(", "self", ",", "floating_ip_id", ")", ":", "fip", "=", "self", ".", "client", ".", "show_floatingip", "(", "floating_ip_id", ")", ".", "get", "(", "'floatingip'", ")", "self", ".", "_set_instance_info", "(", "fip", ")", "return", "Floating...
Fetches the floating IP. :returns: FloatingIp object corresponding to floating_ip_id
[ "Fetches", "the", "floating", "IP", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L605-L612
train
216,077
openstack/horizon
openstack_dashboard/api/neutron.py
FloatingIpManager.allocate
def allocate(self, pool, tenant_id=None, **params): """Allocates a floating IP to the tenant. You must provide a pool name or id for which you would like to allocate a floating IP. :returns: FloatingIp object corresponding to an allocated floating IP """ if not tenant_id: tenant_id = self.request.user.project_id create_dict = {'floating_network_id': pool, 'tenant_id': tenant_id} if 'subnet_id' in params: create_dict['subnet_id'] = params['subnet_id'] if 'floating_ip_address' in params: create_dict['floating_ip_address'] = params['floating_ip_address'] if 'description' in params: create_dict['description'] = params['description'] if 'dns_domain' in params: create_dict['dns_domain'] = params['dns_domain'] if 'dns_name' in params: create_dict['dns_name'] = params['dns_name'] fip = self.client.create_floatingip( {'floatingip': create_dict}).get('floatingip') self._set_instance_info(fip) return FloatingIp(fip)
python
def allocate(self, pool, tenant_id=None, **params): """Allocates a floating IP to the tenant. You must provide a pool name or id for which you would like to allocate a floating IP. :returns: FloatingIp object corresponding to an allocated floating IP """ if not tenant_id: tenant_id = self.request.user.project_id create_dict = {'floating_network_id': pool, 'tenant_id': tenant_id} if 'subnet_id' in params: create_dict['subnet_id'] = params['subnet_id'] if 'floating_ip_address' in params: create_dict['floating_ip_address'] = params['floating_ip_address'] if 'description' in params: create_dict['description'] = params['description'] if 'dns_domain' in params: create_dict['dns_domain'] = params['dns_domain'] if 'dns_name' in params: create_dict['dns_name'] = params['dns_name'] fip = self.client.create_floatingip( {'floatingip': create_dict}).get('floatingip') self._set_instance_info(fip) return FloatingIp(fip)
[ "def", "allocate", "(", "self", ",", "pool", ",", "tenant_id", "=", "None", ",", "*", "*", "params", ")", ":", "if", "not", "tenant_id", ":", "tenant_id", "=", "self", ".", "request", ".", "user", ".", "project_id", "create_dict", "=", "{", "'floating_...
Allocates a floating IP to the tenant. You must provide a pool name or id for which you would like to allocate a floating IP. :returns: FloatingIp object corresponding to an allocated floating IP
[ "Allocates", "a", "floating", "IP", "to", "the", "tenant", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L615-L640
train
216,078
openstack/horizon
openstack_dashboard/api/neutron.py
FloatingIpManager.associate
def associate(self, floating_ip_id, port_id): """Associates the floating IP to the port. ``port_id`` represents a VNIC of an instance. ``port_id`` argument is different from a normal neutron port ID. A value passed as ``port_id`` must be one of target_id returned by ``list_targets``, ``get_target_by_instance`` or ``list_targets_by_instance`` method. """ # NOTE: In Neutron Horizon floating IP support, port_id is # "<port_id>_<ip_address>" format to identify multiple ports. pid, ip_address = port_id.split('_', 1) update_dict = {'port_id': pid, 'fixed_ip_address': ip_address} self.client.update_floatingip(floating_ip_id, {'floatingip': update_dict})
python
def associate(self, floating_ip_id, port_id): """Associates the floating IP to the port. ``port_id`` represents a VNIC of an instance. ``port_id`` argument is different from a normal neutron port ID. A value passed as ``port_id`` must be one of target_id returned by ``list_targets``, ``get_target_by_instance`` or ``list_targets_by_instance`` method. """ # NOTE: In Neutron Horizon floating IP support, port_id is # "<port_id>_<ip_address>" format to identify multiple ports. pid, ip_address = port_id.split('_', 1) update_dict = {'port_id': pid, 'fixed_ip_address': ip_address} self.client.update_floatingip(floating_ip_id, {'floatingip': update_dict})
[ "def", "associate", "(", "self", ",", "floating_ip_id", ",", "port_id", ")", ":", "# NOTE: In Neutron Horizon floating IP support, port_id is", "# \"<port_id>_<ip_address>\" format to identify multiple ports.", "pid", ",", "ip_address", "=", "port_id", ".", "split", "(", "'_'...
Associates the floating IP to the port. ``port_id`` represents a VNIC of an instance. ``port_id`` argument is different from a normal neutron port ID. A value passed as ``port_id`` must be one of target_id returned by ``list_targets``, ``get_target_by_instance`` or ``list_targets_by_instance`` method.
[ "Associates", "the", "floating", "IP", "to", "the", "port", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L648-L663
train
216,079
openstack/horizon
openstack_dashboard/api/neutron.py
FloatingIpManager.list_targets
def list_targets(self): """Returns a list of association targets of instance VIFs. Each association target is represented as FloatingIpTarget object. FloatingIpTarget is a APIResourceWrapper/APIDictWrapper and 'id' and 'name' attributes must be defined in each object. FloatingIpTarget.id can be passed as port_id in associate(). FloatingIpTarget.name is displayed in Floating Ip Association Form. """ tenant_id = self.request.user.tenant_id ports = port_list(self.request, tenant_id=tenant_id) servers, has_more = nova.server_list(self.request, detailed=False) server_dict = collections.OrderedDict( [(s.id, s.name) for s in servers]) reachable_subnets = self._get_reachable_subnets(ports) targets = [] for p in ports: # Remove network ports from Floating IP targets if p.device_owner.startswith('network:'): continue server_name = server_dict.get(p.device_id) for ip in p.fixed_ips: if ip['subnet_id'] not in reachable_subnets: continue # Floating IPs can only target IPv4 addresses. if netaddr.IPAddress(ip['ip_address']).version != 4: continue targets.append(FloatingIpTarget(p, ip['ip_address'], server_name)) return targets
python
def list_targets(self): """Returns a list of association targets of instance VIFs. Each association target is represented as FloatingIpTarget object. FloatingIpTarget is a APIResourceWrapper/APIDictWrapper and 'id' and 'name' attributes must be defined in each object. FloatingIpTarget.id can be passed as port_id in associate(). FloatingIpTarget.name is displayed in Floating Ip Association Form. """ tenant_id = self.request.user.tenant_id ports = port_list(self.request, tenant_id=tenant_id) servers, has_more = nova.server_list(self.request, detailed=False) server_dict = collections.OrderedDict( [(s.id, s.name) for s in servers]) reachable_subnets = self._get_reachable_subnets(ports) targets = [] for p in ports: # Remove network ports from Floating IP targets if p.device_owner.startswith('network:'): continue server_name = server_dict.get(p.device_id) for ip in p.fixed_ips: if ip['subnet_id'] not in reachable_subnets: continue # Floating IPs can only target IPv4 addresses. if netaddr.IPAddress(ip['ip_address']).version != 4: continue targets.append(FloatingIpTarget(p, ip['ip_address'], server_name)) return targets
[ "def", "list_targets", "(", "self", ")", ":", "tenant_id", "=", "self", ".", "request", ".", "user", ".", "tenant_id", "ports", "=", "port_list", "(", "self", ".", "request", ",", "tenant_id", "=", "tenant_id", ")", "servers", ",", "has_more", "=", "nova...
Returns a list of association targets of instance VIFs. Each association target is represented as FloatingIpTarget object. FloatingIpTarget is a APIResourceWrapper/APIDictWrapper and 'id' and 'name' attributes must be defined in each object. FloatingIpTarget.id can be passed as port_id in associate(). FloatingIpTarget.name is displayed in Floating Ip Association Form.
[ "Returns", "a", "list", "of", "association", "targets", "of", "instance", "VIFs", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L700-L731
train
216,080
openstack/horizon
openstack_dashboard/api/neutron.py
FloatingIpManager.list_targets_by_instance
def list_targets_by_instance(self, instance_id, target_list=None): """Returns a list of FloatingIpTarget objects of FIP association. :param instance_id: ID of target VM instance :param target_list: (optional) a list returned by list_targets(). If specified, looking up is done against the specified list to save extra API calls to a back-end. Otherwise target list is retrieved from a back-end inside the method. """ if target_list is not None: # We assume that target_list was returned by list_targets() # so we can assume checks for subnet reachability and IP version # have been done already. We skip all checks here. return [target for target in target_list if target['instance_id'] == instance_id] else: ports = self._target_ports_by_instance(instance_id) reachable_subnets = self._get_reachable_subnets( ports, fetch_router_ports=True) name = self._get_server_name(instance_id) targets = [] for p in ports: for ip in p.fixed_ips: if ip['subnet_id'] not in reachable_subnets: continue # Floating IPs can only target IPv4 addresses. if netaddr.IPAddress(ip['ip_address']).version != 4: continue targets.append(FloatingIpTarget(p, ip['ip_address'], name)) return targets
python
def list_targets_by_instance(self, instance_id, target_list=None): """Returns a list of FloatingIpTarget objects of FIP association. :param instance_id: ID of target VM instance :param target_list: (optional) a list returned by list_targets(). If specified, looking up is done against the specified list to save extra API calls to a back-end. Otherwise target list is retrieved from a back-end inside the method. """ if target_list is not None: # We assume that target_list was returned by list_targets() # so we can assume checks for subnet reachability and IP version # have been done already. We skip all checks here. return [target for target in target_list if target['instance_id'] == instance_id] else: ports = self._target_ports_by_instance(instance_id) reachable_subnets = self._get_reachable_subnets( ports, fetch_router_ports=True) name = self._get_server_name(instance_id) targets = [] for p in ports: for ip in p.fixed_ips: if ip['subnet_id'] not in reachable_subnets: continue # Floating IPs can only target IPv4 addresses. if netaddr.IPAddress(ip['ip_address']).version != 4: continue targets.append(FloatingIpTarget(p, ip['ip_address'], name)) return targets
[ "def", "list_targets_by_instance", "(", "self", ",", "instance_id", ",", "target_list", "=", "None", ")", ":", "if", "target_list", "is", "not", "None", ":", "# We assume that target_list was returned by list_targets()", "# so we can assume checks for subnet reachability and IP...
Returns a list of FloatingIpTarget objects of FIP association. :param instance_id: ID of target VM instance :param target_list: (optional) a list returned by list_targets(). If specified, looking up is done against the specified list to save extra API calls to a back-end. Otherwise target list is retrieved from a back-end inside the method.
[ "Returns", "a", "list", "of", "FloatingIpTarget", "objects", "of", "FIP", "association", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L740-L769
train
216,081
openstack/horizon
horizon/decorators.py
require_perms
def require_perms(view_func, required): """Enforces permission-based access controls. :param list required: A tuple of permission names, all of which the request user must possess in order access the decorated view. Example usage:: from horizon.decorators import require_perms @require_perms(['foo.admin', 'foo.member']) def my_view(request): ... Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the requirements are not met. """ from horizon.exceptions import NotAuthorized # We only need to check each permission once for a view, so we'll use a set current_perms = getattr(view_func, '_required_perms', set([])) view_func._required_perms = current_perms | set(required) @functools.wraps(view_func, assigned=available_attrs(view_func)) def dec(request, *args, **kwargs): if request.user.is_authenticated: if request.user.has_perms(view_func._required_perms): return view_func(request, *args, **kwargs) raise NotAuthorized(_("You are not authorized to access %s") % request.path) # If we don't have any permissions, just return the original view. if required: return dec else: return view_func
python
def require_perms(view_func, required): """Enforces permission-based access controls. :param list required: A tuple of permission names, all of which the request user must possess in order access the decorated view. Example usage:: from horizon.decorators import require_perms @require_perms(['foo.admin', 'foo.member']) def my_view(request): ... Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the requirements are not met. """ from horizon.exceptions import NotAuthorized # We only need to check each permission once for a view, so we'll use a set current_perms = getattr(view_func, '_required_perms', set([])) view_func._required_perms = current_perms | set(required) @functools.wraps(view_func, assigned=available_attrs(view_func)) def dec(request, *args, **kwargs): if request.user.is_authenticated: if request.user.has_perms(view_func._required_perms): return view_func(request, *args, **kwargs) raise NotAuthorized(_("You are not authorized to access %s") % request.path) # If we don't have any permissions, just return the original view. if required: return dec else: return view_func
[ "def", "require_perms", "(", "view_func", ",", "required", ")", ":", "from", "horizon", ".", "exceptions", "import", "NotAuthorized", "# We only need to check each permission once for a view, so we'll use a set", "current_perms", "=", "getattr", "(", "view_func", ",", "'_re...
Enforces permission-based access controls. :param list required: A tuple of permission names, all of which the request user must possess in order access the decorated view. Example usage:: from horizon.decorators import require_perms @require_perms(['foo.admin', 'foo.member']) def my_view(request): ... Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the requirements are not met.
[ "Enforces", "permission", "-", "based", "access", "controls", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/decorators.py#L57-L92
train
216,082
openstack/horizon
horizon/decorators.py
require_component_access
def require_component_access(view_func, component): """Perform component can_access check to access the view. :param component containing the view (panel or dashboard). Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the user cannot access the component containing the view. By example the check of component policy rules will be applied to its views. """ from horizon.exceptions import NotAuthorized @functools.wraps(view_func, assigned=available_attrs(view_func)) def dec(request, *args, **kwargs): if not component.can_access({'request': request}): raise NotAuthorized(_("You are not authorized to access %s") % request.path) return view_func(request, *args, **kwargs) return dec
python
def require_component_access(view_func, component): """Perform component can_access check to access the view. :param component containing the view (panel or dashboard). Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the user cannot access the component containing the view. By example the check of component policy rules will be applied to its views. """ from horizon.exceptions import NotAuthorized @functools.wraps(view_func, assigned=available_attrs(view_func)) def dec(request, *args, **kwargs): if not component.can_access({'request': request}): raise NotAuthorized(_("You are not authorized to access %s") % request.path) return view_func(request, *args, **kwargs) return dec
[ "def", "require_component_access", "(", "view_func", ",", "component", ")", ":", "from", "horizon", ".", "exceptions", "import", "NotAuthorized", "@", "functools", ".", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")...
Perform component can_access check to access the view. :param component containing the view (panel or dashboard). Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the user cannot access the component containing the view. By example the check of component policy rules will be applied to its views.
[ "Perform", "component", "can_access", "check", "to", "access", "the", "view", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/decorators.py#L95-L115
train
216,083
openstack/horizon
openstack_dashboard/api/glance.py
image_get
def image_get(request, image_id): """Returns an Image object populated with metadata for a given image.""" image = glanceclient(request).images.get(image_id) return Image(image)
python
def image_get(request, image_id): """Returns an Image object populated with metadata for a given image.""" image = glanceclient(request).images.get(image_id) return Image(image)
[ "def", "image_get", "(", "request", ",", "image_id", ")", ":", "image", "=", "glanceclient", "(", "request", ")", ".", "images", ".", "get", "(", "image_id", ")", "return", "Image", "(", "image", ")" ]
Returns an Image object populated with metadata for a given image.
[ "Returns", "an", "Image", "object", "populated", "with", "metadata", "for", "a", "given", "image", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L263-L266
train
216,084
openstack/horizon
openstack_dashboard/api/glance.py
image_list_detailed
def image_list_detailed(request, marker=None, sort_dir='desc', sort_key='created_at', filters=None, paginate=False, reversed_order=False, **kwargs): """Thin layer above glanceclient, for handling pagination issues. It provides iterating both forward and backward on top of ascetic OpenStack pagination API - which natively supports only iterating forward through the entries. Thus in order to retrieve list of objects at previous page, a request with the reverse entries order had to be made to Glance, using the first object id on current page as the marker - restoring the original items ordering before sending them back to the UI. :param request: The request object coming from browser to be passed further into Glance service. :param marker: The id of an object which defines a starting point of a query sent to Glance service. :param sort_dir: The direction by which the resulting image list throughout all pages (if pagination is enabled) will be sorted. Could be either 'asc' (ascending) or 'desc' (descending), defaults to 'desc'. :param sort_key: The name of key by by which the resulting image list throughout all pages (if pagination is enabled) will be sorted. Defaults to 'created_at'. :param filters: A dictionary of filters passed as is to Glance service. :param paginate: Whether the pagination is enabled. If it is, then the number of entries on a single page of images table is limited to the specific number stored in browser cookies. :param reversed_order: Set this flag to True when it's necessary to get a reversed list of images from Glance (used for navigating the images list back in UI). """ limit = getattr(settings, 'API_RESULT_LIMIT', 1000) page_size = utils.get_page_size(request) if paginate: request_size = page_size + 1 else: request_size = limit _normalize_list_input(filters, **kwargs) kwargs = {'filters': filters or {}} if marker: kwargs['marker'] = marker kwargs['sort_key'] = sort_key if not reversed_order: kwargs['sort_dir'] = sort_dir else: kwargs['sort_dir'] = 'desc' if sort_dir == 'asc' else 'asc' images_iter = glanceclient(request).images.list(page_size=request_size, limit=limit, **kwargs) has_prev_data = False has_more_data = False if paginate: images = list(itertools.islice(images_iter, request_size)) # first and middle page condition if len(images) > page_size: images.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: images = sorted(images, key=lambda image: (getattr(image, sort_key) or '').lower(), reverse=(sort_dir == 'desc')) else: images = list(images_iter) # TODO(jpichon): Do it better wrapped_images = [] for image in images: wrapped_images.append(Image(image)) return wrapped_images, has_more_data, has_prev_data
python
def image_list_detailed(request, marker=None, sort_dir='desc', sort_key='created_at', filters=None, paginate=False, reversed_order=False, **kwargs): """Thin layer above glanceclient, for handling pagination issues. It provides iterating both forward and backward on top of ascetic OpenStack pagination API - which natively supports only iterating forward through the entries. Thus in order to retrieve list of objects at previous page, a request with the reverse entries order had to be made to Glance, using the first object id on current page as the marker - restoring the original items ordering before sending them back to the UI. :param request: The request object coming from browser to be passed further into Glance service. :param marker: The id of an object which defines a starting point of a query sent to Glance service. :param sort_dir: The direction by which the resulting image list throughout all pages (if pagination is enabled) will be sorted. Could be either 'asc' (ascending) or 'desc' (descending), defaults to 'desc'. :param sort_key: The name of key by by which the resulting image list throughout all pages (if pagination is enabled) will be sorted. Defaults to 'created_at'. :param filters: A dictionary of filters passed as is to Glance service. :param paginate: Whether the pagination is enabled. If it is, then the number of entries on a single page of images table is limited to the specific number stored in browser cookies. :param reversed_order: Set this flag to True when it's necessary to get a reversed list of images from Glance (used for navigating the images list back in UI). """ limit = getattr(settings, 'API_RESULT_LIMIT', 1000) page_size = utils.get_page_size(request) if paginate: request_size = page_size + 1 else: request_size = limit _normalize_list_input(filters, **kwargs) kwargs = {'filters': filters or {}} if marker: kwargs['marker'] = marker kwargs['sort_key'] = sort_key if not reversed_order: kwargs['sort_dir'] = sort_dir else: kwargs['sort_dir'] = 'desc' if sort_dir == 'asc' else 'asc' images_iter = glanceclient(request).images.list(page_size=request_size, limit=limit, **kwargs) has_prev_data = False has_more_data = False if paginate: images = list(itertools.islice(images_iter, request_size)) # first and middle page condition if len(images) > page_size: images.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: images = sorted(images, key=lambda image: (getattr(image, sort_key) or '').lower(), reverse=(sort_dir == 'desc')) else: images = list(images_iter) # TODO(jpichon): Do it better wrapped_images = [] for image in images: wrapped_images.append(Image(image)) return wrapped_images, has_more_data, has_prev_data
[ "def", "image_list_detailed", "(", "request", ",", "marker", "=", "None", ",", "sort_dir", "=", "'desc'", ",", "sort_key", "=", "'created_at'", ",", "filters", "=", "None", ",", "paginate", "=", "False", ",", "reversed_order", "=", "False", ",", "*", "*", ...
Thin layer above glanceclient, for handling pagination issues. It provides iterating both forward and backward on top of ascetic OpenStack pagination API - which natively supports only iterating forward through the entries. Thus in order to retrieve list of objects at previous page, a request with the reverse entries order had to be made to Glance, using the first object id on current page as the marker - restoring the original items ordering before sending them back to the UI. :param request: The request object coming from browser to be passed further into Glance service. :param marker: The id of an object which defines a starting point of a query sent to Glance service. :param sort_dir: The direction by which the resulting image list throughout all pages (if pagination is enabled) will be sorted. Could be either 'asc' (ascending) or 'desc' (descending), defaults to 'desc'. :param sort_key: The name of key by by which the resulting image list throughout all pages (if pagination is enabled) will be sorted. Defaults to 'created_at'. :param filters: A dictionary of filters passed as is to Glance service. :param paginate: Whether the pagination is enabled. If it is, then the number of entries on a single page of images table is limited to the specific number stored in browser cookies. :param reversed_order: Set this flag to True when it's necessary to get a reversed list of images from Glance (used for navigating the images list back in UI).
[ "Thin", "layer", "above", "glanceclient", "for", "handling", "pagination", "issues", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L283-L386
train
216,085
openstack/horizon
openstack_dashboard/api/glance.py
create_image_metadata
def create_image_metadata(data): """Generate metadata dict for a new image from a given form data.""" # Default metadata meta = {'protected': data.get('protected', False), 'disk_format': data.get('disk_format', 'raw'), 'container_format': data.get('container_format', 'bare'), 'min_disk': data.get('min_disk') or 0, 'min_ram': data.get('min_ram') or 0, 'name': data.get('name', '')} # Glance does not really do anything with container_format at the # moment. It requires it is set to the same disk_format for the three # Amazon image types, otherwise it just treats them as 'bare.' As such # we will just set that to be that here instead of bothering the user # with asking them for information we can already determine. if meta['disk_format'] in ('ami', 'aki', 'ari',): meta['container_format'] = meta['disk_format'] elif meta['disk_format'] == 'docker': # To support docker containers we allow the user to specify # 'docker' as the format. In that case we really want to use # 'raw' as the disk format and 'docker' as the container format. meta['disk_format'] = 'raw' meta['container_format'] = 'docker' elif meta['disk_format'] == 'ova': # If the user wishes to upload an OVA using Horizon, then # 'ova' must be the container format and 'vmdk' must be the disk # format. meta['container_format'] = 'ova' meta['disk_format'] = 'vmdk' properties = {} for prop, key in [('description', 'description'), ('kernel_id', 'kernel'), ('ramdisk_id', 'ramdisk'), ('architecture', 'architecture')]: if data.get(key): properties[prop] = data[key] _handle_unknown_properties(data, properties) if ('visibility' in data and data['visibility'] not in ['public', 'private', 'community', 'shared']): raise KeyError('invalid visibility option: %s' % data['visibility']) _normalize_is_public_filter(data) if VERSIONS.active < 2: meta['properties'] = properties meta['is_public'] = data.get('is_public', False) else: meta['visibility'] = data.get('visibility', 'private') meta.update(properties) return meta
python
def create_image_metadata(data): """Generate metadata dict for a new image from a given form data.""" # Default metadata meta = {'protected': data.get('protected', False), 'disk_format': data.get('disk_format', 'raw'), 'container_format': data.get('container_format', 'bare'), 'min_disk': data.get('min_disk') or 0, 'min_ram': data.get('min_ram') or 0, 'name': data.get('name', '')} # Glance does not really do anything with container_format at the # moment. It requires it is set to the same disk_format for the three # Amazon image types, otherwise it just treats them as 'bare.' As such # we will just set that to be that here instead of bothering the user # with asking them for information we can already determine. if meta['disk_format'] in ('ami', 'aki', 'ari',): meta['container_format'] = meta['disk_format'] elif meta['disk_format'] == 'docker': # To support docker containers we allow the user to specify # 'docker' as the format. In that case we really want to use # 'raw' as the disk format and 'docker' as the container format. meta['disk_format'] = 'raw' meta['container_format'] = 'docker' elif meta['disk_format'] == 'ova': # If the user wishes to upload an OVA using Horizon, then # 'ova' must be the container format and 'vmdk' must be the disk # format. meta['container_format'] = 'ova' meta['disk_format'] = 'vmdk' properties = {} for prop, key in [('description', 'description'), ('kernel_id', 'kernel'), ('ramdisk_id', 'ramdisk'), ('architecture', 'architecture')]: if data.get(key): properties[prop] = data[key] _handle_unknown_properties(data, properties) if ('visibility' in data and data['visibility'] not in ['public', 'private', 'community', 'shared']): raise KeyError('invalid visibility option: %s' % data['visibility']) _normalize_is_public_filter(data) if VERSIONS.active < 2: meta['properties'] = properties meta['is_public'] = data.get('is_public', False) else: meta['visibility'] = data.get('visibility', 'private') meta.update(properties) return meta
[ "def", "create_image_metadata", "(", "data", ")", ":", "# Default metadata", "meta", "=", "{", "'protected'", ":", "data", ".", "get", "(", "'protected'", ",", "False", ")", ",", "'disk_format'", ":", "data", ".", "get", "(", "'disk_format'", ",", "'raw'", ...
Generate metadata dict for a new image from a given form data.
[ "Generate", "metadata", "dict", "for", "a", "new", "image", "from", "a", "given", "form", "data", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L451-L506
train
216,086
openstack/horizon
openstack_dashboard/api/glance.py
image_create
def image_create(request, **kwargs): """Create image. :param kwargs: * copy_from: URL from which Glance server should immediately copy the data and store it in its configured image store. * data: Form data posted from client. * location: URL where the data for this image already resides. In the case of 'copy_from' and 'location', the Glance server will give us a immediate response from create and handle the data asynchronously. In the case of 'data' the process of uploading the data may take some time and is handed off to a separate thread. """ data = kwargs.pop('data', None) location = None if VERSIONS.active >= 2: location = kwargs.pop('location', None) image = glanceclient(request).images.create(**kwargs) if location is not None: glanceclient(request).images.add_location(image.id, location, {}) if data: if isinstance(data, six.string_types): # The image data is meant to be uploaded externally, return a # special wrapper to bypass the web server in a subsequent upload return ExternallyUploadedImage(image, request) elif isinstance(data, TemporaryUploadedFile): # Hack to fool Django, so we can keep file open in the new thread. if six.PY2: data.file.close_called = True else: data.file._closer.close_called = True elif isinstance(data, InMemoryUploadedFile): # Clone a new file for InMemeoryUploadedFile. # Because the old one will be closed by Django. data = SimpleUploadedFile(data.name, data.read(), data.content_type) if VERSIONS.active < 2: thread.start_new_thread(image_update, (request, image.id), {'data': data}) else: def upload(): try: return glanceclient(request).images.upload(image.id, data) finally: filename = str(data.file.name) try: os.remove(filename) except OSError as e: LOG.warning('Failed to remove temporary image file ' '%(file)s (%(e)s)', {'file': filename, 'e': e}) thread.start_new_thread(upload, ()) return Image(image)
python
def image_create(request, **kwargs): """Create image. :param kwargs: * copy_from: URL from which Glance server should immediately copy the data and store it in its configured image store. * data: Form data posted from client. * location: URL where the data for this image already resides. In the case of 'copy_from' and 'location', the Glance server will give us a immediate response from create and handle the data asynchronously. In the case of 'data' the process of uploading the data may take some time and is handed off to a separate thread. """ data = kwargs.pop('data', None) location = None if VERSIONS.active >= 2: location = kwargs.pop('location', None) image = glanceclient(request).images.create(**kwargs) if location is not None: glanceclient(request).images.add_location(image.id, location, {}) if data: if isinstance(data, six.string_types): # The image data is meant to be uploaded externally, return a # special wrapper to bypass the web server in a subsequent upload return ExternallyUploadedImage(image, request) elif isinstance(data, TemporaryUploadedFile): # Hack to fool Django, so we can keep file open in the new thread. if six.PY2: data.file.close_called = True else: data.file._closer.close_called = True elif isinstance(data, InMemoryUploadedFile): # Clone a new file for InMemeoryUploadedFile. # Because the old one will be closed by Django. data = SimpleUploadedFile(data.name, data.read(), data.content_type) if VERSIONS.active < 2: thread.start_new_thread(image_update, (request, image.id), {'data': data}) else: def upload(): try: return glanceclient(request).images.upload(image.id, data) finally: filename = str(data.file.name) try: os.remove(filename) except OSError as e: LOG.warning('Failed to remove temporary image file ' '%(file)s (%(e)s)', {'file': filename, 'e': e}) thread.start_new_thread(upload, ()) return Image(image)
[ "def", "image_create", "(", "request", ",", "*", "*", "kwargs", ")", ":", "data", "=", "kwargs", ".", "pop", "(", "'data'", ",", "None", ")", "location", "=", "None", "if", "VERSIONS", ".", "active", ">=", "2", ":", "location", "=", "kwargs", ".", ...
Create image. :param kwargs: * copy_from: URL from which Glance server should immediately copy the data and store it in its configured image store. * data: Form data posted from client. * location: URL where the data for this image already resides. In the case of 'copy_from' and 'location', the Glance server will give us a immediate response from create and handle the data asynchronously. In the case of 'data' the process of uploading the data may take some time and is handed off to a separate thread.
[ "Create", "image", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L521-L581
train
216,087
openstack/horizon
openstack_dashboard/api/glance.py
image_update_properties
def image_update_properties(request, image_id, remove_props=None, **kwargs): """Add or update a custom property of an image.""" return glanceclient(request, '2').images.update(image_id, remove_props, **kwargs)
python
def image_update_properties(request, image_id, remove_props=None, **kwargs): """Add or update a custom property of an image.""" return glanceclient(request, '2').images.update(image_id, remove_props, **kwargs)
[ "def", "image_update_properties", "(", "request", ",", "image_id", ",", "remove_props", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "glanceclient", "(", "request", ",", "'2'", ")", ".", "images", ".", "update", "(", "image_id", ",", "remove_p...
Add or update a custom property of an image.
[ "Add", "or", "update", "a", "custom", "property", "of", "an", "image", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L585-L589
train
216,088
openstack/horizon
openstack_dashboard/api/glance.py
image_delete_properties
def image_delete_properties(request, image_id, keys): """Delete custom properties for an image.""" return glanceclient(request, '2').images.update(image_id, keys)
python
def image_delete_properties(request, image_id, keys): """Delete custom properties for an image.""" return glanceclient(request, '2').images.update(image_id, keys)
[ "def", "image_delete_properties", "(", "request", ",", "image_id", ",", "keys", ")", ":", "return", "glanceclient", "(", "request", ",", "'2'", ")", ".", "images", ".", "update", "(", "image_id", ",", "keys", ")" ]
Delete custom properties for an image.
[ "Delete", "custom", "properties", "for", "an", "image", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L593-L595
train
216,089
openstack/horizon
openstack_dashboard/api/glance.py
filter_properties_target
def filter_properties_target(namespaces_iter, resource_types, properties_target): """Filter metadata namespaces. Filtering is done based ongiven resource types and a properties target. :param namespaces_iter: Metadata namespaces iterable. :param resource_types: List of resource type names. :param properties_target: Name of the properties target. """ def filter_namespace(namespace): for asn in namespace.get('resource_type_associations'): if (asn.get('name') in resource_types and asn.get('properties_target') == properties_target): return True return False return filter(filter_namespace, namespaces_iter)
python
def filter_properties_target(namespaces_iter, resource_types, properties_target): """Filter metadata namespaces. Filtering is done based ongiven resource types and a properties target. :param namespaces_iter: Metadata namespaces iterable. :param resource_types: List of resource type names. :param properties_target: Name of the properties target. """ def filter_namespace(namespace): for asn in namespace.get('resource_type_associations'): if (asn.get('name') in resource_types and asn.get('properties_target') == properties_target): return True return False return filter(filter_namespace, namespaces_iter)
[ "def", "filter_properties_target", "(", "namespaces_iter", ",", "resource_types", ",", "properties_target", ")", ":", "def", "filter_namespace", "(", "namespace", ")", ":", "for", "asn", "in", "namespace", ".", "get", "(", "'resource_type_associations'", ")", ":", ...
Filter metadata namespaces. Filtering is done based ongiven resource types and a properties target. :param namespaces_iter: Metadata namespaces iterable. :param resource_types: List of resource type names. :param properties_target: Name of the properties target.
[ "Filter", "metadata", "namespaces", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L634-L651
train
216,090
openstack/horizon
openstack_dashboard/api/glance.py
metadefs_namespace_list
def metadefs_namespace_list(request, filters=None, sort_dir='asc', sort_key='namespace', marker=None, paginate=False): """Retrieve a listing of Namespaces :param paginate: If true will perform pagination based on settings. :param marker: Specifies the namespace of the last-seen namespace. The typical pattern of limit and marker is to make an initial limited request and then to use the last namespace from the response as the marker parameter in a subsequent limited request. With paginate, limit is automatically set. :param sort_dir: The sort direction ('asc' or 'desc'). :param sort_key: The field to sort on (for example, 'created_at'). Default is namespace. The way base namespaces are loaded into glance typically at first deployment is done in a single transaction giving them a potentially unpredictable sort result when using create_at. :param filters: specifies addition fields to filter on such as resource_types. :returns A tuple of three values: 1) Current page results 2) A boolean of whether or not there are previous page(s). 3) A boolean of whether or not there are more page(s). """ # Listing namespaces requires the v2 API. If not supported we return an # empty array so callers don't need to worry about version checking. if get_version() < 2: return [], False, False if filters is None: filters = {} limit = getattr(settings, 'API_RESULT_LIMIT', 1000) page_size = utils.get_page_size(request) if paginate: request_size = page_size + 1 else: request_size = limit kwargs = {'filters': filters} if marker: kwargs['marker'] = marker kwargs['sort_dir'] = sort_dir kwargs['sort_key'] = sort_key namespaces_iter = glanceclient(request, '2').metadefs_namespace.list( page_size=request_size, limit=limit, **kwargs) # Filter the namespaces based on the provided properties_target since this # is not supported by the metadata namespaces API. resource_types = filters.get('resource_types') properties_target = filters.get('properties_target') if resource_types and properties_target: namespaces_iter = filter_properties_target(namespaces_iter, resource_types, properties_target) has_prev_data = False has_more_data = False if paginate: namespaces = list(itertools.islice(namespaces_iter, request_size)) # first and middle page condition if len(namespaces) > page_size: namespaces.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif sort_dir == 'desc' and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True else: namespaces = list(namespaces_iter) namespaces = [Namespace(namespace) for namespace in namespaces] return namespaces, has_more_data, has_prev_data
python
def metadefs_namespace_list(request, filters=None, sort_dir='asc', sort_key='namespace', marker=None, paginate=False): """Retrieve a listing of Namespaces :param paginate: If true will perform pagination based on settings. :param marker: Specifies the namespace of the last-seen namespace. The typical pattern of limit and marker is to make an initial limited request and then to use the last namespace from the response as the marker parameter in a subsequent limited request. With paginate, limit is automatically set. :param sort_dir: The sort direction ('asc' or 'desc'). :param sort_key: The field to sort on (for example, 'created_at'). Default is namespace. The way base namespaces are loaded into glance typically at first deployment is done in a single transaction giving them a potentially unpredictable sort result when using create_at. :param filters: specifies addition fields to filter on such as resource_types. :returns A tuple of three values: 1) Current page results 2) A boolean of whether or not there are previous page(s). 3) A boolean of whether or not there are more page(s). """ # Listing namespaces requires the v2 API. If not supported we return an # empty array so callers don't need to worry about version checking. if get_version() < 2: return [], False, False if filters is None: filters = {} limit = getattr(settings, 'API_RESULT_LIMIT', 1000) page_size = utils.get_page_size(request) if paginate: request_size = page_size + 1 else: request_size = limit kwargs = {'filters': filters} if marker: kwargs['marker'] = marker kwargs['sort_dir'] = sort_dir kwargs['sort_key'] = sort_key namespaces_iter = glanceclient(request, '2').metadefs_namespace.list( page_size=request_size, limit=limit, **kwargs) # Filter the namespaces based on the provided properties_target since this # is not supported by the metadata namespaces API. resource_types = filters.get('resource_types') properties_target = filters.get('properties_target') if resource_types and properties_target: namespaces_iter = filter_properties_target(namespaces_iter, resource_types, properties_target) has_prev_data = False has_more_data = False if paginate: namespaces = list(itertools.islice(namespaces_iter, request_size)) # first and middle page condition if len(namespaces) > page_size: namespaces.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif sort_dir == 'desc' and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True else: namespaces = list(namespaces_iter) namespaces = [Namespace(namespace) for namespace in namespaces] return namespaces, has_more_data, has_prev_data
[ "def", "metadefs_namespace_list", "(", "request", ",", "filters", "=", "None", ",", "sort_dir", "=", "'asc'", ",", "sort_key", "=", "'namespace'", ",", "marker", "=", "None", ",", "paginate", "=", "False", ")", ":", "# Listing namespaces requires the v2 API. If no...
Retrieve a listing of Namespaces :param paginate: If true will perform pagination based on settings. :param marker: Specifies the namespace of the last-seen namespace. The typical pattern of limit and marker is to make an initial limited request and then to use the last namespace from the response as the marker parameter in a subsequent limited request. With paginate, limit is automatically set. :param sort_dir: The sort direction ('asc' or 'desc'). :param sort_key: The field to sort on (for example, 'created_at'). Default is namespace. The way base namespaces are loaded into glance typically at first deployment is done in a single transaction giving them a potentially unpredictable sort result when using create_at. :param filters: specifies addition fields to filter on such as resource_types. :returns A tuple of three values: 1) Current page results 2) A boolean of whether or not there are previous page(s). 3) A boolean of whether or not there are more page(s).
[ "Retrieve", "a", "listing", "of", "Namespaces" ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/glance.py#L668-L751
train
216,091
openstack/horizon
horizon/utils/file_discovery.py
discover_files
def discover_files(base_path, sub_path='', ext='', trim_base_path=False): """Discovers all files with certain extension in given paths.""" file_list = [] for root, dirs, files in walk(path.join(base_path, sub_path)): if trim_base_path: root = path.relpath(root, base_path) file_list.extend([path.join(root, file_name) for file_name in files if file_name.endswith(ext)]) return sorted(file_list)
python
def discover_files(base_path, sub_path='', ext='', trim_base_path=False): """Discovers all files with certain extension in given paths.""" file_list = [] for root, dirs, files in walk(path.join(base_path, sub_path)): if trim_base_path: root = path.relpath(root, base_path) file_list.extend([path.join(root, file_name) for file_name in files if file_name.endswith(ext)]) return sorted(file_list)
[ "def", "discover_files", "(", "base_path", ",", "sub_path", "=", "''", ",", "ext", "=", "''", ",", "trim_base_path", "=", "False", ")", ":", "file_list", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "walk", "(", "path", ".", "join",...
Discovers all files with certain extension in given paths.
[ "Discovers", "all", "files", "with", "certain", "extension", "in", "given", "paths", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/file_discovery.py#L25-L34
train
216,092
openstack/horizon
horizon/utils/file_discovery.py
sort_js_files
def sort_js_files(js_files): """Sorts JavaScript files in `js_files`. It sorts JavaScript files in a given `js_files` into source files, mock files and spec files based on file extension. Output: * sources: source files for production. The order of source files is significant and should be listed in the below order: - First, all the that defines the other application's angular module. Those files have extension of `.module.js`. The order among them is not significant. - Followed by all other source code files. The order among them is not significant. * mocks: mock files provide mock data/services for tests. They have extension of `.mock.js`. The order among them is not significant. * specs: spec files for testing. They have extension of `.spec.js`. The order among them is not significant. """ modules = [f for f in js_files if f.endswith(MODULE_EXT)] mocks = [f for f in js_files if f.endswith(MOCK_EXT)] specs = [f for f in js_files if f.endswith(SPEC_EXT)] other_sources = [f for f in js_files if (not f.endswith(MODULE_EXT) and not f.endswith(MOCK_EXT) and not f.endswith(SPEC_EXT))] sources = modules + other_sources return sources, mocks, specs
python
def sort_js_files(js_files): """Sorts JavaScript files in `js_files`. It sorts JavaScript files in a given `js_files` into source files, mock files and spec files based on file extension. Output: * sources: source files for production. The order of source files is significant and should be listed in the below order: - First, all the that defines the other application's angular module. Those files have extension of `.module.js`. The order among them is not significant. - Followed by all other source code files. The order among them is not significant. * mocks: mock files provide mock data/services for tests. They have extension of `.mock.js`. The order among them is not significant. * specs: spec files for testing. They have extension of `.spec.js`. The order among them is not significant. """ modules = [f for f in js_files if f.endswith(MODULE_EXT)] mocks = [f for f in js_files if f.endswith(MOCK_EXT)] specs = [f for f in js_files if f.endswith(SPEC_EXT)] other_sources = [f for f in js_files if (not f.endswith(MODULE_EXT) and not f.endswith(MOCK_EXT) and not f.endswith(SPEC_EXT))] sources = modules + other_sources return sources, mocks, specs
[ "def", "sort_js_files", "(", "js_files", ")", ":", "modules", "=", "[", "f", "for", "f", "in", "js_files", "if", "f", ".", "endswith", "(", "MODULE_EXT", ")", "]", "mocks", "=", "[", "f", "for", "f", "in", "js_files", "if", "f", ".", "endswith", "(...
Sorts JavaScript files in `js_files`. It sorts JavaScript files in a given `js_files` into source files, mock files and spec files based on file extension. Output: * sources: source files for production. The order of source files is significant and should be listed in the below order: - First, all the that defines the other application's angular module. Those files have extension of `.module.js`. The order among them is not significant. - Followed by all other source code files. The order among them is not significant. * mocks: mock files provide mock data/services for tests. They have extension of `.mock.js`. The order among them is not significant. * specs: spec files for testing. They have extension of `.spec.js`. The order among them is not significant.
[ "Sorts", "JavaScript", "files", "in", "js_files", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/file_discovery.py#L37-L72
train
216,093
openstack/horizon
horizon/utils/file_discovery.py
discover_static_files
def discover_static_files(base_path, sub_path=''): """Discovers static files in given paths. It returns JavaScript sources, mocks, specs and HTML templates, all grouped in lists. """ js_files = discover_files(base_path, sub_path=sub_path, ext='.js', trim_base_path=True) sources, mocks, specs = sort_js_files(js_files) html_files = discover_files(base_path, sub_path=sub_path, ext='.html', trim_base_path=True) p = path.join(base_path, sub_path) _log(sources, 'JavaScript source', p) _log(mocks, 'JavaScript mock', p) _log(specs, 'JavaScript spec', p) _log(html_files, 'HTML template', p) return sources, mocks, specs, html_files
python
def discover_static_files(base_path, sub_path=''): """Discovers static files in given paths. It returns JavaScript sources, mocks, specs and HTML templates, all grouped in lists. """ js_files = discover_files(base_path, sub_path=sub_path, ext='.js', trim_base_path=True) sources, mocks, specs = sort_js_files(js_files) html_files = discover_files(base_path, sub_path=sub_path, ext='.html', trim_base_path=True) p = path.join(base_path, sub_path) _log(sources, 'JavaScript source', p) _log(mocks, 'JavaScript mock', p) _log(specs, 'JavaScript spec', p) _log(html_files, 'HTML template', p) return sources, mocks, specs, html_files
[ "def", "discover_static_files", "(", "base_path", ",", "sub_path", "=", "''", ")", ":", "js_files", "=", "discover_files", "(", "base_path", ",", "sub_path", "=", "sub_path", ",", "ext", "=", "'.js'", ",", "trim_base_path", "=", "True", ")", "sources", ",", ...
Discovers static files in given paths. It returns JavaScript sources, mocks, specs and HTML templates, all grouped in lists.
[ "Discovers", "static", "files", "in", "given", "paths", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/file_discovery.py#L75-L93
train
216,094
openstack/horizon
horizon/utils/file_discovery.py
_log
def _log(file_list, list_name, in_path): """Logs result at debug level""" file_names = '\n'.join(file_list) LOG.debug("\nDiscovered %(size)d %(name)s file(s) in %(path)s:\n" "%(files)s\n", {'size': len(file_list), 'name': list_name, 'path': in_path, 'files': file_names})
python
def _log(file_list, list_name, in_path): """Logs result at debug level""" file_names = '\n'.join(file_list) LOG.debug("\nDiscovered %(size)d %(name)s file(s) in %(path)s:\n" "%(files)s\n", {'size': len(file_list), 'name': list_name, 'path': in_path, 'files': file_names})
[ "def", "_log", "(", "file_list", ",", "list_name", ",", "in_path", ")", ":", "file_names", "=", "'\\n'", ".", "join", "(", "file_list", ")", "LOG", ".", "debug", "(", "\"\\nDiscovered %(size)d %(name)s file(s) in %(path)s:\\n\"", "\"%(files)s\\n\"", ",", "{", "'si...
Logs result at debug level
[ "Logs", "result", "at", "debug", "level" ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/file_discovery.py#L110-L116
train
216,095
openstack/horizon
horizon/browsers/base.py
ResourceBrowser.set_tables
def set_tables(self, tables): """Sets the table instances on the browser. ``tables`` argument specifies tables to be set. It is a dictionary mapping table names to table instances (as constructed by MultiTableView). """ self.navigation_table = tables[self.navigation_table_class._meta.name] self.content_table = tables[self.content_table_class._meta.name] navigation_item = self.kwargs.get(self.navigation_kwarg_name) content_path = self.kwargs.get(self.content_kwarg_name) if self.has_breadcrumb: self.prepare_breadcrumb(tables, navigation_item, content_path)
python
def set_tables(self, tables): """Sets the table instances on the browser. ``tables`` argument specifies tables to be set. It is a dictionary mapping table names to table instances (as constructed by MultiTableView). """ self.navigation_table = tables[self.navigation_table_class._meta.name] self.content_table = tables[self.content_table_class._meta.name] navigation_item = self.kwargs.get(self.navigation_kwarg_name) content_path = self.kwargs.get(self.content_kwarg_name) if self.has_breadcrumb: self.prepare_breadcrumb(tables, navigation_item, content_path)
[ "def", "set_tables", "(", "self", ",", "tables", ")", ":", "self", ".", "navigation_table", "=", "tables", "[", "self", ".", "navigation_table_class", ".", "_meta", ".", "name", "]", "self", ".", "content_table", "=", "tables", "[", "self", ".", "content_t...
Sets the table instances on the browser. ``tables`` argument specifies tables to be set. It is a dictionary mapping table names to table instances (as constructed by MultiTableView).
[ "Sets", "the", "table", "instances", "on", "the", "browser", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/browsers/base.py#L121-L133
train
216,096
danpaquin/coinbasepro-python
cbpro/authenticated_client.py
AuthenticatedClient.get_account_history
def get_account_history(self, account_id, **kwargs): """ List account activity. Account activity either increases or decreases your account balance. Entry type indicates the reason for the account change. * transfer: Funds moved to/from Coinbase to cbpro * match: Funds moved as a result of a trade * fee: Fee as a result of a trade * rebate: Fee rebate as per our fee schedule If an entry is the result of a trade (match, fee), the details field will contain additional information about the trade. Args: account_id (str): Account id to get history of. kwargs (dict): Additional HTTP request parameters. Returns: list: History information for the account. Example:: [ { "id": "100", "created_at": "2014-11-07T08:19:27.028459Z", "amount": "0.001", "balance": "239.669", "type": "fee", "details": { "order_id": "d50ec984-77a8-460a-b958-66f114b0de9b", "trade_id": "74", "product_id": "BTC-USD" } }, { ... } ] """ endpoint = '/accounts/{}/ledger'.format(account_id) return self._send_paginated_message(endpoint, params=kwargs)
python
def get_account_history(self, account_id, **kwargs): """ List account activity. Account activity either increases or decreases your account balance. Entry type indicates the reason for the account change. * transfer: Funds moved to/from Coinbase to cbpro * match: Funds moved as a result of a trade * fee: Fee as a result of a trade * rebate: Fee rebate as per our fee schedule If an entry is the result of a trade (match, fee), the details field will contain additional information about the trade. Args: account_id (str): Account id to get history of. kwargs (dict): Additional HTTP request parameters. Returns: list: History information for the account. Example:: [ { "id": "100", "created_at": "2014-11-07T08:19:27.028459Z", "amount": "0.001", "balance": "239.669", "type": "fee", "details": { "order_id": "d50ec984-77a8-460a-b958-66f114b0de9b", "trade_id": "74", "product_id": "BTC-USD" } }, { ... } ] """ endpoint = '/accounts/{}/ledger'.format(account_id) return self._send_paginated_message(endpoint, params=kwargs)
[ "def", "get_account_history", "(", "self", ",", "account_id", ",", "*", "*", "kwargs", ")", ":", "endpoint", "=", "'/accounts/{}/ledger'", ".", "format", "(", "account_id", ")", "return", "self", ".", "_send_paginated_message", "(", "endpoint", ",", "params", ...
List account activity. Account activity either increases or decreases your account balance. Entry type indicates the reason for the account change. * transfer: Funds moved to/from Coinbase to cbpro * match: Funds moved as a result of a trade * fee: Fee as a result of a trade * rebate: Fee rebate as per our fee schedule If an entry is the result of a trade (match, fee), the details field will contain additional information about the trade. Args: account_id (str): Account id to get history of. kwargs (dict): Additional HTTP request parameters. Returns: list: History information for the account. Example:: [ { "id": "100", "created_at": "2014-11-07T08:19:27.028459Z", "amount": "0.001", "balance": "239.669", "type": "fee", "details": { "order_id": "d50ec984-77a8-460a-b958-66f114b0de9b", "trade_id": "74", "product_id": "BTC-USD" } }, { ... } ]
[ "List", "account", "activity", ".", "Account", "activity", "either", "increases", "or", "decreases", "your", "account", "balance", "." ]
0a9dbd86a25ae266d0e0eefeb112368c284b7dcc
https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L91-L129
train
216,097
danpaquin/coinbasepro-python
cbpro/authenticated_client.py
AuthenticatedClient.get_account_holds
def get_account_holds(self, account_id, **kwargs): """ Get holds on an account. This method returns a generator which may make multiple HTTP requests while iterating through it. Holds are placed on an account for active orders or pending withdraw requests. As an order is filled, the hold amount is updated. If an order is canceled, any remaining hold is removed. For a withdraw, once it is completed, the hold is removed. The `type` field will indicate why the hold exists. The hold type is 'order' for holds related to open orders and 'transfer' for holds related to a withdraw. The `ref` field contains the id of the order or transfer which created the hold. Args: account_id (str): Account id to get holds of. kwargs (dict): Additional HTTP request parameters. Returns: generator(list): Hold information for the account. Example:: [ { "id": "82dcd140-c3c7-4507-8de4-2c529cd1a28f", "account_id": "e0b3f39a-183d-453e-b754-0c13e5bab0b3", "created_at": "2014-11-06T10:34:47.123456Z", "updated_at": "2014-11-06T10:40:47.123456Z", "amount": "4.23", "type": "order", "ref": "0a205de4-dd35-4370-a285-fe8fc375a273", }, { ... } ] """ endpoint = '/accounts/{}/holds'.format(account_id) return self._send_paginated_message(endpoint, params=kwargs)
python
def get_account_holds(self, account_id, **kwargs): """ Get holds on an account. This method returns a generator which may make multiple HTTP requests while iterating through it. Holds are placed on an account for active orders or pending withdraw requests. As an order is filled, the hold amount is updated. If an order is canceled, any remaining hold is removed. For a withdraw, once it is completed, the hold is removed. The `type` field will indicate why the hold exists. The hold type is 'order' for holds related to open orders and 'transfer' for holds related to a withdraw. The `ref` field contains the id of the order or transfer which created the hold. Args: account_id (str): Account id to get holds of. kwargs (dict): Additional HTTP request parameters. Returns: generator(list): Hold information for the account. Example:: [ { "id": "82dcd140-c3c7-4507-8de4-2c529cd1a28f", "account_id": "e0b3f39a-183d-453e-b754-0c13e5bab0b3", "created_at": "2014-11-06T10:34:47.123456Z", "updated_at": "2014-11-06T10:40:47.123456Z", "amount": "4.23", "type": "order", "ref": "0a205de4-dd35-4370-a285-fe8fc375a273", }, { ... } ] """ endpoint = '/accounts/{}/holds'.format(account_id) return self._send_paginated_message(endpoint, params=kwargs)
[ "def", "get_account_holds", "(", "self", ",", "account_id", ",", "*", "*", "kwargs", ")", ":", "endpoint", "=", "'/accounts/{}/holds'", ".", "format", "(", "account_id", ")", "return", "self", ".", "_send_paginated_message", "(", "endpoint", ",", "params", "="...
Get holds on an account. This method returns a generator which may make multiple HTTP requests while iterating through it. Holds are placed on an account for active orders or pending withdraw requests. As an order is filled, the hold amount is updated. If an order is canceled, any remaining hold is removed. For a withdraw, once it is completed, the hold is removed. The `type` field will indicate why the hold exists. The hold type is 'order' for holds related to open orders and 'transfer' for holds related to a withdraw. The `ref` field contains the id of the order or transfer which created the hold. Args: account_id (str): Account id to get holds of. kwargs (dict): Additional HTTP request parameters. Returns: generator(list): Hold information for the account. Example:: [ { "id": "82dcd140-c3c7-4507-8de4-2c529cd1a28f", "account_id": "e0b3f39a-183d-453e-b754-0c13e5bab0b3", "created_at": "2014-11-06T10:34:47.123456Z", "updated_at": "2014-11-06T10:40:47.123456Z", "amount": "4.23", "type": "order", "ref": "0a205de4-dd35-4370-a285-fe8fc375a273", }, { ... } ]
[ "Get", "holds", "on", "an", "account", "." ]
0a9dbd86a25ae266d0e0eefeb112368c284b7dcc
https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L131-L174
train
216,098
danpaquin/coinbasepro-python
cbpro/authenticated_client.py
AuthenticatedClient.buy
def buy(self, product_id, order_type, **kwargs): """Place a buy order. This is included to maintain backwards compatibility with older versions of cbpro-Python. For maximum support from docstrings and function signatures see the order type-specific functions place_limit_order, place_market_order, and place_stop_order. Args: product_id (str): Product to order (eg. 'BTC-USD') order_type (str): Order type ('limit', 'market', or 'stop') **kwargs: Additional arguments can be specified for different order types. Returns: dict: Order details. See `place_order` for example. """ return self.place_order(product_id, 'buy', order_type, **kwargs)
python
def buy(self, product_id, order_type, **kwargs): """Place a buy order. This is included to maintain backwards compatibility with older versions of cbpro-Python. For maximum support from docstrings and function signatures see the order type-specific functions place_limit_order, place_market_order, and place_stop_order. Args: product_id (str): Product to order (eg. 'BTC-USD') order_type (str): Order type ('limit', 'market', or 'stop') **kwargs: Additional arguments can be specified for different order types. Returns: dict: Order details. See `place_order` for example. """ return self.place_order(product_id, 'buy', order_type, **kwargs)
[ "def", "buy", "(", "self", ",", "product_id", ",", "order_type", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "place_order", "(", "product_id", ",", "'buy'", ",", "order_type", ",", "*", "*", "kwargs", ")" ]
Place a buy order. This is included to maintain backwards compatibility with older versions of cbpro-Python. For maximum support from docstrings and function signatures see the order type-specific functions place_limit_order, place_market_order, and place_stop_order. Args: product_id (str): Product to order (eg. 'BTC-USD') order_type (str): Order type ('limit', 'market', or 'stop') **kwargs: Additional arguments can be specified for different order types. Returns: dict: Order details. See `place_order` for example.
[ "Place", "a", "buy", "order", "." ]
0a9dbd86a25ae266d0e0eefeb112368c284b7dcc
https://github.com/danpaquin/coinbasepro-python/blob/0a9dbd86a25ae266d0e0eefeb112368c284b7dcc/cbpro/authenticated_client.py#L258-L276
train
216,099