id
int32
0
252k
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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
1,300
protream/iquery
iquery/trains.py
TrainTicketsQuery._valid_date
def _valid_date(self): """Check and return a valid query date.""" date = self._parse_date(self.date) if not date: exit_after_echo(INVALID_DATE) try: date = datetime.strptime(date, '%Y%m%d') except ValueError: exit_after_echo(INVALID_DATE) # A valid query date should within 50 days. offset = date - datetime.today() if offset.days not in range(-1, 50): exit_after_echo(INVALID_DATE) return datetime.strftime(date, '%Y-%m-%d')
python
def _valid_date(self): """Check and return a valid query date.""" date = self._parse_date(self.date) if not date: exit_after_echo(INVALID_DATE) try: date = datetime.strptime(date, '%Y%m%d') except ValueError: exit_after_echo(INVALID_DATE) # A valid query date should within 50 days. offset = date - datetime.today() if offset.days not in range(-1, 50): exit_after_echo(INVALID_DATE) return datetime.strftime(date, '%Y-%m-%d')
[ "def", "_valid_date", "(", "self", ")", ":", "date", "=", "self", ".", "_parse_date", "(", "self", ".", "date", ")", "if", "not", "date", ":", "exit_after_echo", "(", "INVALID_DATE", ")", "try", ":", "date", "=", "datetime", ".", "strptime", "(", "date", ",", "'%Y%m%d'", ")", "except", "ValueError", ":", "exit_after_echo", "(", "INVALID_DATE", ")", "# A valid query date should within 50 days.", "offset", "=", "date", "-", "datetime", ".", "today", "(", ")", "if", "offset", ".", "days", "not", "in", "range", "(", "-", "1", ",", "50", ")", ":", "exit_after_echo", "(", "INVALID_DATE", ")", "return", "datetime", ".", "strftime", "(", "date", ",", "'%Y-%m-%d'", ")" ]
Check and return a valid query date.
[ "Check", "and", "return", "a", "valid", "query", "date", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L177-L194
1,301
protream/iquery
iquery/trains.py
TrainTicketsQuery._parse_date
def _parse_date(date): """Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string. """ result = ''.join(re.findall('\d', date)) l = len(result) # User only input month and day, eg 6-1, 6.26, 0626... if l in (2, 3, 4): year = str(datetime.today().year) return year + result # User input full format date, eg 201661, 2016-6-26, 20160626... if l in (6, 7, 8): return result return ''
python
def _parse_date(date): """Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string. """ result = ''.join(re.findall('\d', date)) l = len(result) # User only input month and day, eg 6-1, 6.26, 0626... if l in (2, 3, 4): year = str(datetime.today().year) return year + result # User input full format date, eg 201661, 2016-6-26, 20160626... if l in (6, 7, 8): return result return ''
[ "def", "_parse_date", "(", "date", ")", ":", "result", "=", "''", ".", "join", "(", "re", ".", "findall", "(", "'\\d'", ",", "date", ")", ")", "l", "=", "len", "(", "result", ")", "# User only input month and day, eg 6-1, 6.26, 0626...", "if", "l", "in", "(", "2", ",", "3", ",", "4", ")", ":", "year", "=", "str", "(", "datetime", ".", "today", "(", ")", ".", "year", ")", "return", "year", "+", "result", "# User input full format date, eg 201661, 2016-6-26, 20160626...", "if", "l", "in", "(", "6", ",", "7", ",", "8", ")", ":", "return", "result", "return", "''" ]
Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string.
[ "Parse", "from", "the", "user", "input", "date", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L197-L218
1,302
protream/iquery
iquery/trains.py
TrainTicketsQuery._build_params
def _build_params(self): """Have no idea why wrong params order can't get data. So, use `OrderedDict` here. """ d = OrderedDict() d['purpose_codes'] = 'ADULT' d['queryDate'] = self._valid_date d['from_station'] = self._from_station_telecode d['to_station'] = self._to_station_telecode return d
python
def _build_params(self): """Have no idea why wrong params order can't get data. So, use `OrderedDict` here. """ d = OrderedDict() d['purpose_codes'] = 'ADULT' d['queryDate'] = self._valid_date d['from_station'] = self._from_station_telecode d['to_station'] = self._to_station_telecode return d
[ "def", "_build_params", "(", "self", ")", ":", "d", "=", "OrderedDict", "(", ")", "d", "[", "'purpose_codes'", "]", "=", "'ADULT'", "d", "[", "'queryDate'", "]", "=", "self", ".", "_valid_date", "d", "[", "'from_station'", "]", "=", "self", ".", "_from_station_telecode", "d", "[", "'to_station'", "]", "=", "self", ".", "_to_station_telecode", "return", "d" ]
Have no idea why wrong params order can't get data. So, use `OrderedDict` here.
[ "Have", "no", "idea", "why", "wrong", "params", "order", "can", "t", "get", "data", ".", "So", "use", "OrderedDict", "here", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L220-L229
1,303
protream/iquery
iquery/showes.py
ShowTicketsQuery.date_range
def date_range(self): """Generate date range according to the `days` user input.""" try: days = int(self.days) except ValueError: exit_after_echo(QUERY_DAYS_INVALID) if days < 1: exit_after_echo(QUERY_DAYS_INVALID) start = datetime.today() end = start + timedelta(days=days) return ( datetime.strftime(start, '%Y-%m-%d'), datetime.strftime(end, '%Y-%m-%d') )
python
def date_range(self): """Generate date range according to the `days` user input.""" try: days = int(self.days) except ValueError: exit_after_echo(QUERY_DAYS_INVALID) if days < 1: exit_after_echo(QUERY_DAYS_INVALID) start = datetime.today() end = start + timedelta(days=days) return ( datetime.strftime(start, '%Y-%m-%d'), datetime.strftime(end, '%Y-%m-%d') )
[ "def", "date_range", "(", "self", ")", ":", "try", ":", "days", "=", "int", "(", "self", ".", "days", ")", "except", "ValueError", ":", "exit_after_echo", "(", "QUERY_DAYS_INVALID", ")", "if", "days", "<", "1", ":", "exit_after_echo", "(", "QUERY_DAYS_INVALID", ")", "start", "=", "datetime", ".", "today", "(", ")", "end", "=", "start", "+", "timedelta", "(", "days", "=", "days", ")", "return", "(", "datetime", ".", "strftime", "(", "start", ",", "'%Y-%m-%d'", ")", ",", "datetime", ".", "strftime", "(", "end", ",", "'%Y-%m-%d'", ")", ")" ]
Generate date range according to the `days` user input.
[ "Generate", "date", "range", "according", "to", "the", "days", "user", "input", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/showes.py#L121-L135
1,304
protream/iquery
iquery/hospitals.py
query
def query(params): """`params` is a city name or a city name + hospital name. CLI: 1. query all putian hospitals in a city: $ iquery -p 南京 +------+ | 南京 | +------+ |... | +------+ |... | +------+ ... 2. query if the hospital in the city is putian series, you can only input hospital's short name: $ iquery -p 南京 曙光 +------------+ |南京曙光医院| +------------+ | True | +------------+ """ r = requests_get(QUERY_URL, verify=True) return HospitalCollection(r.json(), params)
python
def query(params): """`params` is a city name or a city name + hospital name. CLI: 1. query all putian hospitals in a city: $ iquery -p 南京 +------+ | 南京 | +------+ |... | +------+ |... | +------+ ... 2. query if the hospital in the city is putian series, you can only input hospital's short name: $ iquery -p 南京 曙光 +------------+ |南京曙光医院| +------------+ | True | +------------+ """ r = requests_get(QUERY_URL, verify=True) return HospitalCollection(r.json(), params)
[ "def", "query", "(", "params", ")", ":", "r", "=", "requests_get", "(", "QUERY_URL", ",", "verify", "=", "True", ")", "return", "HospitalCollection", "(", "r", ".", "json", "(", ")", ",", "params", ")" ]
`params` is a city name or a city name + hospital name. CLI: 1. query all putian hospitals in a city: $ iquery -p 南京 +------+ | 南京 | +------+ |... | +------+ |... | +------+ ... 2. query if the hospital in the city is putian series, you can only input hospital's short name: $ iquery -p 南京 曙光 +------------+ |南京曙光医院| +------------+ | True | +------------+
[ "params", "is", "a", "city", "name", "or", "a", "city", "name", "+", "hospital", "name", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/hospitals.py#L67-L99
1,305
protream/iquery
iquery/core.py
cli
def cli(): """Various information query via command line. Usage: iquery -l <song> [singer] iquery (-m|电影) iquery (-c|彩票) iquery -p <city> iquery -p <city> <hospital> iquery <city> <show> [days] iquery [-dgktz] <from> <to> <date> Arguments: from 出发站 to 到达站 date 查询日期 song 歌曲名称 singer 歌手, 可选项 city 查询城市 show 演出的类型 days 查询近(几)天内的演出, 若省略, 默认15 city 城市名,加在-p后查询该城市所有莆田医院 hospital 医院名,加在city后检查该医院是否是莆田系 Options: -h, --help 显示该帮助菜单. -dgktz 动车,高铁,快速,特快,直达 -m 热映电影查询 -p 莆田系医院查询 -l 歌词查询 Show: 演唱会 音乐会 音乐剧 歌舞剧 儿童剧 话剧 歌剧 比赛 舞蹈 戏曲 相声 杂技 马戏 魔术 Go to https://github.com/protream/tickets for usage examples. """ if args.is_asking_for_help: exit_after_echo(cli.__doc__, color=None) elif args.is_querying_lottery: from .lottery import query result = query() elif args.is_querying_movie: from .movies import query result = query() elif args.is_querying_lyric: from .lyrics import query result = query(args.as_lyric_query_params) elif args.is_querying_show: from .showes import query result = query(args.as_show_query_params) elif args.is_querying_putian_hospital: from .hospitals import query result = query(args.as_hospital_query_params) elif args.is_querying_train: from .trains import query result = query(args.as_train_query_params) else: exit_after_echo(show_usage.__doc__, color=None) result.pretty_print()
python
def cli(): """Various information query via command line. Usage: iquery -l <song> [singer] iquery (-m|电影) iquery (-c|彩票) iquery -p <city> iquery -p <city> <hospital> iquery <city> <show> [days] iquery [-dgktz] <from> <to> <date> Arguments: from 出发站 to 到达站 date 查询日期 song 歌曲名称 singer 歌手, 可选项 city 查询城市 show 演出的类型 days 查询近(几)天内的演出, 若省略, 默认15 city 城市名,加在-p后查询该城市所有莆田医院 hospital 医院名,加在city后检查该医院是否是莆田系 Options: -h, --help 显示该帮助菜单. -dgktz 动车,高铁,快速,特快,直达 -m 热映电影查询 -p 莆田系医院查询 -l 歌词查询 Show: 演唱会 音乐会 音乐剧 歌舞剧 儿童剧 话剧 歌剧 比赛 舞蹈 戏曲 相声 杂技 马戏 魔术 Go to https://github.com/protream/tickets for usage examples. """ if args.is_asking_for_help: exit_after_echo(cli.__doc__, color=None) elif args.is_querying_lottery: from .lottery import query result = query() elif args.is_querying_movie: from .movies import query result = query() elif args.is_querying_lyric: from .lyrics import query result = query(args.as_lyric_query_params) elif args.is_querying_show: from .showes import query result = query(args.as_show_query_params) elif args.is_querying_putian_hospital: from .hospitals import query result = query(args.as_hospital_query_params) elif args.is_querying_train: from .trains import query result = query(args.as_train_query_params) else: exit_after_echo(show_usage.__doc__, color=None) result.pretty_print()
[ "def", "cli", "(", ")", ":", "if", "args", ".", "is_asking_for_help", ":", "exit_after_echo", "(", "cli", ".", "__doc__", ",", "color", "=", "None", ")", "elif", "args", ".", "is_querying_lottery", ":", "from", ".", "lottery", "import", "query", "result", "=", "query", "(", ")", "elif", "args", ".", "is_querying_movie", ":", "from", ".", "movies", "import", "query", "result", "=", "query", "(", ")", "elif", "args", ".", "is_querying_lyric", ":", "from", ".", "lyrics", "import", "query", "result", "=", "query", "(", "args", ".", "as_lyric_query_params", ")", "elif", "args", ".", "is_querying_show", ":", "from", ".", "showes", "import", "query", "result", "=", "query", "(", "args", ".", "as_show_query_params", ")", "elif", "args", ".", "is_querying_putian_hospital", ":", "from", ".", "hospitals", "import", "query", "result", "=", "query", "(", "args", ".", "as_hospital_query_params", ")", "elif", "args", ".", "is_querying_train", ":", "from", ".", "trains", "import", "query", "result", "=", "query", "(", "args", ".", "as_train_query_params", ")", "else", ":", "exit_after_echo", "(", "show_usage", ".", "__doc__", ",", "color", "=", "None", ")", "result", ".", "pretty_print", "(", ")" ]
Various information query via command line. Usage: iquery -l <song> [singer] iquery (-m|电影) iquery (-c|彩票) iquery -p <city> iquery -p <city> <hospital> iquery <city> <show> [days] iquery [-dgktz] <from> <to> <date> Arguments: from 出发站 to 到达站 date 查询日期 song 歌曲名称 singer 歌手, 可选项 city 查询城市 show 演出的类型 days 查询近(几)天内的演出, 若省略, 默认15 city 城市名,加在-p后查询该城市所有莆田医院 hospital 医院名,加在city后检查该医院是否是莆田系 Options: -h, --help 显示该帮助菜单. -dgktz 动车,高铁,快速,特快,直达 -m 热映电影查询 -p 莆田系医院查询 -l 歌词查询 Show: 演唱会 音乐会 音乐剧 歌舞剧 儿童剧 话剧 歌剧 比赛 舞蹈 戏曲 相声 杂技 马戏 魔术 Go to https://github.com/protream/tickets for usage examples.
[ "Various", "information", "query", "via", "command", "line", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/core.py#L44-L117
1,306
protream/iquery
iquery/movies.py
query
def query(): """Query hot movies infomation from douban.""" r = requests_get(QUERY_URL) try: rows = r.json()['subject_collection_items'] except (IndexError, TypeError): rows = [] return MoviesCollection(rows)
python
def query(): """Query hot movies infomation from douban.""" r = requests_get(QUERY_URL) try: rows = r.json()['subject_collection_items'] except (IndexError, TypeError): rows = [] return MoviesCollection(rows)
[ "def", "query", "(", ")", ":", "r", "=", "requests_get", "(", "QUERY_URL", ")", "try", ":", "rows", "=", "r", ".", "json", "(", ")", "[", "'subject_collection_items'", "]", "except", "(", "IndexError", ",", "TypeError", ")", ":", "rows", "=", "[", "]", "return", "MoviesCollection", "(", "rows", ")" ]
Query hot movies infomation from douban.
[ "Query", "hot", "movies", "infomation", "from", "douban", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/movies.py#L93-L103
1,307
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory.action_draft
def action_draft(self): """Set a change request as draft""" for rec in self: if not rec.state == 'cancelled': raise UserError( _('You need to cancel it before reopening.')) if not (rec.am_i_owner or rec.am_i_approver): raise UserError( _('You are not authorized to do this.\r\n' 'Only owners or approvers can reopen Change Requests.')) rec.write({'state': 'draft'})
python
def action_draft(self): """Set a change request as draft""" for rec in self: if not rec.state == 'cancelled': raise UserError( _('You need to cancel it before reopening.')) if not (rec.am_i_owner or rec.am_i_approver): raise UserError( _('You are not authorized to do this.\r\n' 'Only owners or approvers can reopen Change Requests.')) rec.write({'state': 'draft'})
[ "def", "action_draft", "(", "self", ")", ":", "for", "rec", "in", "self", ":", "if", "not", "rec", ".", "state", "==", "'cancelled'", ":", "raise", "UserError", "(", "_", "(", "'You need to cancel it before reopening.'", ")", ")", "if", "not", "(", "rec", ".", "am_i_owner", "or", "rec", ".", "am_i_approver", ")", ":", "raise", "UserError", "(", "_", "(", "'You are not authorized to do this.\\r\\n'", "'Only owners or approvers can reopen Change Requests.'", ")", ")", "rec", ".", "write", "(", "{", "'state'", ":", "'draft'", "}", ")" ]
Set a change request as draft
[ "Set", "a", "change", "request", "as", "draft" ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L54-L64
1,308
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory.action_to_approve
def action_to_approve(self): """Set a change request as to approve""" template = self.env.ref( 'document_page_approval.email_template_new_draft_need_approval') approver_gid = self.env.ref( 'document_page_approval.group_document_approver_user') for rec in self: if rec.state != 'draft': raise UserError( _("Can't approve pages in '%s' state.") % rec.state) if not (rec.am_i_owner or rec.am_i_approver): raise UserError( _('You are not authorized to do this.\r\n' 'Only owners or approvers can request approval.')) # request approval if rec.is_approval_required: rec.write({'state': 'to approve'}) guids = [g.id for g in rec.page_id.approver_group_ids] users = self.env['res.users'].search([ ('groups_id', 'in', guids), ('groups_id', 'in', approver_gid.id)]) rec.message_subscribe_users([u.id for u in users]) rec.message_post_with_template(template.id) else: # auto-approve if approval is not required rec.action_approve()
python
def action_to_approve(self): """Set a change request as to approve""" template = self.env.ref( 'document_page_approval.email_template_new_draft_need_approval') approver_gid = self.env.ref( 'document_page_approval.group_document_approver_user') for rec in self: if rec.state != 'draft': raise UserError( _("Can't approve pages in '%s' state.") % rec.state) if not (rec.am_i_owner or rec.am_i_approver): raise UserError( _('You are not authorized to do this.\r\n' 'Only owners or approvers can request approval.')) # request approval if rec.is_approval_required: rec.write({'state': 'to approve'}) guids = [g.id for g in rec.page_id.approver_group_ids] users = self.env['res.users'].search([ ('groups_id', 'in', guids), ('groups_id', 'in', approver_gid.id)]) rec.message_subscribe_users([u.id for u in users]) rec.message_post_with_template(template.id) else: # auto-approve if approval is not required rec.action_approve()
[ "def", "action_to_approve", "(", "self", ")", ":", "template", "=", "self", ".", "env", ".", "ref", "(", "'document_page_approval.email_template_new_draft_need_approval'", ")", "approver_gid", "=", "self", ".", "env", ".", "ref", "(", "'document_page_approval.group_document_approver_user'", ")", "for", "rec", "in", "self", ":", "if", "rec", ".", "state", "!=", "'draft'", ":", "raise", "UserError", "(", "_", "(", "\"Can't approve pages in '%s' state.\"", ")", "%", "rec", ".", "state", ")", "if", "not", "(", "rec", ".", "am_i_owner", "or", "rec", ".", "am_i_approver", ")", ":", "raise", "UserError", "(", "_", "(", "'You are not authorized to do this.\\r\\n'", "'Only owners or approvers can request approval.'", ")", ")", "# request approval", "if", "rec", ".", "is_approval_required", ":", "rec", ".", "write", "(", "{", "'state'", ":", "'to approve'", "}", ")", "guids", "=", "[", "g", ".", "id", "for", "g", "in", "rec", ".", "page_id", ".", "approver_group_ids", "]", "users", "=", "self", ".", "env", "[", "'res.users'", "]", ".", "search", "(", "[", "(", "'groups_id'", ",", "'in'", ",", "guids", ")", ",", "(", "'groups_id'", ",", "'in'", ",", "approver_gid", ".", "id", ")", "]", ")", "rec", ".", "message_subscribe_users", "(", "[", "u", ".", "id", "for", "u", "in", "users", "]", ")", "rec", ".", "message_post_with_template", "(", "template", ".", "id", ")", "else", ":", "# auto-approve if approval is not required", "rec", ".", "action_approve", "(", ")" ]
Set a change request as to approve
[ "Set", "a", "change", "request", "as", "to", "approve" ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L67-L92
1,309
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory.action_approve
def action_approve(self): """Set a change request as approved.""" for rec in self: if rec.state not in ['draft', 'to approve']: raise UserError( _("Can't approve page in '%s' state.") % rec.state) if not rec.am_i_approver: raise UserError(_( 'You are not authorized to do this.\r\n' 'Only approvers with these groups can approve this: ' ) % ', '.join( [g.display_name for g in rec.page_id.approver_group_ids])) # Update state rec.write({ 'state': 'approved', 'approved_date': fields.datetime.now(), 'approved_uid': self.env.uid, }) # Trigger computed field update rec.page_id._compute_history_head() # Notify state change rec.message_post( subtype='mt_comment', body=_( 'Change request has been approved by %s.' ) % (self.env.user.name) ) # Notify followers a new version is available rec.page_id.message_post( subtype='mt_comment', body=_( 'New version of the document %s approved.' ) % (rec.page_id.name) )
python
def action_approve(self): """Set a change request as approved.""" for rec in self: if rec.state not in ['draft', 'to approve']: raise UserError( _("Can't approve page in '%s' state.") % rec.state) if not rec.am_i_approver: raise UserError(_( 'You are not authorized to do this.\r\n' 'Only approvers with these groups can approve this: ' ) % ', '.join( [g.display_name for g in rec.page_id.approver_group_ids])) # Update state rec.write({ 'state': 'approved', 'approved_date': fields.datetime.now(), 'approved_uid': self.env.uid, }) # Trigger computed field update rec.page_id._compute_history_head() # Notify state change rec.message_post( subtype='mt_comment', body=_( 'Change request has been approved by %s.' ) % (self.env.user.name) ) # Notify followers a new version is available rec.page_id.message_post( subtype='mt_comment', body=_( 'New version of the document %s approved.' ) % (rec.page_id.name) )
[ "def", "action_approve", "(", "self", ")", ":", "for", "rec", "in", "self", ":", "if", "rec", ".", "state", "not", "in", "[", "'draft'", ",", "'to approve'", "]", ":", "raise", "UserError", "(", "_", "(", "\"Can't approve page in '%s' state.\"", ")", "%", "rec", ".", "state", ")", "if", "not", "rec", ".", "am_i_approver", ":", "raise", "UserError", "(", "_", "(", "'You are not authorized to do this.\\r\\n'", "'Only approvers with these groups can approve this: '", ")", "%", "', '", ".", "join", "(", "[", "g", ".", "display_name", "for", "g", "in", "rec", ".", "page_id", ".", "approver_group_ids", "]", ")", ")", "# Update state", "rec", ".", "write", "(", "{", "'state'", ":", "'approved'", ",", "'approved_date'", ":", "fields", ".", "datetime", ".", "now", "(", ")", ",", "'approved_uid'", ":", "self", ".", "env", ".", "uid", ",", "}", ")", "# Trigger computed field update", "rec", ".", "page_id", ".", "_compute_history_head", "(", ")", "# Notify state change", "rec", ".", "message_post", "(", "subtype", "=", "'mt_comment'", ",", "body", "=", "_", "(", "'Change request has been approved by %s.'", ")", "%", "(", "self", ".", "env", ".", "user", ".", "name", ")", ")", "# Notify followers a new version is available", "rec", ".", "page_id", ".", "message_post", "(", "subtype", "=", "'mt_comment'", ",", "body", "=", "_", "(", "'New version of the document %s approved.'", ")", "%", "(", "rec", ".", "page_id", ".", "name", ")", ")" ]
Set a change request as approved.
[ "Set", "a", "change", "request", "as", "approved", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L95-L129
1,310
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory.action_cancel
def action_cancel(self): """Set a change request as cancelled.""" self.write({'state': 'cancelled'}) for rec in self: rec.message_post( subtype='mt_comment', body=_( 'Change request <b>%s</b> has been cancelled by %s.' ) % (rec.display_name, self.env.user.name) )
python
def action_cancel(self): """Set a change request as cancelled.""" self.write({'state': 'cancelled'}) for rec in self: rec.message_post( subtype='mt_comment', body=_( 'Change request <b>%s</b> has been cancelled by %s.' ) % (rec.display_name, self.env.user.name) )
[ "def", "action_cancel", "(", "self", ")", ":", "self", ".", "write", "(", "{", "'state'", ":", "'cancelled'", "}", ")", "for", "rec", "in", "self", ":", "rec", ".", "message_post", "(", "subtype", "=", "'mt_comment'", ",", "body", "=", "_", "(", "'Change request <b>%s</b> has been cancelled by %s.'", ")", "%", "(", "rec", ".", "display_name", ",", "self", ".", "env", ".", "user", ".", "name", ")", ")" ]
Set a change request as cancelled.
[ "Set", "a", "change", "request", "as", "cancelled", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L132-L141
1,311
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory._compute_am_i_owner
def _compute_am_i_owner(self): """Check if current user is the owner""" for rec in self: rec.am_i_owner = (rec.create_uid == self.env.user)
python
def _compute_am_i_owner(self): """Check if current user is the owner""" for rec in self: rec.am_i_owner = (rec.create_uid == self.env.user)
[ "def", "_compute_am_i_owner", "(", "self", ")", ":", "for", "rec", "in", "self", ":", "rec", ".", "am_i_owner", "=", "(", "rec", ".", "create_uid", "==", "self", ".", "env", ".", "user", ")" ]
Check if current user is the owner
[ "Check", "if", "current", "user", "is", "the", "owner" ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L150-L153
1,312
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory._compute_page_url
def _compute_page_url(self): """Compute the page url.""" for page in self: base_url = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url', default='http://localhost:8069' ) page.page_url = ( '{}/web#db={}&id={}&view_type=form&' 'model=document.page.history').format( base_url, self.env.cr.dbname, page.id )
python
def _compute_page_url(self): """Compute the page url.""" for page in self: base_url = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url', default='http://localhost:8069' ) page.page_url = ( '{}/web#db={}&id={}&view_type=form&' 'model=document.page.history').format( base_url, self.env.cr.dbname, page.id )
[ "def", "_compute_page_url", "(", "self", ")", ":", "for", "page", "in", "self", ":", "base_url", "=", "self", ".", "env", "[", "'ir.config_parameter'", "]", ".", "sudo", "(", ")", ".", "get_param", "(", "'web.base.url'", ",", "default", "=", "'http://localhost:8069'", ")", "page", ".", "page_url", "=", "(", "'{}/web#db={}&id={}&view_type=form&'", "'model=document.page.history'", ")", ".", "format", "(", "base_url", ",", "self", ".", "env", ".", "cr", ".", "dbname", ",", "page", ".", "id", ")" ]
Compute the page url.
[ "Compute", "the", "page", "url", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L156-L170
1,313
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory._compute_diff
def _compute_diff(self): """Shows a diff between this version and the previous version""" history = self.env['document.page.history'] for rec in self: domain = [ ('page_id', '=', rec.page_id.id), ('state', '=', 'approved')] if rec.approved_date: domain.append(('approved_date', '<', rec.approved_date)) prev = history.search(domain, limit=1, order='approved_date DESC') if prev: rec.diff = self.getDiff(prev.id, rec.id) else: rec.diff = self.getDiff(False, rec.id)
python
def _compute_diff(self): """Shows a diff between this version and the previous version""" history = self.env['document.page.history'] for rec in self: domain = [ ('page_id', '=', rec.page_id.id), ('state', '=', 'approved')] if rec.approved_date: domain.append(('approved_date', '<', rec.approved_date)) prev = history.search(domain, limit=1, order='approved_date DESC') if prev: rec.diff = self.getDiff(prev.id, rec.id) else: rec.diff = self.getDiff(False, rec.id)
[ "def", "_compute_diff", "(", "self", ")", ":", "history", "=", "self", ".", "env", "[", "'document.page.history'", "]", "for", "rec", "in", "self", ":", "domain", "=", "[", "(", "'page_id'", ",", "'='", ",", "rec", ".", "page_id", ".", "id", ")", ",", "(", "'state'", ",", "'='", ",", "'approved'", ")", "]", "if", "rec", ".", "approved_date", ":", "domain", ".", "append", "(", "(", "'approved_date'", ",", "'<'", ",", "rec", ".", "approved_date", ")", ")", "prev", "=", "history", ".", "search", "(", "domain", ",", "limit", "=", "1", ",", "order", "=", "'approved_date DESC'", ")", "if", "prev", ":", "rec", ".", "diff", "=", "self", ".", "getDiff", "(", "prev", ".", "id", ",", "rec", ".", "id", ")", "else", ":", "rec", ".", "diff", "=", "self", ".", "getDiff", "(", "False", ",", "rec", ".", "id", ")" ]
Shows a diff between this version and the previous version
[ "Shows", "a", "diff", "between", "this", "version", "and", "the", "previous", "version" ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L173-L186
1,314
OCA/knowledge
document_url/wizard/document_url.py
AddUrlWizard.action_add_url
def action_add_url(self): """Adds the URL with the given name as an ir.attachment record.""" if not self.env.context.get('active_model'): return attachment_obj = self.env['ir.attachment'] for form in self: url = parse.urlparse(form.url) if not url.scheme: url = parse.urlparse('%s%s' % ('http://', form.url)) for active_id in self.env.context.get('active_ids', []): attachment = { 'name': form.name, 'type': 'url', 'url': url.geturl(), 'res_id': active_id, 'res_model': self.env.context['active_model'], } attachment_obj.create(attachment) return {'type': 'ir.actions.act_close_wizard_and_reload_view'}
python
def action_add_url(self): """Adds the URL with the given name as an ir.attachment record.""" if not self.env.context.get('active_model'): return attachment_obj = self.env['ir.attachment'] for form in self: url = parse.urlparse(form.url) if not url.scheme: url = parse.urlparse('%s%s' % ('http://', form.url)) for active_id in self.env.context.get('active_ids', []): attachment = { 'name': form.name, 'type': 'url', 'url': url.geturl(), 'res_id': active_id, 'res_model': self.env.context['active_model'], } attachment_obj.create(attachment) return {'type': 'ir.actions.act_close_wizard_and_reload_view'}
[ "def", "action_add_url", "(", "self", ")", ":", "if", "not", "self", ".", "env", ".", "context", ".", "get", "(", "'active_model'", ")", ":", "return", "attachment_obj", "=", "self", ".", "env", "[", "'ir.attachment'", "]", "for", "form", "in", "self", ":", "url", "=", "parse", ".", "urlparse", "(", "form", ".", "url", ")", "if", "not", "url", ".", "scheme", ":", "url", "=", "parse", ".", "urlparse", "(", "'%s%s'", "%", "(", "'http://'", ",", "form", ".", "url", ")", ")", "for", "active_id", "in", "self", ".", "env", ".", "context", ".", "get", "(", "'active_ids'", ",", "[", "]", ")", ":", "attachment", "=", "{", "'name'", ":", "form", ".", "name", ",", "'type'", ":", "'url'", ",", "'url'", ":", "url", ".", "geturl", "(", ")", ",", "'res_id'", ":", "active_id", ",", "'res_model'", ":", "self", ".", "env", ".", "context", "[", "'active_model'", "]", ",", "}", "attachment_obj", ".", "create", "(", "attachment", ")", "return", "{", "'type'", ":", "'ir.actions.act_close_wizard_and_reload_view'", "}" ]
Adds the URL with the given name as an ir.attachment record.
[ "Adds", "the", "URL", "with", "the", "given", "name", "as", "an", "ir", ".", "attachment", "record", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_url/wizard/document_url.py#L14-L32
1,315
OCA/knowledge
document_page_approval/models/document_page.py
DocumentPage._compute_is_approval_required
def _compute_is_approval_required(self): """Check if the document required approval based on his parents.""" for page in self: res = page.approval_required if page.parent_id: res = res or page.parent_id.is_approval_required page.is_approval_required = res
python
def _compute_is_approval_required(self): """Check if the document required approval based on his parents.""" for page in self: res = page.approval_required if page.parent_id: res = res or page.parent_id.is_approval_required page.is_approval_required = res
[ "def", "_compute_is_approval_required", "(", "self", ")", ":", "for", "page", "in", "self", ":", "res", "=", "page", ".", "approval_required", "if", "page", ".", "parent_id", ":", "res", "=", "res", "or", "page", ".", "parent_id", ".", "is_approval_required", "page", ".", "is_approval_required", "=", "res" ]
Check if the document required approval based on his parents.
[ "Check", "if", "the", "document", "required", "approval", "based", "on", "his", "parents", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L76-L82
1,316
OCA/knowledge
document_page_approval/models/document_page.py
DocumentPage._compute_approver_group_ids
def _compute_approver_group_ids(self): """Compute the approver groups based on his parents.""" for page in self: res = page.approver_gid if page.parent_id: res = res | page.parent_id.approver_group_ids page.approver_group_ids = res
python
def _compute_approver_group_ids(self): """Compute the approver groups based on his parents.""" for page in self: res = page.approver_gid if page.parent_id: res = res | page.parent_id.approver_group_ids page.approver_group_ids = res
[ "def", "_compute_approver_group_ids", "(", "self", ")", ":", "for", "page", "in", "self", ":", "res", "=", "page", ".", "approver_gid", "if", "page", ".", "parent_id", ":", "res", "=", "res", "|", "page", ".", "parent_id", ".", "approver_group_ids", "page", ".", "approver_group_ids", "=", "res" ]
Compute the approver groups based on his parents.
[ "Compute", "the", "approver", "groups", "based", "on", "his", "parents", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L86-L92
1,317
OCA/knowledge
document_page_approval/models/document_page.py
DocumentPage._compute_am_i_approver
def _compute_am_i_approver(self): """Check if the current user can approve changes to this page.""" for rec in self: rec.am_i_approver = rec.can_user_approve_this_page(self.env.user)
python
def _compute_am_i_approver(self): """Check if the current user can approve changes to this page.""" for rec in self: rec.am_i_approver = rec.can_user_approve_this_page(self.env.user)
[ "def", "_compute_am_i_approver", "(", "self", ")", ":", "for", "rec", "in", "self", ":", "rec", ".", "am_i_approver", "=", "rec", ".", "can_user_approve_this_page", "(", "self", ".", "env", ".", "user", ")" ]
Check if the current user can approve changes to this page.
[ "Check", "if", "the", "current", "user", "can", "approve", "changes", "to", "this", "page", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L96-L99
1,318
OCA/knowledge
document_page_approval/models/document_page.py
DocumentPage.can_user_approve_this_page
def can_user_approve_this_page(self, user): """Check if a user can approve this page.""" self.ensure_one() # if it's not required, anyone can approve if not self.is_approval_required: return True # if user belongs to 'Knowledge / Manager', he can approve anything if user.has_group('document_page.group_document_manager'): return True # to approve, user must have approver rights if not user.has_group( 'document_page_approval.group_document_approver_user'): return False # if there aren't any approver_groups_defined, user can approve if not self.approver_group_ids: return True # to approve, user must belong to any of the approver groups return len(user.groups_id & self.approver_group_ids) > 0
python
def can_user_approve_this_page(self, user): """Check if a user can approve this page.""" self.ensure_one() # if it's not required, anyone can approve if not self.is_approval_required: return True # if user belongs to 'Knowledge / Manager', he can approve anything if user.has_group('document_page.group_document_manager'): return True # to approve, user must have approver rights if not user.has_group( 'document_page_approval.group_document_approver_user'): return False # if there aren't any approver_groups_defined, user can approve if not self.approver_group_ids: return True # to approve, user must belong to any of the approver groups return len(user.groups_id & self.approver_group_ids) > 0
[ "def", "can_user_approve_this_page", "(", "self", ",", "user", ")", ":", "self", ".", "ensure_one", "(", ")", "# if it's not required, anyone can approve", "if", "not", "self", ".", "is_approval_required", ":", "return", "True", "# if user belongs to 'Knowledge / Manager', he can approve anything", "if", "user", ".", "has_group", "(", "'document_page.group_document_manager'", ")", ":", "return", "True", "# to approve, user must have approver rights", "if", "not", "user", ".", "has_group", "(", "'document_page_approval.group_document_approver_user'", ")", ":", "return", "False", "# if there aren't any approver_groups_defined, user can approve", "if", "not", "self", ".", "approver_group_ids", ":", "return", "True", "# to approve, user must belong to any of the approver groups", "return", "len", "(", "user", ".", "groups_id", "&", "self", ".", "approver_group_ids", ")", ">", "0" ]
Check if a user can approve this page.
[ "Check", "if", "a", "user", "can", "approve", "this", "page", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L102-L119
1,319
watchforstock/evohome-client
evohomeclient2/location.py
Location.status
def status(self): """Retrieves the location status.""" response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1/" "location/%s/status?includeTemperatureControlSystems=True" % self.locationId, headers=self.client._headers() # pylint: disable=protected-access ) response.raise_for_status() data = response.json() # Now feed into other elements for gw_data in data['gateways']: gateway = self.gateways[gw_data['gatewayId']] for sys in gw_data["temperatureControlSystems"]: system = gateway.control_systems[sys['systemId']] system.__dict__.update( {'systemModeStatus': sys['systemModeStatus'], 'activeFaults': sys['activeFaults']}) if 'dhw' in sys: system.hotwater.__dict__.update(sys['dhw']) for zone_data in sys["zones"]: zone = system.zones[zone_data['name']] zone.__dict__.update(zone_data) return data
python
def status(self): """Retrieves the location status.""" response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1/" "location/%s/status?includeTemperatureControlSystems=True" % self.locationId, headers=self.client._headers() # pylint: disable=protected-access ) response.raise_for_status() data = response.json() # Now feed into other elements for gw_data in data['gateways']: gateway = self.gateways[gw_data['gatewayId']] for sys in gw_data["temperatureControlSystems"]: system = gateway.control_systems[sys['systemId']] system.__dict__.update( {'systemModeStatus': sys['systemModeStatus'], 'activeFaults': sys['activeFaults']}) if 'dhw' in sys: system.hotwater.__dict__.update(sys['dhw']) for zone_data in sys["zones"]: zone = system.zones[zone_data['name']] zone.__dict__.update(zone_data) return data
[ "def", "status", "(", "self", ")", ":", "response", "=", "requests", ".", "get", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1/\"", "\"location/%s/status?includeTemperatureControlSystems=True\"", "%", "self", ".", "locationId", ",", "headers", "=", "self", ".", "client", ".", "_headers", "(", ")", "# pylint: disable=protected-access", ")", "response", ".", "raise_for_status", "(", ")", "data", "=", "response", ".", "json", "(", ")", "# Now feed into other elements", "for", "gw_data", "in", "data", "[", "'gateways'", "]", ":", "gateway", "=", "self", ".", "gateways", "[", "gw_data", "[", "'gatewayId'", "]", "]", "for", "sys", "in", "gw_data", "[", "\"temperatureControlSystems\"", "]", ":", "system", "=", "gateway", ".", "control_systems", "[", "sys", "[", "'systemId'", "]", "]", "system", ".", "__dict__", ".", "update", "(", "{", "'systemModeStatus'", ":", "sys", "[", "'systemModeStatus'", "]", ",", "'activeFaults'", ":", "sys", "[", "'activeFaults'", "]", "}", ")", "if", "'dhw'", "in", "sys", ":", "system", ".", "hotwater", ".", "__dict__", ".", "update", "(", "sys", "[", "'dhw'", "]", ")", "for", "zone_data", "in", "sys", "[", "\"zones\"", "]", ":", "zone", "=", "system", ".", "zones", "[", "zone_data", "[", "'name'", "]", "]", "zone", ".", "__dict__", ".", "update", "(", "zone_data", ")", "return", "data" ]
Retrieves the location status.
[ "Retrieves", "the", "location", "status", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/location.py#L26-L55
1,320
watchforstock/evohome-client
evohomeclient2/hotwater.py
HotWater.set_dhw_on
def set_dhw_on(self, until=None): """Sets the DHW on until a given time, or permanently.""" if until is None: data = {"Mode": "PermanentOverride", "State": "On", "UntilTime": None} else: data = {"Mode": "TemporaryOverride", "State": "On", "UntilTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_dhw(data)
python
def set_dhw_on(self, until=None): """Sets the DHW on until a given time, or permanently.""" if until is None: data = {"Mode": "PermanentOverride", "State": "On", "UntilTime": None} else: data = {"Mode": "TemporaryOverride", "State": "On", "UntilTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_dhw(data)
[ "def", "set_dhw_on", "(", "self", ",", "until", "=", "None", ")", ":", "if", "until", "is", "None", ":", "data", "=", "{", "\"Mode\"", ":", "\"PermanentOverride\"", ",", "\"State\"", ":", "\"On\"", ",", "\"UntilTime\"", ":", "None", "}", "else", ":", "data", "=", "{", "\"Mode\"", ":", "\"TemporaryOverride\"", ",", "\"State\"", ":", "\"On\"", ",", "\"UntilTime\"", ":", "until", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "}", "self", ".", "_set_dhw", "(", "data", ")" ]
Sets the DHW on until a given time, or permanently.
[ "Sets", "the", "DHW", "on", "until", "a", "given", "time", "or", "permanently", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/hotwater.py#L34-L45
1,321
watchforstock/evohome-client
evohomeclient2/hotwater.py
HotWater.set_dhw_off
def set_dhw_off(self, until=None): """Sets the DHW off until a given time, or permanently.""" if until is None: data = {"Mode": "PermanentOverride", "State": "Off", "UntilTime": None} else: data = {"Mode": "TemporaryOverride", "State": "Off", "UntilTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_dhw(data)
python
def set_dhw_off(self, until=None): """Sets the DHW off until a given time, or permanently.""" if until is None: data = {"Mode": "PermanentOverride", "State": "Off", "UntilTime": None} else: data = {"Mode": "TemporaryOverride", "State": "Off", "UntilTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_dhw(data)
[ "def", "set_dhw_off", "(", "self", ",", "until", "=", "None", ")", ":", "if", "until", "is", "None", ":", "data", "=", "{", "\"Mode\"", ":", "\"PermanentOverride\"", ",", "\"State\"", ":", "\"Off\"", ",", "\"UntilTime\"", ":", "None", "}", "else", ":", "data", "=", "{", "\"Mode\"", ":", "\"TemporaryOverride\"", ",", "\"State\"", ":", "\"Off\"", ",", "\"UntilTime\"", ":", "until", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "}", "self", ".", "_set_dhw", "(", "data", ")" ]
Sets the DHW off until a given time, or permanently.
[ "Sets", "the", "DHW", "off", "until", "a", "given", "time", "or", "permanently", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/hotwater.py#L47-L58
1,322
watchforstock/evohome-client
evohomeclient2/zone.py
ZoneBase.schedule
def schedule(self): """Gets the schedule for the given zone""" response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % (self.zone_type, self.zoneId), headers=self.client._headers() # pylint: disable=no-member,protected-access ) response.raise_for_status() mapping = [ ('dailySchedules', 'DailySchedules'), ('dayOfWeek', 'DayOfWeek'), ('temperature', 'TargetTemperature'), ('timeOfDay', 'TimeOfDay'), ('switchpoints', 'Switchpoints'), ('dhwState', 'DhwState'), ] response_data = response.text for from_val, to_val in mapping: response_data = response_data.replace(from_val, to_val) data = json.loads(response_data) # change the day name string to a number offset (0 = Monday) for day_of_week, schedule in enumerate(data['DailySchedules']): schedule['DayOfWeek'] = day_of_week return data
python
def schedule(self): """Gets the schedule for the given zone""" response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % (self.zone_type, self.zoneId), headers=self.client._headers() # pylint: disable=no-member,protected-access ) response.raise_for_status() mapping = [ ('dailySchedules', 'DailySchedules'), ('dayOfWeek', 'DayOfWeek'), ('temperature', 'TargetTemperature'), ('timeOfDay', 'TimeOfDay'), ('switchpoints', 'Switchpoints'), ('dhwState', 'DhwState'), ] response_data = response.text for from_val, to_val in mapping: response_data = response_data.replace(from_val, to_val) data = json.loads(response_data) # change the day name string to a number offset (0 = Monday) for day_of_week, schedule in enumerate(data['DailySchedules']): schedule['DayOfWeek'] = day_of_week return data
[ "def", "schedule", "(", "self", ")", ":", "response", "=", "requests", ".", "get", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1\"", "\"/%s/%s/schedule\"", "%", "(", "self", ".", "zone_type", ",", "self", ".", "zoneId", ")", ",", "headers", "=", "self", ".", "client", ".", "_headers", "(", ")", "# pylint: disable=no-member,protected-access", ")", "response", ".", "raise_for_status", "(", ")", "mapping", "=", "[", "(", "'dailySchedules'", ",", "'DailySchedules'", ")", ",", "(", "'dayOfWeek'", ",", "'DayOfWeek'", ")", ",", "(", "'temperature'", ",", "'TargetTemperature'", ")", ",", "(", "'timeOfDay'", ",", "'TimeOfDay'", ")", ",", "(", "'switchpoints'", ",", "'Switchpoints'", ")", ",", "(", "'dhwState'", ",", "'DhwState'", ")", ",", "]", "response_data", "=", "response", ".", "text", "for", "from_val", ",", "to_val", "in", "mapping", ":", "response_data", "=", "response_data", ".", "replace", "(", "from_val", ",", "to_val", ")", "data", "=", "json", ".", "loads", "(", "response_data", ")", "# change the day name string to a number offset (0 = Monday)", "for", "day_of_week", ",", "schedule", "in", "enumerate", "(", "data", "[", "'DailySchedules'", "]", ")", ":", "schedule", "[", "'DayOfWeek'", "]", "=", "day_of_week", "return", "data" ]
Gets the schedule for the given zone
[ "Gets", "the", "schedule", "for", "the", "given", "zone" ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/zone.py#L16-L42
1,323
watchforstock/evohome-client
evohomeclient2/zone.py
ZoneBase.set_schedule
def set_schedule(self, zone_info): """Sets the schedule for this zone""" # must only POST json, otherwise server API handler raises exceptions try: json.loads(zone_info) except ValueError as error: raise ValueError("zone_info must be valid JSON: ", error) headers = dict(self.client._headers()) # pylint: disable=protected-access headers['Content-Type'] = 'application/json' response = requests.put( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % (self.zone_type, self.zoneId), data=zone_info, headers=headers ) response.raise_for_status() return response.json()
python
def set_schedule(self, zone_info): """Sets the schedule for this zone""" # must only POST json, otherwise server API handler raises exceptions try: json.loads(zone_info) except ValueError as error: raise ValueError("zone_info must be valid JSON: ", error) headers = dict(self.client._headers()) # pylint: disable=protected-access headers['Content-Type'] = 'application/json' response = requests.put( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % (self.zone_type, self.zoneId), data=zone_info, headers=headers ) response.raise_for_status() return response.json()
[ "def", "set_schedule", "(", "self", ",", "zone_info", ")", ":", "# must only POST json, otherwise server API handler raises exceptions", "try", ":", "json", ".", "loads", "(", "zone_info", ")", "except", "ValueError", "as", "error", ":", "raise", "ValueError", "(", "\"zone_info must be valid JSON: \"", ",", "error", ")", "headers", "=", "dict", "(", "self", ".", "client", ".", "_headers", "(", ")", ")", "# pylint: disable=protected-access", "headers", "[", "'Content-Type'", "]", "=", "'application/json'", "response", "=", "requests", ".", "put", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1\"", "\"/%s/%s/schedule\"", "%", "(", "self", ".", "zone_type", ",", "self", ".", "zoneId", ")", ",", "data", "=", "zone_info", ",", "headers", "=", "headers", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "json", "(", ")" ]
Sets the schedule for this zone
[ "Sets", "the", "schedule", "for", "this", "zone" ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/zone.py#L44-L63
1,324
watchforstock/evohome-client
evohomeclient/__init__.py
EvohomeClient.temperatures
def temperatures(self, force_refresh=False): """Retrieve the current details for each zone. Returns a generator.""" self._populate_full_data(force_refresh) for device in self.full_data['devices']: set_point = 0 status = "" if 'heatSetpoint' in device['thermostat']['changeableValues']: set_point = float( device['thermostat']['changeableValues']["heatSetpoint"]["value"]) status = device['thermostat']['changeableValues']["heatSetpoint"]["status"] else: status = device['thermostat']['changeableValues']['status'] yield {'thermostat': device['thermostatModelType'], 'id': device['deviceID'], 'name': device['name'], 'temp': float(device['thermostat']['indoorTemperature']), 'setpoint': set_point, 'status': status, 'mode': device['thermostat']['changeableValues']['mode']}
python
def temperatures(self, force_refresh=False): """Retrieve the current details for each zone. Returns a generator.""" self._populate_full_data(force_refresh) for device in self.full_data['devices']: set_point = 0 status = "" if 'heatSetpoint' in device['thermostat']['changeableValues']: set_point = float( device['thermostat']['changeableValues']["heatSetpoint"]["value"]) status = device['thermostat']['changeableValues']["heatSetpoint"]["status"] else: status = device['thermostat']['changeableValues']['status'] yield {'thermostat': device['thermostatModelType'], 'id': device['deviceID'], 'name': device['name'], 'temp': float(device['thermostat']['indoorTemperature']), 'setpoint': set_point, 'status': status, 'mode': device['thermostat']['changeableValues']['mode']}
[ "def", "temperatures", "(", "self", ",", "force_refresh", "=", "False", ")", ":", "self", ".", "_populate_full_data", "(", "force_refresh", ")", "for", "device", "in", "self", ".", "full_data", "[", "'devices'", "]", ":", "set_point", "=", "0", "status", "=", "\"\"", "if", "'heatSetpoint'", "in", "device", "[", "'thermostat'", "]", "[", "'changeableValues'", "]", ":", "set_point", "=", "float", "(", "device", "[", "'thermostat'", "]", "[", "'changeableValues'", "]", "[", "\"heatSetpoint\"", "]", "[", "\"value\"", "]", ")", "status", "=", "device", "[", "'thermostat'", "]", "[", "'changeableValues'", "]", "[", "\"heatSetpoint\"", "]", "[", "\"status\"", "]", "else", ":", "status", "=", "device", "[", "'thermostat'", "]", "[", "'changeableValues'", "]", "[", "'status'", "]", "yield", "{", "'thermostat'", ":", "device", "[", "'thermostatModelType'", "]", ",", "'id'", ":", "device", "[", "'deviceID'", "]", ",", "'name'", ":", "device", "[", "'name'", "]", ",", "'temp'", ":", "float", "(", "device", "[", "'thermostat'", "]", "[", "'indoorTemperature'", "]", ")", ",", "'setpoint'", ":", "set_point", ",", "'status'", ":", "status", ",", "'mode'", ":", "device", "[", "'thermostat'", "]", "[", "'changeableValues'", "]", "[", "'mode'", "]", "}" ]
Retrieve the current details for each zone. Returns a generator.
[ "Retrieve", "the", "current", "details", "for", "each", "zone", ".", "Returns", "a", "generator", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L115-L133
1,325
watchforstock/evohome-client
evohomeclient/__init__.py
EvohomeClient.get_modes
def get_modes(self, zone): """Returns the set of modes the device can be assigned.""" self._populate_full_data() device = self._get_device(zone) return device['thermostat']['allowedModes']
python
def get_modes(self, zone): """Returns the set of modes the device can be assigned.""" self._populate_full_data() device = self._get_device(zone) return device['thermostat']['allowedModes']
[ "def", "get_modes", "(", "self", ",", "zone", ")", ":", "self", ".", "_populate_full_data", "(", ")", "device", "=", "self", ".", "_get_device", "(", "zone", ")", "return", "device", "[", "'thermostat'", "]", "[", "'allowedModes'", "]" ]
Returns the set of modes the device can be assigned.
[ "Returns", "the", "set", "of", "modes", "the", "device", "can", "be", "assigned", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L135-L139
1,326
watchforstock/evohome-client
evohomeclient/__init__.py
EvohomeClient.set_temperature
def set_temperature(self, zone, temperature, until=None): """Sets the temperature of the given zone.""" if until is None: data = {"Value": temperature, "Status": "Hold", "NextTime": None} else: data = {"Value": temperature, "Status": "Temporary", "NextTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_heat_setpoint(zone, data)
python
def set_temperature(self, zone, temperature, until=None): """Sets the temperature of the given zone.""" if until is None: data = {"Value": temperature, "Status": "Hold", "NextTime": None} else: data = {"Value": temperature, "Status": "Temporary", "NextTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_heat_setpoint(zone, data)
[ "def", "set_temperature", "(", "self", ",", "zone", ",", "temperature", ",", "until", "=", "None", ")", ":", "if", "until", "is", "None", ":", "data", "=", "{", "\"Value\"", ":", "temperature", ",", "\"Status\"", ":", "\"Hold\"", ",", "\"NextTime\"", ":", "None", "}", "else", ":", "data", "=", "{", "\"Value\"", ":", "temperature", ",", "\"Status\"", ":", "\"Temporary\"", ",", "\"NextTime\"", ":", "until", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "}", "self", ".", "_set_heat_setpoint", "(", "zone", ",", "data", ")" ]
Sets the temperature of the given zone.
[ "Sets", "the", "temperature", "of", "the", "given", "zone", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L266-L275
1,327
watchforstock/evohome-client
evohomeclient/__init__.py
EvohomeClient._set_dhw
def _set_dhw(self, status="Scheduled", mode=None, next_time=None): """Set DHW to On, Off or Auto, either indefinitely, or until a specified time. """ data = {"Status": status, "Mode": mode, "NextTime": next_time, "SpecialModes": None, "HeatSetpoint": None, "CoolSetpoint": None} self._populate_full_data() dhw_zone = self._get_dhw_zone() if dhw_zone is None: raise Exception('No DHW zone reported from API') url = (self.hostname + "/WebAPI/api/devices" "/%s/thermostat/changeableValues" % dhw_zone) response = self._do_request('put', url, json.dumps(data)) task_id = self._get_task_id(response) while self._get_task_status(task_id) != 'Succeeded': time.sleep(1)
python
def _set_dhw(self, status="Scheduled", mode=None, next_time=None): """Set DHW to On, Off or Auto, either indefinitely, or until a specified time. """ data = {"Status": status, "Mode": mode, "NextTime": next_time, "SpecialModes": None, "HeatSetpoint": None, "CoolSetpoint": None} self._populate_full_data() dhw_zone = self._get_dhw_zone() if dhw_zone is None: raise Exception('No DHW zone reported from API') url = (self.hostname + "/WebAPI/api/devices" "/%s/thermostat/changeableValues" % dhw_zone) response = self._do_request('put', url, json.dumps(data)) task_id = self._get_task_id(response) while self._get_task_status(task_id) != 'Succeeded': time.sleep(1)
[ "def", "_set_dhw", "(", "self", ",", "status", "=", "\"Scheduled\"", ",", "mode", "=", "None", ",", "next_time", "=", "None", ")", ":", "data", "=", "{", "\"Status\"", ":", "status", ",", "\"Mode\"", ":", "mode", ",", "\"NextTime\"", ":", "next_time", ",", "\"SpecialModes\"", ":", "None", ",", "\"HeatSetpoint\"", ":", "None", ",", "\"CoolSetpoint\"", ":", "None", "}", "self", ".", "_populate_full_data", "(", ")", "dhw_zone", "=", "self", ".", "_get_dhw_zone", "(", ")", "if", "dhw_zone", "is", "None", ":", "raise", "Exception", "(", "'No DHW zone reported from API'", ")", "url", "=", "(", "self", ".", "hostname", "+", "\"/WebAPI/api/devices\"", "\"/%s/thermostat/changeableValues\"", "%", "dhw_zone", ")", "response", "=", "self", ".", "_do_request", "(", "'put'", ",", "url", ",", "json", ".", "dumps", "(", "data", ")", ")", "task_id", "=", "self", ".", "_get_task_id", "(", "response", ")", "while", "self", ".", "_get_task_status", "(", "task_id", ")", "!=", "'Succeeded'", ":", "time", ".", "sleep", "(", "1", ")" ]
Set DHW to On, Off or Auto, either indefinitely, or until a specified time.
[ "Set", "DHW", "to", "On", "Off", "or", "Auto", "either", "indefinitely", "or", "until", "a", "specified", "time", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L288-L311
1,328
watchforstock/evohome-client
evohomeclient/__init__.py
EvohomeClient.set_dhw_on
def set_dhw_on(self, until=None): """Set DHW to on, either indefinitely, or until a specified time. When On, the DHW controller will work to keep its target temperature at/above its target temperature. After the specified time, it will revert to its scheduled behaviour. """ time_until = None if until is None else until.strftime( '%Y-%m-%dT%H:%M:%SZ') self._set_dhw(status="Hold", mode="DHWOn", next_time=time_until)
python
def set_dhw_on(self, until=None): """Set DHW to on, either indefinitely, or until a specified time. When On, the DHW controller will work to keep its target temperature at/above its target temperature. After the specified time, it will revert to its scheduled behaviour. """ time_until = None if until is None else until.strftime( '%Y-%m-%dT%H:%M:%SZ') self._set_dhw(status="Hold", mode="DHWOn", next_time=time_until)
[ "def", "set_dhw_on", "(", "self", ",", "until", "=", "None", ")", ":", "time_until", "=", "None", "if", "until", "is", "None", "else", "until", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "self", ".", "_set_dhw", "(", "status", "=", "\"Hold\"", ",", "mode", "=", "\"DHWOn\"", ",", "next_time", "=", "time_until", ")" ]
Set DHW to on, either indefinitely, or until a specified time. When On, the DHW controller will work to keep its target temperature at/above its target temperature. After the specified time, it will revert to its scheduled behaviour.
[ "Set", "DHW", "to", "on", "either", "indefinitely", "or", "until", "a", "specified", "time", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L313-L324
1,329
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient._headers
def _headers(self): """Ensure the Authorization Header has a valid Access Token.""" if not self.access_token or not self.access_token_expires: self._basic_login() elif datetime.now() > self.access_token_expires - timedelta(seconds=30): self._basic_login() return {'Accept': HEADER_ACCEPT, 'Authorization': 'bearer ' + self.access_token}
python
def _headers(self): """Ensure the Authorization Header has a valid Access Token.""" if not self.access_token or not self.access_token_expires: self._basic_login() elif datetime.now() > self.access_token_expires - timedelta(seconds=30): self._basic_login() return {'Accept': HEADER_ACCEPT, 'Authorization': 'bearer ' + self.access_token}
[ "def", "_headers", "(", "self", ")", ":", "if", "not", "self", ".", "access_token", "or", "not", "self", ".", "access_token_expires", ":", "self", ".", "_basic_login", "(", ")", "elif", "datetime", ".", "now", "(", ")", ">", "self", ".", "access_token_expires", "-", "timedelta", "(", "seconds", "=", "30", ")", ":", "self", ".", "_basic_login", "(", ")", "return", "{", "'Accept'", ":", "HEADER_ACCEPT", ",", "'Authorization'", ":", "'bearer '", "+", "self", ".", "access_token", "}" ]
Ensure the Authorization Header has a valid Access Token.
[ "Ensure", "the", "Authorization", "Header", "has", "a", "valid", "Access", "Token", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L84-L93
1,330
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient._basic_login
def _basic_login(self): """Obtain a new access token from the vendor. First, try using the refresh_token, if one is available, otherwise authenticate using the user credentials. """ _LOGGER.debug("No/Expired/Invalid access_token, re-authenticating...") self.access_token = self.access_token_expires = None if self.refresh_token: _LOGGER.debug("Trying refresh_token...") credentials = {'grant_type': "refresh_token", 'scope': "EMEA-V1-Basic EMEA-V1-Anonymous", 'refresh_token': self.refresh_token} try: self._obtain_access_token(credentials) except (requests.HTTPError, KeyError, ValueError): _LOGGER.warning( "Invalid refresh_token, will try user credentials.") self.refresh_token = None if not self.refresh_token: _LOGGER.debug("Trying user credentials...") credentials = {'grant_type': "password", 'scope': "EMEA-V1-Basic EMEA-V1-Anonymous " "EMEA-V1-Get-Current-User-Account", 'Username': self.username, 'Password': self.password} self._obtain_access_token(credentials) _LOGGER.debug("refresh_token = %s", self.refresh_token) _LOGGER.debug("access_token = %s", self.access_token) _LOGGER.debug("access_token_expires = %s", self.access_token_expires.strftime("%Y-%m-%d %H:%M:%S"))
python
def _basic_login(self): """Obtain a new access token from the vendor. First, try using the refresh_token, if one is available, otherwise authenticate using the user credentials. """ _LOGGER.debug("No/Expired/Invalid access_token, re-authenticating...") self.access_token = self.access_token_expires = None if self.refresh_token: _LOGGER.debug("Trying refresh_token...") credentials = {'grant_type': "refresh_token", 'scope': "EMEA-V1-Basic EMEA-V1-Anonymous", 'refresh_token': self.refresh_token} try: self._obtain_access_token(credentials) except (requests.HTTPError, KeyError, ValueError): _LOGGER.warning( "Invalid refresh_token, will try user credentials.") self.refresh_token = None if not self.refresh_token: _LOGGER.debug("Trying user credentials...") credentials = {'grant_type': "password", 'scope': "EMEA-V1-Basic EMEA-V1-Anonymous " "EMEA-V1-Get-Current-User-Account", 'Username': self.username, 'Password': self.password} self._obtain_access_token(credentials) _LOGGER.debug("refresh_token = %s", self.refresh_token) _LOGGER.debug("access_token = %s", self.access_token) _LOGGER.debug("access_token_expires = %s", self.access_token_expires.strftime("%Y-%m-%d %H:%M:%S"))
[ "def", "_basic_login", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"No/Expired/Invalid access_token, re-authenticating...\"", ")", "self", ".", "access_token", "=", "self", ".", "access_token_expires", "=", "None", "if", "self", ".", "refresh_token", ":", "_LOGGER", ".", "debug", "(", "\"Trying refresh_token...\"", ")", "credentials", "=", "{", "'grant_type'", ":", "\"refresh_token\"", ",", "'scope'", ":", "\"EMEA-V1-Basic EMEA-V1-Anonymous\"", ",", "'refresh_token'", ":", "self", ".", "refresh_token", "}", "try", ":", "self", ".", "_obtain_access_token", "(", "credentials", ")", "except", "(", "requests", ".", "HTTPError", ",", "KeyError", ",", "ValueError", ")", ":", "_LOGGER", ".", "warning", "(", "\"Invalid refresh_token, will try user credentials.\"", ")", "self", ".", "refresh_token", "=", "None", "if", "not", "self", ".", "refresh_token", ":", "_LOGGER", ".", "debug", "(", "\"Trying user credentials...\"", ")", "credentials", "=", "{", "'grant_type'", ":", "\"password\"", ",", "'scope'", ":", "\"EMEA-V1-Basic EMEA-V1-Anonymous \"", "\"EMEA-V1-Get-Current-User-Account\"", ",", "'Username'", ":", "self", ".", "username", ",", "'Password'", ":", "self", ".", "password", "}", "self", ".", "_obtain_access_token", "(", "credentials", ")", "_LOGGER", ".", "debug", "(", "\"refresh_token = %s\"", ",", "self", ".", "refresh_token", ")", "_LOGGER", ".", "debug", "(", "\"access_token = %s\"", ",", "self", ".", "access_token", ")", "_LOGGER", ".", "debug", "(", "\"access_token_expires = %s\"", ",", "self", ".", "access_token_expires", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ")", ")" ]
Obtain a new access token from the vendor. First, try using the refresh_token, if one is available, otherwise authenticate using the user credentials.
[ "Obtain", "a", "new", "access", "token", "from", "the", "vendor", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L95-L130
1,331
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient.user_account
def user_account(self): """Return the user account information.""" self.account_info = None url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount' response = requests.get(url, headers=self._headers()) response.raise_for_status() self.account_info = response.json() return self.account_info
python
def user_account(self): """Return the user account information.""" self.account_info = None url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount' response = requests.get(url, headers=self._headers()) response.raise_for_status() self.account_info = response.json() return self.account_info
[ "def", "user_account", "(", "self", ")", ":", "self", ".", "account_info", "=", "None", "url", "=", "'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount'", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "self", ".", "account_info", "=", "response", ".", "json", "(", ")", "return", "self", ".", "account_info" ]
Return the user account information.
[ "Return", "the", "user", "account", "information", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L192-L202
1,332
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient.installation
def installation(self): """Return the details of the installation.""" self.locations = [] url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/installationInfo?userId=%s" "&includeTemperatureControlSystems=True" % self.account_info['userId']) response = requests.get(url, headers=self._headers()) response.raise_for_status() self.installation_info = response.json() self.system_id = (self.installation_info[0]['gateways'][0] ['temperatureControlSystems'][0]['systemId']) for loc_data in self.installation_info: self.locations.append(Location(self, loc_data)) return self.installation_info
python
def installation(self): """Return the details of the installation.""" self.locations = [] url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/installationInfo?userId=%s" "&includeTemperatureControlSystems=True" % self.account_info['userId']) response = requests.get(url, headers=self._headers()) response.raise_for_status() self.installation_info = response.json() self.system_id = (self.installation_info[0]['gateways'][0] ['temperatureControlSystems'][0]['systemId']) for loc_data in self.installation_info: self.locations.append(Location(self, loc_data)) return self.installation_info
[ "def", "installation", "(", "self", ")", ":", "self", ".", "locations", "=", "[", "]", "url", "=", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1/location\"", "\"/installationInfo?userId=%s\"", "\"&includeTemperatureControlSystems=True\"", "%", "self", ".", "account_info", "[", "'userId'", "]", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "self", ".", "installation_info", "=", "response", ".", "json", "(", ")", "self", ".", "system_id", "=", "(", "self", ".", "installation_info", "[", "0", "]", "[", "'gateways'", "]", "[", "0", "]", "[", "'temperatureControlSystems'", "]", "[", "0", "]", "[", "'systemId'", "]", ")", "for", "loc_data", "in", "self", ".", "installation_info", ":", "self", ".", "locations", ".", "append", "(", "Location", "(", "self", ",", "loc_data", ")", ")", "return", "self", ".", "installation_info" ]
Return the details of the installation.
[ "Return", "the", "details", "of", "the", "installation", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L204-L223
1,333
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient.full_installation
def full_installation(self, location=None): """Return the full details of the installation.""" url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/%s/installationInfo?includeTemperatureControlSystems=True" % self._get_location(location)) response = requests.get(url, headers=self._headers()) response.raise_for_status() return response.json()
python
def full_installation(self, location=None): """Return the full details of the installation.""" url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/%s/installationInfo?includeTemperatureControlSystems=True" % self._get_location(location)) response = requests.get(url, headers=self._headers()) response.raise_for_status() return response.json()
[ "def", "full_installation", "(", "self", ",", "location", "=", "None", ")", ":", "url", "=", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1/location\"", "\"/%s/installationInfo?includeTemperatureControlSystems=True\"", "%", "self", ".", "_get_location", "(", "location", ")", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "json", "(", ")" ]
Return the full details of the installation.
[ "Return", "the", "full", "details", "of", "the", "installation", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L225-L234
1,334
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient.gateway
def gateway(self): """Return the detail of the gateway.""" url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway' response = requests.get(url, headers=self._headers()) response.raise_for_status() return response.json()
python
def gateway(self): """Return the detail of the gateway.""" url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway' response = requests.get(url, headers=self._headers()) response.raise_for_status() return response.json()
[ "def", "gateway", "(", "self", ")", ":", "url", "=", "'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway'", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "json", "(", ")" ]
Return the detail of the gateway.
[ "Return", "the", "detail", "of", "the", "gateway", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L236-L243
1,335
watchforstock/evohome-client
evohomeclient2/controlsystem.py
ControlSystem.temperatures
def temperatures(self): """Return a generator with the details of each zone.""" self.location.status() if self.hotwater: yield { 'thermostat': 'DOMESTIC_HOT_WATER', 'id': self.hotwater.dhwId, 'name': '', 'temp': self.hotwater.temperatureStatus['temperature'], # pylint: disable=no-member 'setpoint': '' } for zone in self._zones: zone_info = { 'thermostat': 'EMEA_ZONE', 'id': zone.zoneId, 'name': zone.name, 'temp': None, 'setpoint': zone.setpointStatus['targetHeatTemperature'] } if zone.temperatureStatus['isAvailable']: zone_info['temp'] = zone.temperatureStatus['temperature'] yield zone_info
python
def temperatures(self): """Return a generator with the details of each zone.""" self.location.status() if self.hotwater: yield { 'thermostat': 'DOMESTIC_HOT_WATER', 'id': self.hotwater.dhwId, 'name': '', 'temp': self.hotwater.temperatureStatus['temperature'], # pylint: disable=no-member 'setpoint': '' } for zone in self._zones: zone_info = { 'thermostat': 'EMEA_ZONE', 'id': zone.zoneId, 'name': zone.name, 'temp': None, 'setpoint': zone.setpointStatus['targetHeatTemperature'] } if zone.temperatureStatus['isAvailable']: zone_info['temp'] = zone.temperatureStatus['temperature'] yield zone_info
[ "def", "temperatures", "(", "self", ")", ":", "self", ".", "location", ".", "status", "(", ")", "if", "self", ".", "hotwater", ":", "yield", "{", "'thermostat'", ":", "'DOMESTIC_HOT_WATER'", ",", "'id'", ":", "self", ".", "hotwater", ".", "dhwId", ",", "'name'", ":", "''", ",", "'temp'", ":", "self", ".", "hotwater", ".", "temperatureStatus", "[", "'temperature'", "]", ",", "# pylint: disable=no-member", "'setpoint'", ":", "''", "}", "for", "zone", "in", "self", ".", "_zones", ":", "zone_info", "=", "{", "'thermostat'", ":", "'EMEA_ZONE'", ",", "'id'", ":", "zone", ".", "zoneId", ",", "'name'", ":", "zone", ".", "name", ",", "'temp'", ":", "None", ",", "'setpoint'", ":", "zone", ".", "setpointStatus", "[", "'targetHeatTemperature'", "]", "}", "if", "zone", ".", "temperatureStatus", "[", "'isAvailable'", "]", ":", "zone_info", "[", "'temp'", "]", "=", "zone", ".", "temperatureStatus", "[", "'temperature'", "]", "yield", "zone_info" ]
Return a generator with the details of each zone.
[ "Return", "a", "generator", "with", "the", "details", "of", "each", "zone", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L92-L116
1,336
watchforstock/evohome-client
evohomeclient2/controlsystem.py
ControlSystem.zone_schedules_backup
def zone_schedules_backup(self, filename): """Backup all zones on control system to the given file.""" _LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...", self.systemId, self.location.name) schedules = {} if self.hotwater: _LOGGER.info("Retrieving DHW schedule: %s...", self.hotwater.zoneId) schedule = self.hotwater.schedule() schedules[self.hotwater.zoneId] = { 'name': 'Domestic Hot Water', 'schedule': schedule} for zone in self._zones: zone_id = zone.zoneId name = zone.name _LOGGER.info("Retrieving Zone schedule: %s - %s", zone_id, name) schedule = zone.schedule() schedules[zone_id] = {'name': name, 'schedule': schedule} schedule_db = json.dumps(schedules, indent=4) _LOGGER.info("Writing to backup file: %s...", filename) with open(filename, 'w') as file_output: file_output.write(schedule_db) _LOGGER.info("Backup completed.")
python
def zone_schedules_backup(self, filename): """Backup all zones on control system to the given file.""" _LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...", self.systemId, self.location.name) schedules = {} if self.hotwater: _LOGGER.info("Retrieving DHW schedule: %s...", self.hotwater.zoneId) schedule = self.hotwater.schedule() schedules[self.hotwater.zoneId] = { 'name': 'Domestic Hot Water', 'schedule': schedule} for zone in self._zones: zone_id = zone.zoneId name = zone.name _LOGGER.info("Retrieving Zone schedule: %s - %s", zone_id, name) schedule = zone.schedule() schedules[zone_id] = {'name': name, 'schedule': schedule} schedule_db = json.dumps(schedules, indent=4) _LOGGER.info("Writing to backup file: %s...", filename) with open(filename, 'w') as file_output: file_output.write(schedule_db) _LOGGER.info("Backup completed.")
[ "def", "zone_schedules_backup", "(", "self", ",", "filename", ")", ":", "_LOGGER", ".", "info", "(", "\"Backing up schedules from ControlSystem: %s (%s)...\"", ",", "self", ".", "systemId", ",", "self", ".", "location", ".", "name", ")", "schedules", "=", "{", "}", "if", "self", ".", "hotwater", ":", "_LOGGER", ".", "info", "(", "\"Retrieving DHW schedule: %s...\"", ",", "self", ".", "hotwater", ".", "zoneId", ")", "schedule", "=", "self", ".", "hotwater", ".", "schedule", "(", ")", "schedules", "[", "self", ".", "hotwater", ".", "zoneId", "]", "=", "{", "'name'", ":", "'Domestic Hot Water'", ",", "'schedule'", ":", "schedule", "}", "for", "zone", "in", "self", ".", "_zones", ":", "zone_id", "=", "zone", ".", "zoneId", "name", "=", "zone", ".", "name", "_LOGGER", ".", "info", "(", "\"Retrieving Zone schedule: %s - %s\"", ",", "zone_id", ",", "name", ")", "schedule", "=", "zone", ".", "schedule", "(", ")", "schedules", "[", "zone_id", "]", "=", "{", "'name'", ":", "name", ",", "'schedule'", ":", "schedule", "}", "schedule_db", "=", "json", ".", "dumps", "(", "schedules", ",", "indent", "=", "4", ")", "_LOGGER", ".", "info", "(", "\"Writing to backup file: %s...\"", ",", "filename", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "file_output", ":", "file_output", ".", "write", "(", "schedule_db", ")", "_LOGGER", ".", "info", "(", "\"Backup completed.\"", ")" ]
Backup all zones on control system to the given file.
[ "Backup", "all", "zones", "on", "control", "system", "to", "the", "given", "file", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L118-L149
1,337
watchforstock/evohome-client
evohomeclient2/controlsystem.py
ControlSystem.zone_schedules_restore
def zone_schedules_restore(self, filename): """Restore all zones on control system from the given file.""" _LOGGER.info("Restoring schedules to ControlSystem %s (%s)...", self.systemId, self.location) _LOGGER.info("Reading from backup file: %s...", filename) with open(filename, 'r') as file_input: schedule_db = file_input.read() schedules = json.loads(schedule_db) for zone_id, zone_schedule in schedules.items(): name = zone_schedule['name'] zone_info = zone_schedule['schedule'] _LOGGER.info("Restoring schedule for: %s - %s...", zone_id, name) if self.hotwater and self.hotwater.zoneId == zone_id: self.hotwater.set_schedule(json.dumps(zone_info)) else: self.zones_by_id[zone_id].set_schedule( json.dumps(zone_info)) _LOGGER.info("Restore completed.")
python
def zone_schedules_restore(self, filename): """Restore all zones on control system from the given file.""" _LOGGER.info("Restoring schedules to ControlSystem %s (%s)...", self.systemId, self.location) _LOGGER.info("Reading from backup file: %s...", filename) with open(filename, 'r') as file_input: schedule_db = file_input.read() schedules = json.loads(schedule_db) for zone_id, zone_schedule in schedules.items(): name = zone_schedule['name'] zone_info = zone_schedule['schedule'] _LOGGER.info("Restoring schedule for: %s - %s...", zone_id, name) if self.hotwater and self.hotwater.zoneId == zone_id: self.hotwater.set_schedule(json.dumps(zone_info)) else: self.zones_by_id[zone_id].set_schedule( json.dumps(zone_info)) _LOGGER.info("Restore completed.")
[ "def", "zone_schedules_restore", "(", "self", ",", "filename", ")", ":", "_LOGGER", ".", "info", "(", "\"Restoring schedules to ControlSystem %s (%s)...\"", ",", "self", ".", "systemId", ",", "self", ".", "location", ")", "_LOGGER", ".", "info", "(", "\"Reading from backup file: %s...\"", ",", "filename", ")", "with", "open", "(", "filename", ",", "'r'", ")", "as", "file_input", ":", "schedule_db", "=", "file_input", ".", "read", "(", ")", "schedules", "=", "json", ".", "loads", "(", "schedule_db", ")", "for", "zone_id", ",", "zone_schedule", "in", "schedules", ".", "items", "(", ")", ":", "name", "=", "zone_schedule", "[", "'name'", "]", "zone_info", "=", "zone_schedule", "[", "'schedule'", "]", "_LOGGER", ".", "info", "(", "\"Restoring schedule for: %s - %s...\"", ",", "zone_id", ",", "name", ")", "if", "self", ".", "hotwater", "and", "self", ".", "hotwater", ".", "zoneId", "==", "zone_id", ":", "self", ".", "hotwater", ".", "set_schedule", "(", "json", ".", "dumps", "(", "zone_info", ")", ")", "else", ":", "self", ".", "zones_by_id", "[", "zone_id", "]", ".", "set_schedule", "(", "json", ".", "dumps", "(", "zone_info", ")", ")", "_LOGGER", ".", "info", "(", "\"Restore completed.\"", ")" ]
Restore all zones on control system from the given file.
[ "Restore", "all", "zones", "on", "control", "system", "from", "the", "given", "file", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L151-L174
1,338
softlayer/softlayer-python
SoftLayer/CLI/order/item_list.py
cli
def cli(env, package_keyname, keyword, category): """List package items used for ordering. The item keyNames listed can be used with `slcli order place` to specify the items that are being ordered in the package. .. Note:: Items with a numbered category, like disk0 or gpu0, can be included multiple times in an order to match how many of the item you want to order. :: # List all items in the VSI package slcli order item-list CLOUD_SERVER # List Ubuntu OSes from the os category of the Bare Metal package slcli order item-list BARE_METAL_SERVER --category os --keyword ubuntu """ table = formatting.Table(COLUMNS) manager = ordering.OrderingManager(env.client) _filter = {'items': {}} if keyword: _filter['items']['description'] = {'operation': '*= %s' % keyword} if category: _filter['items']['categories'] = {'categoryCode': {'operation': '_= %s' % category}} items = manager.list_items(package_keyname, filter=_filter) sorted_items = sort_items(items) categories = sorted_items.keys() for catname in sorted(categories): for item in sorted_items[catname]: table.add_row([catname, item['keyName'], item['description'], get_price(item)]) env.fout(table)
python
def cli(env, package_keyname, keyword, category): """List package items used for ordering. The item keyNames listed can be used with `slcli order place` to specify the items that are being ordered in the package. .. Note:: Items with a numbered category, like disk0 or gpu0, can be included multiple times in an order to match how many of the item you want to order. :: # List all items in the VSI package slcli order item-list CLOUD_SERVER # List Ubuntu OSes from the os category of the Bare Metal package slcli order item-list BARE_METAL_SERVER --category os --keyword ubuntu """ table = formatting.Table(COLUMNS) manager = ordering.OrderingManager(env.client) _filter = {'items': {}} if keyword: _filter['items']['description'] = {'operation': '*= %s' % keyword} if category: _filter['items']['categories'] = {'categoryCode': {'operation': '_= %s' % category}} items = manager.list_items(package_keyname, filter=_filter) sorted_items = sort_items(items) categories = sorted_items.keys() for catname in sorted(categories): for item in sorted_items[catname]: table.add_row([catname, item['keyName'], item['description'], get_price(item)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "package_keyname", ",", "keyword", ",", "category", ")", ":", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "_filter", "=", "{", "'items'", ":", "{", "}", "}", "if", "keyword", ":", "_filter", "[", "'items'", "]", "[", "'description'", "]", "=", "{", "'operation'", ":", "'*= %s'", "%", "keyword", "}", "if", "category", ":", "_filter", "[", "'items'", "]", "[", "'categories'", "]", "=", "{", "'categoryCode'", ":", "{", "'operation'", ":", "'_= %s'", "%", "category", "}", "}", "items", "=", "manager", ".", "list_items", "(", "package_keyname", ",", "filter", "=", "_filter", ")", "sorted_items", "=", "sort_items", "(", "items", ")", "categories", "=", "sorted_items", ".", "keys", "(", ")", "for", "catname", "in", "sorted", "(", "categories", ")", ":", "for", "item", "in", "sorted_items", "[", "catname", "]", ":", "table", ".", "add_row", "(", "[", "catname", ",", "item", "[", "'keyName'", "]", ",", "item", "[", "'description'", "]", ",", "get_price", "(", "item", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List package items used for ordering. The item keyNames listed can be used with `slcli order place` to specify the items that are being ordered in the package. .. Note:: Items with a numbered category, like disk0 or gpu0, can be included multiple times in an order to match how many of the item you want to order. :: # List all items in the VSI package slcli order item-list CLOUD_SERVER # List Ubuntu OSes from the os category of the Bare Metal package slcli order item-list BARE_METAL_SERVER --category os --keyword ubuntu
[ "List", "package", "items", "used", "for", "ordering", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/item_list.py#L18-L53
1,339
softlayer/softlayer-python
SoftLayer/CLI/order/item_list.py
sort_items
def sort_items(items): """sorts the items into a dictionary of categories, with a list of items""" sorted_items = {} for item in items: category = lookup(item, 'itemCategory', 'categoryCode') if sorted_items.get(category) is None: sorted_items[category] = [] sorted_items[category].append(item) return sorted_items
python
def sort_items(items): """sorts the items into a dictionary of categories, with a list of items""" sorted_items = {} for item in items: category = lookup(item, 'itemCategory', 'categoryCode') if sorted_items.get(category) is None: sorted_items[category] = [] sorted_items[category].append(item) return sorted_items
[ "def", "sort_items", "(", "items", ")", ":", "sorted_items", "=", "{", "}", "for", "item", "in", "items", ":", "category", "=", "lookup", "(", "item", ",", "'itemCategory'", ",", "'categoryCode'", ")", "if", "sorted_items", ".", "get", "(", "category", ")", "is", "None", ":", "sorted_items", "[", "category", "]", "=", "[", "]", "sorted_items", "[", "category", "]", ".", "append", "(", "item", ")", "return", "sorted_items" ]
sorts the items into a dictionary of categories, with a list of items
[ "sorts", "the", "items", "into", "a", "dictionary", "of", "categories", "with", "a", "list", "of", "items" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/item_list.py#L56-L66
1,340
softlayer/softlayer-python
SoftLayer/CLI/vlan/list.py
cli
def cli(env, sortby, datacenter, number, name, limit): """List VLANs.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby vlans = mgr.list_vlans(datacenter=datacenter, vlan_number=number, name=name, limit=limit) for vlan in vlans: table.add_row([ vlan['id'], vlan['vlanNumber'], vlan.get('name') or formatting.blank(), 'Yes' if vlan['firewallInterfaces'] else 'No', utils.lookup(vlan, 'primaryRouter', 'datacenter', 'name'), vlan['hardwareCount'], vlan['virtualGuestCount'], vlan['totalPrimaryIpAddressCount'], ]) env.fout(table)
python
def cli(env, sortby, datacenter, number, name, limit): """List VLANs.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby vlans = mgr.list_vlans(datacenter=datacenter, vlan_number=number, name=name, limit=limit) for vlan in vlans: table.add_row([ vlan['id'], vlan['vlanNumber'], vlan.get('name') or formatting.blank(), 'Yes' if vlan['firewallInterfaces'] else 'No', utils.lookup(vlan, 'primaryRouter', 'datacenter', 'name'), vlan['hardwareCount'], vlan['virtualGuestCount'], vlan['totalPrimaryIpAddressCount'], ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "datacenter", ",", "number", ",", "name", ",", "limit", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "table", ".", "sortby", "=", "sortby", "vlans", "=", "mgr", ".", "list_vlans", "(", "datacenter", "=", "datacenter", ",", "vlan_number", "=", "number", ",", "name", "=", "name", ",", "limit", "=", "limit", ")", "for", "vlan", "in", "vlans", ":", "table", ".", "add_row", "(", "[", "vlan", "[", "'id'", "]", ",", "vlan", "[", "'vlanNumber'", "]", ",", "vlan", ".", "get", "(", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "'Yes'", "if", "vlan", "[", "'firewallInterfaces'", "]", "else", "'No'", ",", "utils", ".", "lookup", "(", "vlan", ",", "'primaryRouter'", ",", "'datacenter'", ",", "'name'", ")", ",", "vlan", "[", "'hardwareCount'", "]", ",", "vlan", "[", "'virtualGuestCount'", "]", ",", "vlan", "[", "'totalPrimaryIpAddressCount'", "]", ",", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List VLANs.
[ "List", "VLANs", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vlan/list.py#L34-L58
1,341
softlayer/softlayer-python
SoftLayer/CLI/nas/list.py
cli
def cli(env): """List NAS accounts.""" account = env.client['Account'] nas_accounts = account.getNasNetworkStorage( mask='eventCount,serviceResource[datacenter.name]') table = formatting.Table(['id', 'datacenter', 'size', 'server']) for nas_account in nas_accounts: table.add_row([ nas_account['id'], utils.lookup(nas_account, 'serviceResource', 'datacenter', 'name') or formatting.blank(), formatting.FormattedItem( nas_account.get('capacityGb', formatting.blank()), "%dGB" % nas_account.get('capacityGb', 0)), nas_account.get('serviceResourceBackendIpAddress', formatting.blank())]) env.fout(table)
python
def cli(env): """List NAS accounts.""" account = env.client['Account'] nas_accounts = account.getNasNetworkStorage( mask='eventCount,serviceResource[datacenter.name]') table = formatting.Table(['id', 'datacenter', 'size', 'server']) for nas_account in nas_accounts: table.add_row([ nas_account['id'], utils.lookup(nas_account, 'serviceResource', 'datacenter', 'name') or formatting.blank(), formatting.FormattedItem( nas_account.get('capacityGb', formatting.blank()), "%dGB" % nas_account.get('capacityGb', 0)), nas_account.get('serviceResourceBackendIpAddress', formatting.blank())]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "account", "=", "env", ".", "client", "[", "'Account'", "]", "nas_accounts", "=", "account", ".", "getNasNetworkStorage", "(", "mask", "=", "'eventCount,serviceResource[datacenter.name]'", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'datacenter'", ",", "'size'", ",", "'server'", "]", ")", "for", "nas_account", "in", "nas_accounts", ":", "table", ".", "add_row", "(", "[", "nas_account", "[", "'id'", "]", ",", "utils", ".", "lookup", "(", "nas_account", ",", "'serviceResource'", ",", "'datacenter'", ",", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "formatting", ".", "FormattedItem", "(", "nas_account", ".", "get", "(", "'capacityGb'", ",", "formatting", ".", "blank", "(", ")", ")", ",", "\"%dGB\"", "%", "nas_account", ".", "get", "(", "'capacityGb'", ",", "0", ")", ")", ",", "nas_account", ".", "get", "(", "'serviceResourceBackendIpAddress'", ",", "formatting", ".", "blank", "(", ")", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List NAS accounts.
[ "List", "NAS", "accounts", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/nas/list.py#L13-L36
1,342
softlayer/softlayer-python
SoftLayer/CLI/config/setup.py
get_api_key
def get_api_key(client, username, secret): """Attempts API-Key and password auth to get an API key. This will also generate an API key if one doesn't exist """ # Try to use a client with username/api key if len(secret) == 64: try: client['Account'].getCurrentUser() return secret except SoftLayer.SoftLayerAPIError as ex: if 'invalid api token' not in ex.faultString.lower(): raise else: # Try to use a client with username/password client.authenticate_with_password(username, secret) user_record = client['Account'].getCurrentUser(mask='id, apiAuthenticationKeys') api_keys = user_record['apiAuthenticationKeys'] if len(api_keys) == 0: return client['User_Customer'].addApiAuthenticationKey(id=user_record['id']) return api_keys[0]['authenticationKey']
python
def get_api_key(client, username, secret): """Attempts API-Key and password auth to get an API key. This will also generate an API key if one doesn't exist """ # Try to use a client with username/api key if len(secret) == 64: try: client['Account'].getCurrentUser() return secret except SoftLayer.SoftLayerAPIError as ex: if 'invalid api token' not in ex.faultString.lower(): raise else: # Try to use a client with username/password client.authenticate_with_password(username, secret) user_record = client['Account'].getCurrentUser(mask='id, apiAuthenticationKeys') api_keys = user_record['apiAuthenticationKeys'] if len(api_keys) == 0: return client['User_Customer'].addApiAuthenticationKey(id=user_record['id']) return api_keys[0]['authenticationKey']
[ "def", "get_api_key", "(", "client", ",", "username", ",", "secret", ")", ":", "# Try to use a client with username/api key", "if", "len", "(", "secret", ")", "==", "64", ":", "try", ":", "client", "[", "'Account'", "]", ".", "getCurrentUser", "(", ")", "return", "secret", "except", "SoftLayer", ".", "SoftLayerAPIError", "as", "ex", ":", "if", "'invalid api token'", "not", "in", "ex", ".", "faultString", ".", "lower", "(", ")", ":", "raise", "else", ":", "# Try to use a client with username/password", "client", ".", "authenticate_with_password", "(", "username", ",", "secret", ")", "user_record", "=", "client", "[", "'Account'", "]", ".", "getCurrentUser", "(", "mask", "=", "'id, apiAuthenticationKeys'", ")", "api_keys", "=", "user_record", "[", "'apiAuthenticationKeys'", "]", "if", "len", "(", "api_keys", ")", "==", "0", ":", "return", "client", "[", "'User_Customer'", "]", ".", "addApiAuthenticationKey", "(", "id", "=", "user_record", "[", "'id'", "]", ")", "return", "api_keys", "[", "0", "]", "[", "'authenticationKey'", "]" ]
Attempts API-Key and password auth to get an API key. This will also generate an API key if one doesn't exist
[ "Attempts", "API", "-", "Key", "and", "password", "auth", "to", "get", "an", "API", "key", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/setup.py#L15-L37
1,343
softlayer/softlayer-python
SoftLayer/CLI/config/setup.py
cli
def cli(env): """Edit configuration.""" username, secret, endpoint_url, timeout = get_user_input(env) new_client = SoftLayer.Client(username=username, api_key=secret, endpoint_url=endpoint_url, timeout=timeout) api_key = get_api_key(new_client, username, secret) path = '~/.softlayer' if env.config_file: path = env.config_file config_path = os.path.expanduser(path) env.out(env.fmt(config.config_table({'username': username, 'api_key': api_key, 'endpoint_url': endpoint_url, 'timeout': timeout}))) if not formatting.confirm('Are you sure you want to write settings ' 'to "%s"?' % config_path, default=True): raise exceptions.CLIAbort('Aborted.') # Persist the config file. Read the target config file in before # setting the values to avoid clobbering settings parsed_config = utils.configparser.RawConfigParser() parsed_config.read(config_path) try: parsed_config.add_section('softlayer') except utils.configparser.DuplicateSectionError: pass parsed_config.set('softlayer', 'username', username) parsed_config.set('softlayer', 'api_key', api_key) parsed_config.set('softlayer', 'endpoint_url', endpoint_url) parsed_config.set('softlayer', 'timeout', timeout) config_fd = os.fdopen(os.open(config_path, (os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 0o600), 'w') try: parsed_config.write(config_fd) finally: config_fd.close() env.fout("Configuration Updated Successfully")
python
def cli(env): """Edit configuration.""" username, secret, endpoint_url, timeout = get_user_input(env) new_client = SoftLayer.Client(username=username, api_key=secret, endpoint_url=endpoint_url, timeout=timeout) api_key = get_api_key(new_client, username, secret) path = '~/.softlayer' if env.config_file: path = env.config_file config_path = os.path.expanduser(path) env.out(env.fmt(config.config_table({'username': username, 'api_key': api_key, 'endpoint_url': endpoint_url, 'timeout': timeout}))) if not formatting.confirm('Are you sure you want to write settings ' 'to "%s"?' % config_path, default=True): raise exceptions.CLIAbort('Aborted.') # Persist the config file. Read the target config file in before # setting the values to avoid clobbering settings parsed_config = utils.configparser.RawConfigParser() parsed_config.read(config_path) try: parsed_config.add_section('softlayer') except utils.configparser.DuplicateSectionError: pass parsed_config.set('softlayer', 'username', username) parsed_config.set('softlayer', 'api_key', api_key) parsed_config.set('softlayer', 'endpoint_url', endpoint_url) parsed_config.set('softlayer', 'timeout', timeout) config_fd = os.fdopen(os.open(config_path, (os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 0o600), 'w') try: parsed_config.write(config_fd) finally: config_fd.close() env.fout("Configuration Updated Successfully")
[ "def", "cli", "(", "env", ")", ":", "username", ",", "secret", ",", "endpoint_url", ",", "timeout", "=", "get_user_input", "(", "env", ")", "new_client", "=", "SoftLayer", ".", "Client", "(", "username", "=", "username", ",", "api_key", "=", "secret", ",", "endpoint_url", "=", "endpoint_url", ",", "timeout", "=", "timeout", ")", "api_key", "=", "get_api_key", "(", "new_client", ",", "username", ",", "secret", ")", "path", "=", "'~/.softlayer'", "if", "env", ".", "config_file", ":", "path", "=", "env", ".", "config_file", "config_path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "env", ".", "out", "(", "env", ".", "fmt", "(", "config", ".", "config_table", "(", "{", "'username'", ":", "username", ",", "'api_key'", ":", "api_key", ",", "'endpoint_url'", ":", "endpoint_url", ",", "'timeout'", ":", "timeout", "}", ")", ")", ")", "if", "not", "formatting", ".", "confirm", "(", "'Are you sure you want to write settings '", "'to \"%s\"?'", "%", "config_path", ",", "default", "=", "True", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted.'", ")", "# Persist the config file. Read the target config file in before", "# setting the values to avoid clobbering settings", "parsed_config", "=", "utils", ".", "configparser", ".", "RawConfigParser", "(", ")", "parsed_config", ".", "read", "(", "config_path", ")", "try", ":", "parsed_config", ".", "add_section", "(", "'softlayer'", ")", "except", "utils", ".", "configparser", ".", "DuplicateSectionError", ":", "pass", "parsed_config", ".", "set", "(", "'softlayer'", ",", "'username'", ",", "username", ")", "parsed_config", ".", "set", "(", "'softlayer'", ",", "'api_key'", ",", "api_key", ")", "parsed_config", ".", "set", "(", "'softlayer'", ",", "'endpoint_url'", ",", "endpoint_url", ")", "parsed_config", ".", "set", "(", "'softlayer'", ",", "'timeout'", ",", "timeout", ")", "config_fd", "=", "os", ".", "fdopen", "(", "os", ".", "open", "(", "config_path", ",", "(", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREAT", "|", "os", ".", "O_TRUNC", ")", ",", "0o600", ")", ",", "'w'", ")", "try", ":", "parsed_config", ".", "write", "(", "config_fd", ")", "finally", ":", "config_fd", ".", "close", "(", ")", "env", ".", "fout", "(", "\"Configuration Updated Successfully\"", ")" ]
Edit configuration.
[ "Edit", "configuration", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/setup.py#L42-L86
1,344
softlayer/softlayer-python
SoftLayer/CLI/dedicatedhost/create_options.py
cli
def cli(env, **kwargs): """host order options for a given dedicated host. To get a list of available backend routers see example: slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB """ mgr = SoftLayer.DedicatedHostManager(env.client) tables = [] if not kwargs['flavor'] and not kwargs['datacenter']: options = mgr.get_create_options() # Datacenters dc_table = formatting.Table(['datacenter', 'value']) dc_table.sortby = 'value' for location in options['locations']: dc_table.add_row([location['name'], location['key']]) tables.append(dc_table) dh_table = formatting.Table(['Dedicated Virtual Host Flavor(s)', 'value']) dh_table.sortby = 'value' for item in options['dedicated_host']: dh_table.add_row([item['name'], item['key']]) tables.append(dh_table) else: if kwargs['flavor'] is None or kwargs['datacenter'] is None: raise exceptions.ArgumentError('Both a flavor and datacenter need ' 'to be passed as arguments ' 'ex. slcli dh create-options -d ' 'ams01 -f ' '56_CORES_X_242_RAM_X_1_4_TB') router_opt = mgr.get_router_options(kwargs['datacenter'], kwargs['flavor']) br_table = formatting.Table( ['Available Backend Routers']) for router in router_opt: br_table.add_row([router['hostname']]) tables.append(br_table) env.fout(formatting.listing(tables, separator='\n'))
python
def cli(env, **kwargs): """host order options for a given dedicated host. To get a list of available backend routers see example: slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB """ mgr = SoftLayer.DedicatedHostManager(env.client) tables = [] if not kwargs['flavor'] and not kwargs['datacenter']: options = mgr.get_create_options() # Datacenters dc_table = formatting.Table(['datacenter', 'value']) dc_table.sortby = 'value' for location in options['locations']: dc_table.add_row([location['name'], location['key']]) tables.append(dc_table) dh_table = formatting.Table(['Dedicated Virtual Host Flavor(s)', 'value']) dh_table.sortby = 'value' for item in options['dedicated_host']: dh_table.add_row([item['name'], item['key']]) tables.append(dh_table) else: if kwargs['flavor'] is None or kwargs['datacenter'] is None: raise exceptions.ArgumentError('Both a flavor and datacenter need ' 'to be passed as arguments ' 'ex. slcli dh create-options -d ' 'ams01 -f ' '56_CORES_X_242_RAM_X_1_4_TB') router_opt = mgr.get_router_options(kwargs['datacenter'], kwargs['flavor']) br_table = formatting.Table( ['Available Backend Routers']) for router in router_opt: br_table.add_row([router['hostname']]) tables.append(br_table) env.fout(formatting.listing(tables, separator='\n'))
[ "def", "cli", "(", "env", ",", "*", "*", "kwargs", ")", ":", "mgr", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "tables", "=", "[", "]", "if", "not", "kwargs", "[", "'flavor'", "]", "and", "not", "kwargs", "[", "'datacenter'", "]", ":", "options", "=", "mgr", ".", "get_create_options", "(", ")", "# Datacenters", "dc_table", "=", "formatting", ".", "Table", "(", "[", "'datacenter'", ",", "'value'", "]", ")", "dc_table", ".", "sortby", "=", "'value'", "for", "location", "in", "options", "[", "'locations'", "]", ":", "dc_table", ".", "add_row", "(", "[", "location", "[", "'name'", "]", ",", "location", "[", "'key'", "]", "]", ")", "tables", ".", "append", "(", "dc_table", ")", "dh_table", "=", "formatting", ".", "Table", "(", "[", "'Dedicated Virtual Host Flavor(s)'", ",", "'value'", "]", ")", "dh_table", ".", "sortby", "=", "'value'", "for", "item", "in", "options", "[", "'dedicated_host'", "]", ":", "dh_table", ".", "add_row", "(", "[", "item", "[", "'name'", "]", ",", "item", "[", "'key'", "]", "]", ")", "tables", ".", "append", "(", "dh_table", ")", "else", ":", "if", "kwargs", "[", "'flavor'", "]", "is", "None", "or", "kwargs", "[", "'datacenter'", "]", "is", "None", ":", "raise", "exceptions", ".", "ArgumentError", "(", "'Both a flavor and datacenter need '", "'to be passed as arguments '", "'ex. slcli dh create-options -d '", "'ams01 -f '", "'56_CORES_X_242_RAM_X_1_4_TB'", ")", "router_opt", "=", "mgr", ".", "get_router_options", "(", "kwargs", "[", "'datacenter'", "]", ",", "kwargs", "[", "'flavor'", "]", ")", "br_table", "=", "formatting", ".", "Table", "(", "[", "'Available Backend Routers'", "]", ")", "for", "router", "in", "router_opt", ":", "br_table", ".", "add_row", "(", "[", "router", "[", "'hostname'", "]", "]", ")", "tables", ".", "append", "(", "br_table", ")", "env", ".", "fout", "(", "formatting", ".", "listing", "(", "tables", ",", "separator", "=", "'\\n'", ")", ")" ]
host order options for a given dedicated host. To get a list of available backend routers see example: slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB
[ "host", "order", "options", "for", "a", "given", "dedicated", "host", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/create_options.py#L22-L61
1,345
softlayer/softlayer-python
SoftLayer/CLI/hardware/cancel_reasons.py
cli
def cli(env): """Display a list of cancellation reasons.""" table = formatting.Table(['Code', 'Reason']) table.align['Code'] = 'r' table.align['Reason'] = 'l' mgr = SoftLayer.HardwareManager(env.client) for code, reason in mgr.get_cancellation_reasons().items(): table.add_row([code, reason]) env.fout(table)
python
def cli(env): """Display a list of cancellation reasons.""" table = formatting.Table(['Code', 'Reason']) table.align['Code'] = 'r' table.align['Reason'] = 'l' mgr = SoftLayer.HardwareManager(env.client) for code, reason in mgr.get_cancellation_reasons().items(): table.add_row([code, reason]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Code'", ",", "'Reason'", "]", ")", "table", ".", "align", "[", "'Code'", "]", "=", "'r'", "table", ".", "align", "[", "'Reason'", "]", "=", "'l'", "mgr", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "for", "code", ",", "reason", "in", "mgr", ".", "get_cancellation_reasons", "(", ")", ".", "items", "(", ")", ":", "table", ".", "add_row", "(", "[", "code", ",", "reason", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Display a list of cancellation reasons.
[ "Display", "a", "list", "of", "cancellation", "reasons", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/cancel_reasons.py#L13-L25
1,346
softlayer/softlayer-python
SoftLayer/CLI/vpn/ipsec/list.py
cli
def cli(env): """List IPSec VPN tunnel contexts""" manager = SoftLayer.IPSECManager(env.client) contexts = manager.get_tunnel_contexts() table = formatting.Table(['id', 'name', 'friendly name', 'internal peer IP address', 'remote peer IP address', 'created']) for context in contexts: table.add_row([context.get('id', ''), context.get('name', ''), context.get('friendlyName', ''), context.get('internalPeerIpAddress', ''), context.get('customerPeerIpAddress', ''), context.get('createDate', '')]) env.fout(table)
python
def cli(env): """List IPSec VPN tunnel contexts""" manager = SoftLayer.IPSECManager(env.client) contexts = manager.get_tunnel_contexts() table = formatting.Table(['id', 'name', 'friendly name', 'internal peer IP address', 'remote peer IP address', 'created']) for context in contexts: table.add_row([context.get('id', ''), context.get('name', ''), context.get('friendlyName', ''), context.get('internalPeerIpAddress', ''), context.get('customerPeerIpAddress', ''), context.get('createDate', '')]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "manager", "=", "SoftLayer", ".", "IPSECManager", "(", "env", ".", "client", ")", "contexts", "=", "manager", ".", "get_tunnel_contexts", "(", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'name'", ",", "'friendly name'", ",", "'internal peer IP address'", ",", "'remote peer IP address'", ",", "'created'", "]", ")", "for", "context", "in", "contexts", ":", "table", ".", "add_row", "(", "[", "context", ".", "get", "(", "'id'", ",", "''", ")", ",", "context", ".", "get", "(", "'name'", ",", "''", ")", ",", "context", ".", "get", "(", "'friendlyName'", ",", "''", ")", ",", "context", ".", "get", "(", "'internalPeerIpAddress'", ",", "''", ")", ",", "context", ".", "get", "(", "'customerPeerIpAddress'", ",", "''", ")", ",", "context", ".", "get", "(", "'createDate'", ",", "''", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List IPSec VPN tunnel contexts
[ "List", "IPSec", "VPN", "tunnel", "contexts" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/list.py#L13-L31
1,347
softlayer/softlayer-python
SoftLayer/CLI/file/replication/locations.py
cli
def cli(env, columns, sortby, volume_id): """List suitable replication datacenters for the given volume.""" file_storage_manager = SoftLayer.FileStorageManager(env.client) legal_centers = file_storage_manager.get_replication_locations( volume_id ) if not legal_centers: click.echo("No data centers compatible for replication.") else: table = formatting.KeyValueTable(columns.columns) table.sortby = sortby for legal_center in legal_centers: table.add_row([value or formatting.blank() for value in columns.row(legal_center)]) env.fout(table)
python
def cli(env, columns, sortby, volume_id): """List suitable replication datacenters for the given volume.""" file_storage_manager = SoftLayer.FileStorageManager(env.client) legal_centers = file_storage_manager.get_replication_locations( volume_id ) if not legal_centers: click.echo("No data centers compatible for replication.") else: table = formatting.KeyValueTable(columns.columns) table.sortby = sortby for legal_center in legal_centers: table.add_row([value or formatting.blank() for value in columns.row(legal_center)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "columns", ",", "sortby", ",", "volume_id", ")", ":", "file_storage_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "legal_centers", "=", "file_storage_manager", ".", "get_replication_locations", "(", "volume_id", ")", "if", "not", "legal_centers", ":", "click", ".", "echo", "(", "\"No data centers compatible for replication.\"", ")", "else", ":", "table", "=", "formatting", ".", "KeyValueTable", "(", "columns", ".", "columns", ")", "table", ".", "sortby", "=", "sortby", "for", "legal_center", "in", "legal_centers", ":", "table", ".", "add_row", "(", "[", "value", "or", "formatting", ".", "blank", "(", ")", "for", "value", "in", "columns", ".", "row", "(", "legal_center", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List suitable replication datacenters for the given volume.
[ "List", "suitable", "replication", "datacenters", "for", "the", "given", "volume", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/replication/locations.py#L32-L49
1,348
softlayer/softlayer-python
SoftLayer/CLI/dedicatedhost/list_guests.py
cli
def cli(env, identifier, sortby, cpu, domain, hostname, memory, tag, columns): """List guests which are in a dedicated host server.""" mgr = SoftLayer.DedicatedHostManager(env.client) guests = mgr.list_guests(host_id=identifier, cpus=cpu, hostname=hostname, domain=domain, memory=memory, tags=tag, mask=columns.mask()) table = formatting.Table(columns.columns) table.sortby = sortby for guest in guests: table.add_row([value or formatting.blank() for value in columns.row(guest)]) env.fout(table)
python
def cli(env, identifier, sortby, cpu, domain, hostname, memory, tag, columns): """List guests which are in a dedicated host server.""" mgr = SoftLayer.DedicatedHostManager(env.client) guests = mgr.list_guests(host_id=identifier, cpus=cpu, hostname=hostname, domain=domain, memory=memory, tags=tag, mask=columns.mask()) table = formatting.Table(columns.columns) table.sortby = sortby for guest in guests: table.add_row([value or formatting.blank() for value in columns.row(guest)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "identifier", ",", "sortby", ",", "cpu", ",", "domain", ",", "hostname", ",", "memory", ",", "tag", ",", "columns", ")", ":", "mgr", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "guests", "=", "mgr", ".", "list_guests", "(", "host_id", "=", "identifier", ",", "cpus", "=", "cpu", ",", "hostname", "=", "hostname", ",", "domain", "=", "domain", ",", "memory", "=", "memory", ",", "tags", "=", "tag", ",", "mask", "=", "columns", ".", "mask", "(", ")", ")", "table", "=", "formatting", ".", "Table", "(", "columns", ".", "columns", ")", "table", ".", "sortby", "=", "sortby", "for", "guest", "in", "guests", ":", "table", ".", "add_row", "(", "[", "value", "or", "formatting", ".", "blank", "(", ")", "for", "value", "in", "columns", ".", "row", "(", "guest", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List guests which are in a dedicated host server.
[ "List", "guests", "which", "are", "in", "a", "dedicated", "host", "server", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/list_guests.py#L57-L76
1,349
softlayer/softlayer-python
SoftLayer/CLI/ticket/detail.py
cli
def cli(env, identifier, count): """Get details for a ticket.""" mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') env.fout(ticket.get_ticket_results(mgr, ticket_id, update_count=count))
python
def cli(env, identifier, count): """Get details for a ticket.""" mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') env.fout(ticket.get_ticket_results(mgr, ticket_id, update_count=count))
[ "def", "cli", "(", "env", ",", "identifier", ",", "count", ")", ":", "mgr", "=", "SoftLayer", ".", "TicketManager", "(", "env", ".", "client", ")", "ticket_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'ticket'", ")", "env", ".", "fout", "(", "ticket", ".", "get_ticket_results", "(", "mgr", ",", "ticket_id", ",", "update_count", "=", "count", ")", ")" ]
Get details for a ticket.
[ "Get", "details", "for", "a", "ticket", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/detail.py#L20-L26
1,350
softlayer/softlayer-python
SoftLayer/transports.py
get_session
def get_session(user_agent): """Sets up urllib sessions""" client = requests.Session() client.headers.update({ 'Content-Type': 'application/json', 'User-Agent': user_agent, }) retry = Retry(connect=3, backoff_factor=3) adapter = HTTPAdapter(max_retries=retry) client.mount('https://', adapter) return client
python
def get_session(user_agent): """Sets up urllib sessions""" client = requests.Session() client.headers.update({ 'Content-Type': 'application/json', 'User-Agent': user_agent, }) retry = Retry(connect=3, backoff_factor=3) adapter = HTTPAdapter(max_retries=retry) client.mount('https://', adapter) return client
[ "def", "get_session", "(", "user_agent", ")", ":", "client", "=", "requests", ".", "Session", "(", ")", "client", ".", "headers", ".", "update", "(", "{", "'Content-Type'", ":", "'application/json'", ",", "'User-Agent'", ":", "user_agent", ",", "}", ")", "retry", "=", "Retry", "(", "connect", "=", "3", ",", "backoff_factor", "=", "3", ")", "adapter", "=", "HTTPAdapter", "(", "max_retries", "=", "retry", ")", "client", ".", "mount", "(", "'https://'", ",", "adapter", ")", "return", "client" ]
Sets up urllib sessions
[ "Sets", "up", "urllib", "sessions" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L45-L56
1,351
softlayer/softlayer-python
SoftLayer/transports.py
_format_object_mask
def _format_object_mask(objectmask): """Format the new style object mask. This wraps the user mask with mask[USER_MASK] if it does not already have one. This makes it slightly easier for users. :param objectmask: a string-based object mask """ objectmask = objectmask.strip() if (not objectmask.startswith('mask') and not objectmask.startswith('[')): objectmask = "mask[%s]" % objectmask return objectmask
python
def _format_object_mask(objectmask): """Format the new style object mask. This wraps the user mask with mask[USER_MASK] if it does not already have one. This makes it slightly easier for users. :param objectmask: a string-based object mask """ objectmask = objectmask.strip() if (not objectmask.startswith('mask') and not objectmask.startswith('[')): objectmask = "mask[%s]" % objectmask return objectmask
[ "def", "_format_object_mask", "(", "objectmask", ")", ":", "objectmask", "=", "objectmask", ".", "strip", "(", ")", "if", "(", "not", "objectmask", ".", "startswith", "(", "'mask'", ")", "and", "not", "objectmask", ".", "startswith", "(", "'['", ")", ")", ":", "objectmask", "=", "\"mask[%s]\"", "%", "objectmask", "return", "objectmask" ]
Format the new style object mask. This wraps the user mask with mask[USER_MASK] if it does not already have one. This makes it slightly easier for users. :param objectmask: a string-based object mask
[ "Format", "the", "new", "style", "object", "mask", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L544-L558
1,352
softlayer/softlayer-python
SoftLayer/transports.py
XmlRpcTransport.client
def client(self): """Returns client session object""" if self._client is None: self._client = get_session(self.user_agent) return self._client
python
def client(self): """Returns client session object""" if self._client is None: self._client = get_session(self.user_agent) return self._client
[ "def", "client", "(", "self", ")", ":", "if", "self", ".", "_client", "is", "None", ":", "self", ".", "_client", "=", "get_session", "(", "self", ".", "user_agent", ")", "return", "self", ".", "_client" ]
Returns client session object
[ "Returns", "client", "session", "object" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/transports.py#L158-L163
1,353
softlayer/softlayer-python
SoftLayer/CLI/hardware/toggle_ipmi.py
cli
def cli(env, identifier, enable): """Toggle the IPMI interface on and off""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') result = env.client['Hardware_Server'].toggleManagementInterface(enable, id=hw_id) env.fout(result)
python
def cli(env, identifier, enable): """Toggle the IPMI interface on and off""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') result = env.client['Hardware_Server'].toggleManagementInterface(enable, id=hw_id) env.fout(result)
[ "def", "cli", "(", "env", ",", "identifier", ",", "enable", ")", ":", "mgr", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "hw_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'hardware'", ")", "result", "=", "env", ".", "client", "[", "'Hardware_Server'", "]", ".", "toggleManagementInterface", "(", "enable", ",", "id", "=", "hw_id", ")", "env", ".", "fout", "(", "result", ")" ]
Toggle the IPMI interface on and off
[ "Toggle", "the", "IPMI", "interface", "on", "and", "off" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/toggle_ipmi.py#L16-L22
1,354
softlayer/softlayer-python
SoftLayer/CLI/dns/record_remove.py
cli
def cli(env, record_id): """Remove resource record.""" manager = SoftLayer.DNSManager(env.client) if not (env.skip_confirmations or formatting.no_going_back('yes')): raise exceptions.CLIAbort("Aborted.") manager.delete_record(record_id)
python
def cli(env, record_id): """Remove resource record.""" manager = SoftLayer.DNSManager(env.client) if not (env.skip_confirmations or formatting.no_going_back('yes')): raise exceptions.CLIAbort("Aborted.") manager.delete_record(record_id)
[ "def", "cli", "(", "env", ",", "record_id", ")", ":", "manager", "=", "SoftLayer", ".", "DNSManager", "(", "env", ".", "client", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "'yes'", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Aborted.\"", ")", "manager", ".", "delete_record", "(", "record_id", ")" ]
Remove resource record.
[ "Remove", "resource", "record", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/record_remove.py#L15-L23
1,355
softlayer/softlayer-python
SoftLayer/CLI/block/count.py
cli
def cli(env, sortby, datacenter): """List number of block storage volumes per datacenter.""" block_manager = SoftLayer.BlockStorageManager(env.client) mask = "mask[serviceResource[datacenter[name]],"\ "replicationPartners[serviceResource[datacenter[name]]]]" block_volumes = block_manager.list_block_volumes(datacenter=datacenter, mask=mask) # cycle through all block volumes and count datacenter occurences. datacenters = dict() for volume in block_volumes: service_resource = volume['serviceResource'] if 'datacenter' in service_resource: datacenter_name = service_resource['datacenter']['name'] if datacenter_name not in datacenters.keys(): datacenters[datacenter_name] = 1 else: datacenters[datacenter_name] += 1 table = formatting.KeyValueTable(DEFAULT_COLUMNS) table.sortby = sortby for datacenter_name in datacenters: table.add_row([datacenter_name, datacenters[datacenter_name]]) env.fout(table)
python
def cli(env, sortby, datacenter): """List number of block storage volumes per datacenter.""" block_manager = SoftLayer.BlockStorageManager(env.client) mask = "mask[serviceResource[datacenter[name]],"\ "replicationPartners[serviceResource[datacenter[name]]]]" block_volumes = block_manager.list_block_volumes(datacenter=datacenter, mask=mask) # cycle through all block volumes and count datacenter occurences. datacenters = dict() for volume in block_volumes: service_resource = volume['serviceResource'] if 'datacenter' in service_resource: datacenter_name = service_resource['datacenter']['name'] if datacenter_name not in datacenters.keys(): datacenters[datacenter_name] = 1 else: datacenters[datacenter_name] += 1 table = formatting.KeyValueTable(DEFAULT_COLUMNS) table.sortby = sortby for datacenter_name in datacenters: table.add_row([datacenter_name, datacenters[datacenter_name]]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "datacenter", ")", ":", "block_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "mask", "=", "\"mask[serviceResource[datacenter[name]],\"", "\"replicationPartners[serviceResource[datacenter[name]]]]\"", "block_volumes", "=", "block_manager", ".", "list_block_volumes", "(", "datacenter", "=", "datacenter", ",", "mask", "=", "mask", ")", "# cycle through all block volumes and count datacenter occurences.", "datacenters", "=", "dict", "(", ")", "for", "volume", "in", "block_volumes", ":", "service_resource", "=", "volume", "[", "'serviceResource'", "]", "if", "'datacenter'", "in", "service_resource", ":", "datacenter_name", "=", "service_resource", "[", "'datacenter'", "]", "[", "'name'", "]", "if", "datacenter_name", "not", "in", "datacenters", ".", "keys", "(", ")", ":", "datacenters", "[", "datacenter_name", "]", "=", "1", "else", ":", "datacenters", "[", "datacenter_name", "]", "+=", "1", "table", "=", "formatting", ".", "KeyValueTable", "(", "DEFAULT_COLUMNS", ")", "table", ".", "sortby", "=", "sortby", "for", "datacenter_name", "in", "datacenters", ":", "table", ".", "add_row", "(", "[", "datacenter_name", ",", "datacenters", "[", "datacenter_name", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List number of block storage volumes per datacenter.
[ "List", "number", "of", "block", "storage", "volumes", "per", "datacenter", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/count.py#L19-L42
1,356
softlayer/softlayer-python
SoftLayer/CLI/cdn/load.py
cli
def cli(env, account_id, content_url): """Cache one or more files on all edge nodes.""" manager = SoftLayer.CDNManager(env.client) manager.load_content(account_id, content_url)
python
def cli(env, account_id, content_url): """Cache one or more files on all edge nodes.""" manager = SoftLayer.CDNManager(env.client) manager.load_content(account_id, content_url)
[ "def", "cli", "(", "env", ",", "account_id", ",", "content_url", ")", ":", "manager", "=", "SoftLayer", ".", "CDNManager", "(", "env", ".", "client", ")", "manager", ".", "load_content", "(", "account_id", ",", "content_url", ")" ]
Cache one or more files on all edge nodes.
[ "Cache", "one", "or", "more", "files", "on", "all", "edge", "nodes", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/load.py#L14-L18
1,357
softlayer/softlayer-python
SoftLayer/CLI/vlan/detail.py
cli
def cli(env, identifier, no_vs, no_hardware): """Get details about a VLAN.""" mgr = SoftLayer.NetworkManager(env.client) vlan_id = helpers.resolve_id(mgr.resolve_vlan_ids, identifier, 'VLAN') vlan = mgr.get_vlan(vlan_id) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', vlan['id']]) table.add_row(['number', vlan['vlanNumber']]) table.add_row(['datacenter', vlan['primaryRouter']['datacenter']['longName']]) table.add_row(['primary_router', vlan['primaryRouter']['fullyQualifiedDomainName']]) table.add_row(['firewall', 'Yes' if vlan['firewallInterfaces'] else 'No']) subnets = [] for subnet in vlan.get('subnets', []): subnet_table = formatting.KeyValueTable(['name', 'value']) subnet_table.align['name'] = 'r' subnet_table.align['value'] = 'l' subnet_table.add_row(['id', subnet['id']]) subnet_table.add_row(['identifier', subnet['networkIdentifier']]) subnet_table.add_row(['netmask', subnet['netmask']]) subnet_table.add_row(['gateway', subnet.get('gateway', '-')]) subnet_table.add_row(['type', subnet['subnetType']]) subnet_table.add_row(['usable ips', subnet['usableIpAddressCount']]) subnets.append(subnet_table) table.add_row(['subnets', subnets]) server_columns = ['hostname', 'domain', 'public_ip', 'private_ip'] if not no_vs: if vlan.get('virtualGuests'): vs_table = formatting.KeyValueTable(server_columns) for vsi in vlan['virtualGuests']: vs_table.add_row([vsi.get('hostname'), vsi.get('domain'), vsi.get('primaryIpAddress'), vsi.get('primaryBackendIpAddress')]) table.add_row(['vs', vs_table]) else: table.add_row(['vs', 'none']) if not no_hardware: if vlan.get('hardware'): hw_table = formatting.Table(server_columns) for hardware in vlan['hardware']: hw_table.add_row([hardware.get('hostname'), hardware.get('domain'), hardware.get('primaryIpAddress'), hardware.get('primaryBackendIpAddress')]) table.add_row(['hardware', hw_table]) else: table.add_row(['hardware', 'none']) env.fout(table)
python
def cli(env, identifier, no_vs, no_hardware): """Get details about a VLAN.""" mgr = SoftLayer.NetworkManager(env.client) vlan_id = helpers.resolve_id(mgr.resolve_vlan_ids, identifier, 'VLAN') vlan = mgr.get_vlan(vlan_id) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', vlan['id']]) table.add_row(['number', vlan['vlanNumber']]) table.add_row(['datacenter', vlan['primaryRouter']['datacenter']['longName']]) table.add_row(['primary_router', vlan['primaryRouter']['fullyQualifiedDomainName']]) table.add_row(['firewall', 'Yes' if vlan['firewallInterfaces'] else 'No']) subnets = [] for subnet in vlan.get('subnets', []): subnet_table = formatting.KeyValueTable(['name', 'value']) subnet_table.align['name'] = 'r' subnet_table.align['value'] = 'l' subnet_table.add_row(['id', subnet['id']]) subnet_table.add_row(['identifier', subnet['networkIdentifier']]) subnet_table.add_row(['netmask', subnet['netmask']]) subnet_table.add_row(['gateway', subnet.get('gateway', '-')]) subnet_table.add_row(['type', subnet['subnetType']]) subnet_table.add_row(['usable ips', subnet['usableIpAddressCount']]) subnets.append(subnet_table) table.add_row(['subnets', subnets]) server_columns = ['hostname', 'domain', 'public_ip', 'private_ip'] if not no_vs: if vlan.get('virtualGuests'): vs_table = formatting.KeyValueTable(server_columns) for vsi in vlan['virtualGuests']: vs_table.add_row([vsi.get('hostname'), vsi.get('domain'), vsi.get('primaryIpAddress'), vsi.get('primaryBackendIpAddress')]) table.add_row(['vs', vs_table]) else: table.add_row(['vs', 'none']) if not no_hardware: if vlan.get('hardware'): hw_table = formatting.Table(server_columns) for hardware in vlan['hardware']: hw_table.add_row([hardware.get('hostname'), hardware.get('domain'), hardware.get('primaryIpAddress'), hardware.get('primaryBackendIpAddress')]) table.add_row(['hardware', hw_table]) else: table.add_row(['hardware', 'none']) env.fout(table)
[ "def", "cli", "(", "env", ",", "identifier", ",", "no_vs", ",", "no_hardware", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "vlan_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_vlan_ids", ",", "identifier", ",", "'VLAN'", ")", "vlan", "=", "mgr", ".", "get_vlan", "(", "vlan_id", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "table", ".", "add_row", "(", "[", "'id'", ",", "vlan", "[", "'id'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'number'", ",", "vlan", "[", "'vlanNumber'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'datacenter'", ",", "vlan", "[", "'primaryRouter'", "]", "[", "'datacenter'", "]", "[", "'longName'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'primary_router'", ",", "vlan", "[", "'primaryRouter'", "]", "[", "'fullyQualifiedDomainName'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'firewall'", ",", "'Yes'", "if", "vlan", "[", "'firewallInterfaces'", "]", "else", "'No'", "]", ")", "subnets", "=", "[", "]", "for", "subnet", "in", "vlan", ".", "get", "(", "'subnets'", ",", "[", "]", ")", ":", "subnet_table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "subnet_table", ".", "align", "[", "'name'", "]", "=", "'r'", "subnet_table", ".", "align", "[", "'value'", "]", "=", "'l'", "subnet_table", ".", "add_row", "(", "[", "'id'", ",", "subnet", "[", "'id'", "]", "]", ")", "subnet_table", ".", "add_row", "(", "[", "'identifier'", ",", "subnet", "[", "'networkIdentifier'", "]", "]", ")", "subnet_table", ".", "add_row", "(", "[", "'netmask'", ",", "subnet", "[", "'netmask'", "]", "]", ")", "subnet_table", ".", "add_row", "(", "[", "'gateway'", ",", "subnet", ".", "get", "(", "'gateway'", ",", "'-'", ")", "]", ")", "subnet_table", ".", "add_row", "(", "[", "'type'", ",", "subnet", "[", "'subnetType'", "]", "]", ")", "subnet_table", ".", "add_row", "(", "[", "'usable ips'", ",", "subnet", "[", "'usableIpAddressCount'", "]", "]", ")", "subnets", ".", "append", "(", "subnet_table", ")", "table", ".", "add_row", "(", "[", "'subnets'", ",", "subnets", "]", ")", "server_columns", "=", "[", "'hostname'", ",", "'domain'", ",", "'public_ip'", ",", "'private_ip'", "]", "if", "not", "no_vs", ":", "if", "vlan", ".", "get", "(", "'virtualGuests'", ")", ":", "vs_table", "=", "formatting", ".", "KeyValueTable", "(", "server_columns", ")", "for", "vsi", "in", "vlan", "[", "'virtualGuests'", "]", ":", "vs_table", ".", "add_row", "(", "[", "vsi", ".", "get", "(", "'hostname'", ")", ",", "vsi", ".", "get", "(", "'domain'", ")", ",", "vsi", ".", "get", "(", "'primaryIpAddress'", ")", ",", "vsi", ".", "get", "(", "'primaryBackendIpAddress'", ")", "]", ")", "table", ".", "add_row", "(", "[", "'vs'", ",", "vs_table", "]", ")", "else", ":", "table", ".", "add_row", "(", "[", "'vs'", ",", "'none'", "]", ")", "if", "not", "no_hardware", ":", "if", "vlan", ".", "get", "(", "'hardware'", ")", ":", "hw_table", "=", "formatting", ".", "Table", "(", "server_columns", ")", "for", "hardware", "in", "vlan", "[", "'hardware'", "]", ":", "hw_table", ".", "add_row", "(", "[", "hardware", ".", "get", "(", "'hostname'", ")", ",", "hardware", ".", "get", "(", "'domain'", ")", ",", "hardware", ".", "get", "(", "'primaryIpAddress'", ")", ",", "hardware", ".", "get", "(", "'primaryBackendIpAddress'", ")", "]", ")", "table", ".", "add_row", "(", "[", "'hardware'", ",", "hw_table", "]", ")", "else", ":", "table", ".", "add_row", "(", "[", "'hardware'", ",", "'none'", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Get details about a VLAN.
[ "Get", "details", "about", "a", "VLAN", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vlan/detail.py#L21-L83
1,358
softlayer/softlayer-python
SoftLayer/CLI/block/lun.py
cli
def cli(env, volume_id, lun_id): """Set the LUN ID on an existing block storage volume. The LUN ID only takes effect during the Host Authorization process. It is recommended (but not necessary) to de-authorize all hosts before using this method. See `block access-revoke`. VOLUME_ID - the volume ID on which to set the LUN ID. LUN_ID - recommended range is an integer between 0 and 255. Advanced users can use an integer between 0 and 4095. """ block_storage_manager = SoftLayer.BlockStorageManager(env.client) res = block_storage_manager.create_or_update_lun_id(volume_id, lun_id) if 'value' in res and lun_id == res['value']: click.echo( 'Block volume with id %s is reporting LUN ID %s' % (res['volumeId'], res['value'])) else: click.echo( 'Failed to confirm the new LUN ID on volume %s' % (volume_id))
python
def cli(env, volume_id, lun_id): """Set the LUN ID on an existing block storage volume. The LUN ID only takes effect during the Host Authorization process. It is recommended (but not necessary) to de-authorize all hosts before using this method. See `block access-revoke`. VOLUME_ID - the volume ID on which to set the LUN ID. LUN_ID - recommended range is an integer between 0 and 255. Advanced users can use an integer between 0 and 4095. """ block_storage_manager = SoftLayer.BlockStorageManager(env.client) res = block_storage_manager.create_or_update_lun_id(volume_id, lun_id) if 'value' in res and lun_id == res['value']: click.echo( 'Block volume with id %s is reporting LUN ID %s' % (res['volumeId'], res['value'])) else: click.echo( 'Failed to confirm the new LUN ID on volume %s' % (volume_id))
[ "def", "cli", "(", "env", ",", "volume_id", ",", "lun_id", ")", ":", "block_storage_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "res", "=", "block_storage_manager", ".", "create_or_update_lun_id", "(", "volume_id", ",", "lun_id", ")", "if", "'value'", "in", "res", "and", "lun_id", "==", "res", "[", "'value'", "]", ":", "click", ".", "echo", "(", "'Block volume with id %s is reporting LUN ID %s'", "%", "(", "res", "[", "'volumeId'", "]", ",", "res", "[", "'value'", "]", ")", ")", "else", ":", "click", ".", "echo", "(", "'Failed to confirm the new LUN ID on volume %s'", "%", "(", "volume_id", ")", ")" ]
Set the LUN ID on an existing block storage volume. The LUN ID only takes effect during the Host Authorization process. It is recommended (but not necessary) to de-authorize all hosts before using this method. See `block access-revoke`. VOLUME_ID - the volume ID on which to set the LUN ID. LUN_ID - recommended range is an integer between 0 and 255. Advanced users can use an integer between 0 and 4095.
[ "Set", "the", "LUN", "ID", "on", "an", "existing", "block", "storage", "volume", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/lun.py#L14-L36
1,359
softlayer/softlayer-python
SoftLayer/CLI/loadbal/detail.py
cli
def cli(env, identifier): """Get Load balancer details.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, loadbal_id = loadbal.parse_id(identifier) load_balancer = mgr.get_local_lb(loadbal_id) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'l' table.align['value'] = 'l' table.add_row(['ID', 'local:%s' % load_balancer['id']]) table.add_row(['IP Address', load_balancer['ipAddress']['ipAddress']]) name = load_balancer['loadBalancerHardware'][0]['datacenter']['name'] table.add_row(['Datacenter', name]) table.add_row(['Connections limit', load_balancer['connectionLimit']]) table.add_row(['Dedicated', load_balancer['dedicatedFlag']]) table.add_row(['HA', load_balancer['highAvailabilityFlag']]) table.add_row(['SSL Enabled', load_balancer['sslEnabledFlag']]) table.add_row(['SSL Active', load_balancer['sslActiveFlag']]) index0 = 1 for virtual_server in load_balancer['virtualServers']: for group in virtual_server['serviceGroups']: service_group_table = formatting.KeyValueTable(['name', 'value']) table.add_row(['Service Group %s' % index0, service_group_table]) index0 += 1 service_group_table.add_row(['Guest ID', virtual_server['id']]) service_group_table.add_row(['Port', virtual_server['port']]) service_group_table.add_row(['Allocation', '%s %%' % virtual_server['allocation']]) service_group_table.add_row(['Routing Type', '%s:%s' % (group['routingTypeId'], group['routingType']['name'])]) service_group_table.add_row(['Routing Method', '%s:%s' % (group['routingMethodId'], group['routingMethod']['name'])]) index1 = 1 for service in group['services']: service_table = formatting.KeyValueTable(['name', 'value']) service_group_table.add_row(['Service %s' % index1, service_table]) index1 += 1 health_check = service['healthChecks'][0] service_table.add_row(['Service ID', service['id']]) service_table.add_row(['IP Address', service['ipAddress']['ipAddress']]) service_table.add_row(['Port', service['port']]) service_table.add_row(['Health Check', '%s:%s' % (health_check['healthCheckTypeId'], health_check['type']['name'])]) service_table.add_row( ['Weight', service['groupReferences'][0]['weight']]) service_table.add_row(['Enabled', service['enabled']]) service_table.add_row(['Status', service['status']]) env.fout(table)
python
def cli(env, identifier): """Get Load balancer details.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, loadbal_id = loadbal.parse_id(identifier) load_balancer = mgr.get_local_lb(loadbal_id) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'l' table.align['value'] = 'l' table.add_row(['ID', 'local:%s' % load_balancer['id']]) table.add_row(['IP Address', load_balancer['ipAddress']['ipAddress']]) name = load_balancer['loadBalancerHardware'][0]['datacenter']['name'] table.add_row(['Datacenter', name]) table.add_row(['Connections limit', load_balancer['connectionLimit']]) table.add_row(['Dedicated', load_balancer['dedicatedFlag']]) table.add_row(['HA', load_balancer['highAvailabilityFlag']]) table.add_row(['SSL Enabled', load_balancer['sslEnabledFlag']]) table.add_row(['SSL Active', load_balancer['sslActiveFlag']]) index0 = 1 for virtual_server in load_balancer['virtualServers']: for group in virtual_server['serviceGroups']: service_group_table = formatting.KeyValueTable(['name', 'value']) table.add_row(['Service Group %s' % index0, service_group_table]) index0 += 1 service_group_table.add_row(['Guest ID', virtual_server['id']]) service_group_table.add_row(['Port', virtual_server['port']]) service_group_table.add_row(['Allocation', '%s %%' % virtual_server['allocation']]) service_group_table.add_row(['Routing Type', '%s:%s' % (group['routingTypeId'], group['routingType']['name'])]) service_group_table.add_row(['Routing Method', '%s:%s' % (group['routingMethodId'], group['routingMethod']['name'])]) index1 = 1 for service in group['services']: service_table = formatting.KeyValueTable(['name', 'value']) service_group_table.add_row(['Service %s' % index1, service_table]) index1 += 1 health_check = service['healthChecks'][0] service_table.add_row(['Service ID', service['id']]) service_table.add_row(['IP Address', service['ipAddress']['ipAddress']]) service_table.add_row(['Port', service['port']]) service_table.add_row(['Health Check', '%s:%s' % (health_check['healthCheckTypeId'], health_check['type']['name'])]) service_table.add_row( ['Weight', service['groupReferences'][0]['weight']]) service_table.add_row(['Enabled', service['enabled']]) service_table.add_row(['Status', service['status']]) env.fout(table)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "_", ",", "loadbal_id", "=", "loadbal", ".", "parse_id", "(", "identifier", ")", "load_balancer", "=", "mgr", ".", "get_local_lb", "(", "loadbal_id", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'l'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "table", ".", "add_row", "(", "[", "'ID'", ",", "'local:%s'", "%", "load_balancer", "[", "'id'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'IP Address'", ",", "load_balancer", "[", "'ipAddress'", "]", "[", "'ipAddress'", "]", "]", ")", "name", "=", "load_balancer", "[", "'loadBalancerHardware'", "]", "[", "0", "]", "[", "'datacenter'", "]", "[", "'name'", "]", "table", ".", "add_row", "(", "[", "'Datacenter'", ",", "name", "]", ")", "table", ".", "add_row", "(", "[", "'Connections limit'", ",", "load_balancer", "[", "'connectionLimit'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'Dedicated'", ",", "load_balancer", "[", "'dedicatedFlag'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'HA'", ",", "load_balancer", "[", "'highAvailabilityFlag'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'SSL Enabled'", ",", "load_balancer", "[", "'sslEnabledFlag'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'SSL Active'", ",", "load_balancer", "[", "'sslActiveFlag'", "]", "]", ")", "index0", "=", "1", "for", "virtual_server", "in", "load_balancer", "[", "'virtualServers'", "]", ":", "for", "group", "in", "virtual_server", "[", "'serviceGroups'", "]", ":", "service_group_table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "add_row", "(", "[", "'Service Group %s'", "%", "index0", ",", "service_group_table", "]", ")", "index0", "+=", "1", "service_group_table", ".", "add_row", "(", "[", "'Guest ID'", ",", "virtual_server", "[", "'id'", "]", "]", ")", "service_group_table", ".", "add_row", "(", "[", "'Port'", ",", "virtual_server", "[", "'port'", "]", "]", ")", "service_group_table", ".", "add_row", "(", "[", "'Allocation'", ",", "'%s %%'", "%", "virtual_server", "[", "'allocation'", "]", "]", ")", "service_group_table", ".", "add_row", "(", "[", "'Routing Type'", ",", "'%s:%s'", "%", "(", "group", "[", "'routingTypeId'", "]", ",", "group", "[", "'routingType'", "]", "[", "'name'", "]", ")", "]", ")", "service_group_table", ".", "add_row", "(", "[", "'Routing Method'", ",", "'%s:%s'", "%", "(", "group", "[", "'routingMethodId'", "]", ",", "group", "[", "'routingMethod'", "]", "[", "'name'", "]", ")", "]", ")", "index1", "=", "1", "for", "service", "in", "group", "[", "'services'", "]", ":", "service_table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "service_group_table", ".", "add_row", "(", "[", "'Service %s'", "%", "index1", ",", "service_table", "]", ")", "index1", "+=", "1", "health_check", "=", "service", "[", "'healthChecks'", "]", "[", "0", "]", "service_table", ".", "add_row", "(", "[", "'Service ID'", ",", "service", "[", "'id'", "]", "]", ")", "service_table", ".", "add_row", "(", "[", "'IP Address'", ",", "service", "[", "'ipAddress'", "]", "[", "'ipAddress'", "]", "]", ")", "service_table", ".", "add_row", "(", "[", "'Port'", ",", "service", "[", "'port'", "]", "]", ")", "service_table", ".", "add_row", "(", "[", "'Health Check'", ",", "'%s:%s'", "%", "(", "health_check", "[", "'healthCheckTypeId'", "]", ",", "health_check", "[", "'type'", "]", "[", "'name'", "]", ")", "]", ")", "service_table", ".", "add_row", "(", "[", "'Weight'", ",", "service", "[", "'groupReferences'", "]", "[", "0", "]", "[", "'weight'", "]", "]", ")", "service_table", ".", "add_row", "(", "[", "'Enabled'", ",", "service", "[", "'enabled'", "]", "]", ")", "service_table", ".", "add_row", "(", "[", "'Status'", ",", "service", "[", "'status'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Get Load balancer details.
[ "Get", "Load", "balancer", "details", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/detail.py#L15-L81
1,360
softlayer/softlayer-python
SoftLayer/CLI/core.py
cli
def cli(env, format='table', config=None, verbose=0, proxy=None, really=False, demo=False, **kwargs): """Main click CLI entry-point.""" # Populate environement with client and set it as the context object env.skip_confirmations = really env.config_file = config env.format = format env.ensure_client(config_file=config, is_demo=demo, proxy=proxy) env.vars['_start'] = time.time() logger = logging.getLogger() if demo is False: logger.addHandler(logging.StreamHandler()) else: # This section is for running CLI tests. logging.getLogger("urllib3").setLevel(logging.WARNING) logger.addHandler(logging.NullHandler()) logger.setLevel(DEBUG_LOGGING_MAP.get(verbose, logging.DEBUG)) env.vars['_timings'] = SoftLayer.DebugTransport(env.client.transport) env.client.transport = env.vars['_timings']
python
def cli(env, format='table', config=None, verbose=0, proxy=None, really=False, demo=False, **kwargs): """Main click CLI entry-point.""" # Populate environement with client and set it as the context object env.skip_confirmations = really env.config_file = config env.format = format env.ensure_client(config_file=config, is_demo=demo, proxy=proxy) env.vars['_start'] = time.time() logger = logging.getLogger() if demo is False: logger.addHandler(logging.StreamHandler()) else: # This section is for running CLI tests. logging.getLogger("urllib3").setLevel(logging.WARNING) logger.addHandler(logging.NullHandler()) logger.setLevel(DEBUG_LOGGING_MAP.get(verbose, logging.DEBUG)) env.vars['_timings'] = SoftLayer.DebugTransport(env.client.transport) env.client.transport = env.vars['_timings']
[ "def", "cli", "(", "env", ",", "format", "=", "'table'", ",", "config", "=", "None", ",", "verbose", "=", "0", ",", "proxy", "=", "None", ",", "really", "=", "False", ",", "demo", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Populate environement with client and set it as the context object", "env", ".", "skip_confirmations", "=", "really", "env", ".", "config_file", "=", "config", "env", ".", "format", "=", "format", "env", ".", "ensure_client", "(", "config_file", "=", "config", ",", "is_demo", "=", "demo", ",", "proxy", "=", "proxy", ")", "env", ".", "vars", "[", "'_start'", "]", "=", "time", ".", "time", "(", ")", "logger", "=", "logging", ".", "getLogger", "(", ")", "if", "demo", "is", "False", ":", "logger", ".", "addHandler", "(", "logging", ".", "StreamHandler", "(", ")", ")", "else", ":", "# This section is for running CLI tests.", "logging", ".", "getLogger", "(", "\"urllib3\"", ")", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "logger", ".", "addHandler", "(", "logging", ".", "NullHandler", "(", ")", ")", "logger", ".", "setLevel", "(", "DEBUG_LOGGING_MAP", ".", "get", "(", "verbose", ",", "logging", ".", "DEBUG", ")", ")", "env", ".", "vars", "[", "'_timings'", "]", "=", "SoftLayer", ".", "DebugTransport", "(", "env", ".", "client", ".", "transport", ")", "env", ".", "client", ".", "transport", "=", "env", ".", "vars", "[", "'_timings'", "]" ]
Main click CLI entry-point.
[ "Main", "click", "CLI", "entry", "-", "point", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L108-L135
1,361
softlayer/softlayer-python
SoftLayer/CLI/core.py
output_diagnostics
def output_diagnostics(env, result, verbose=0, **kwargs): """Output diagnostic information.""" if verbose > 0: diagnostic_table = formatting.Table(['name', 'value']) diagnostic_table.add_row(['execution_time', '%fs' % (time.time() - START_TIME)]) api_call_value = [] for call in env.client.transport.get_last_calls(): api_call_value.append("%s::%s (%fs)" % (call.service, call.method, call.end_time - call.start_time)) diagnostic_table.add_row(['api_calls', api_call_value]) diagnostic_table.add_row(['version', consts.USER_AGENT]) diagnostic_table.add_row(['python_version', sys.version]) diagnostic_table.add_row(['library_location', os.path.dirname(SoftLayer.__file__)]) env.err(env.fmt(diagnostic_table)) if verbose > 1: for call in env.client.transport.get_last_calls(): call_table = formatting.Table(['', '{}::{}'.format(call.service, call.method)]) nice_mask = '' if call.mask is not None: nice_mask = call.mask call_table.add_row(['id', call.identifier]) call_table.add_row(['mask', nice_mask]) call_table.add_row(['filter', call.filter]) call_table.add_row(['limit', call.limit]) call_table.add_row(['offset', call.offset]) env.err(env.fmt(call_table)) if verbose > 2: for call in env.client.transport.get_last_calls(): env.err(env.client.transport.print_reproduceable(call))
python
def output_diagnostics(env, result, verbose=0, **kwargs): """Output diagnostic information.""" if verbose > 0: diagnostic_table = formatting.Table(['name', 'value']) diagnostic_table.add_row(['execution_time', '%fs' % (time.time() - START_TIME)]) api_call_value = [] for call in env.client.transport.get_last_calls(): api_call_value.append("%s::%s (%fs)" % (call.service, call.method, call.end_time - call.start_time)) diagnostic_table.add_row(['api_calls', api_call_value]) diagnostic_table.add_row(['version', consts.USER_AGENT]) diagnostic_table.add_row(['python_version', sys.version]) diagnostic_table.add_row(['library_location', os.path.dirname(SoftLayer.__file__)]) env.err(env.fmt(diagnostic_table)) if verbose > 1: for call in env.client.transport.get_last_calls(): call_table = formatting.Table(['', '{}::{}'.format(call.service, call.method)]) nice_mask = '' if call.mask is not None: nice_mask = call.mask call_table.add_row(['id', call.identifier]) call_table.add_row(['mask', nice_mask]) call_table.add_row(['filter', call.filter]) call_table.add_row(['limit', call.limit]) call_table.add_row(['offset', call.offset]) env.err(env.fmt(call_table)) if verbose > 2: for call in env.client.transport.get_last_calls(): env.err(env.client.transport.print_reproduceable(call))
[ "def", "output_diagnostics", "(", "env", ",", "result", ",", "verbose", "=", "0", ",", "*", "*", "kwargs", ")", ":", "if", "verbose", ">", "0", ":", "diagnostic_table", "=", "formatting", ".", "Table", "(", "[", "'name'", ",", "'value'", "]", ")", "diagnostic_table", ".", "add_row", "(", "[", "'execution_time'", ",", "'%fs'", "%", "(", "time", ".", "time", "(", ")", "-", "START_TIME", ")", "]", ")", "api_call_value", "=", "[", "]", "for", "call", "in", "env", ".", "client", ".", "transport", ".", "get_last_calls", "(", ")", ":", "api_call_value", ".", "append", "(", "\"%s::%s (%fs)\"", "%", "(", "call", ".", "service", ",", "call", ".", "method", ",", "call", ".", "end_time", "-", "call", ".", "start_time", ")", ")", "diagnostic_table", ".", "add_row", "(", "[", "'api_calls'", ",", "api_call_value", "]", ")", "diagnostic_table", ".", "add_row", "(", "[", "'version'", ",", "consts", ".", "USER_AGENT", "]", ")", "diagnostic_table", ".", "add_row", "(", "[", "'python_version'", ",", "sys", ".", "version", "]", ")", "diagnostic_table", ".", "add_row", "(", "[", "'library_location'", ",", "os", ".", "path", ".", "dirname", "(", "SoftLayer", ".", "__file__", ")", "]", ")", "env", ".", "err", "(", "env", ".", "fmt", "(", "diagnostic_table", ")", ")", "if", "verbose", ">", "1", ":", "for", "call", "in", "env", ".", "client", ".", "transport", ".", "get_last_calls", "(", ")", ":", "call_table", "=", "formatting", ".", "Table", "(", "[", "''", ",", "'{}::{}'", ".", "format", "(", "call", ".", "service", ",", "call", ".", "method", ")", "]", ")", "nice_mask", "=", "''", "if", "call", ".", "mask", "is", "not", "None", ":", "nice_mask", "=", "call", ".", "mask", "call_table", ".", "add_row", "(", "[", "'id'", ",", "call", ".", "identifier", "]", ")", "call_table", ".", "add_row", "(", "[", "'mask'", ",", "nice_mask", "]", ")", "call_table", ".", "add_row", "(", "[", "'filter'", ",", "call", ".", "filter", "]", ")", "call_table", ".", "add_row", "(", "[", "'limit'", ",", "call", ".", "limit", "]", ")", "call_table", ".", "add_row", "(", "[", "'offset'", ",", "call", ".", "offset", "]", ")", "env", ".", "err", "(", "env", ".", "fmt", "(", "call_table", ")", ")", "if", "verbose", ">", "2", ":", "for", "call", "in", "env", ".", "client", ".", "transport", ".", "get_last_calls", "(", ")", ":", "env", ".", "err", "(", "env", ".", "client", ".", "transport", ".", "print_reproduceable", "(", "call", ")", ")" ]
Output diagnostic information.
[ "Output", "diagnostic", "information", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L140-L174
1,362
softlayer/softlayer-python
SoftLayer/CLI/core.py
main
def main(reraise_exceptions=False, **kwargs): """Main program. Catches several common errors and displays them nicely.""" exit_status = 0 try: cli.main(**kwargs) except SoftLayer.SoftLayerAPIError as ex: if 'invalid api token' in ex.faultString.lower(): print("Authentication Failed: To update your credentials, use 'slcli config setup'") exit_status = 1 else: print(str(ex)) exit_status = 1 except SoftLayer.SoftLayerError as ex: print(str(ex)) exit_status = 1 except exceptions.CLIAbort as ex: print(str(ex.message)) exit_status = ex.code except Exception: if reraise_exceptions: raise import traceback print("An unexpected error has occured:") print(str(traceback.format_exc())) print("Feel free to report this error as it is likely a bug:") print(" https://github.com/softlayer/softlayer-python/issues") print("The following snippet should be able to reproduce the error") exit_status = 1 sys.exit(exit_status)
python
def main(reraise_exceptions=False, **kwargs): """Main program. Catches several common errors and displays them nicely.""" exit_status = 0 try: cli.main(**kwargs) except SoftLayer.SoftLayerAPIError as ex: if 'invalid api token' in ex.faultString.lower(): print("Authentication Failed: To update your credentials, use 'slcli config setup'") exit_status = 1 else: print(str(ex)) exit_status = 1 except SoftLayer.SoftLayerError as ex: print(str(ex)) exit_status = 1 except exceptions.CLIAbort as ex: print(str(ex.message)) exit_status = ex.code except Exception: if reraise_exceptions: raise import traceback print("An unexpected error has occured:") print(str(traceback.format_exc())) print("Feel free to report this error as it is likely a bug:") print(" https://github.com/softlayer/softlayer-python/issues") print("The following snippet should be able to reproduce the error") exit_status = 1 sys.exit(exit_status)
[ "def", "main", "(", "reraise_exceptions", "=", "False", ",", "*", "*", "kwargs", ")", ":", "exit_status", "=", "0", "try", ":", "cli", ".", "main", "(", "*", "*", "kwargs", ")", "except", "SoftLayer", ".", "SoftLayerAPIError", "as", "ex", ":", "if", "'invalid api token'", "in", "ex", ".", "faultString", ".", "lower", "(", ")", ":", "print", "(", "\"Authentication Failed: To update your credentials, use 'slcli config setup'\"", ")", "exit_status", "=", "1", "else", ":", "print", "(", "str", "(", "ex", ")", ")", "exit_status", "=", "1", "except", "SoftLayer", ".", "SoftLayerError", "as", "ex", ":", "print", "(", "str", "(", "ex", ")", ")", "exit_status", "=", "1", "except", "exceptions", ".", "CLIAbort", "as", "ex", ":", "print", "(", "str", "(", "ex", ".", "message", ")", ")", "exit_status", "=", "ex", ".", "code", "except", "Exception", ":", "if", "reraise_exceptions", ":", "raise", "import", "traceback", "print", "(", "\"An unexpected error has occured:\"", ")", "print", "(", "str", "(", "traceback", ".", "format_exc", "(", ")", ")", ")", "print", "(", "\"Feel free to report this error as it is likely a bug:\"", ")", "print", "(", "\" https://github.com/softlayer/softlayer-python/issues\"", ")", "print", "(", "\"The following snippet should be able to reproduce the error\"", ")", "exit_status", "=", "1", "sys", ".", "exit", "(", "exit_status", ")" ]
Main program. Catches several common errors and displays them nicely.
[ "Main", "program", ".", "Catches", "several", "common", "errors", "and", "displays", "them", "nicely", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/core.py#L177-L208
1,363
softlayer/softlayer-python
SoftLayer/CLI/block/access/revoke.py
cli
def cli(env, volume_id, hardware_id, virtual_id, ip_address_id, ip_address): """Revokes authorization for hosts accessing a given volume""" block_manager = SoftLayer.BlockStorageManager(env.client) ip_address_id_list = list(ip_address_id) # Convert actual IP Addresses to their SoftLayer ids if ip_address is not None: network_manager = SoftLayer.NetworkManager(env.client) for ip_address_value in ip_address: ip_address_object = network_manager.ip_lookup(ip_address_value) ip_address_id_list.append(ip_address_object['id']) block_manager.deauthorize_host_to_volume(volume_id, hardware_id, virtual_id, ip_address_id_list) # If no exception was raised, the command succeeded click.echo('Access to %s was revoked for the specified hosts' % volume_id)
python
def cli(env, volume_id, hardware_id, virtual_id, ip_address_id, ip_address): """Revokes authorization for hosts accessing a given volume""" block_manager = SoftLayer.BlockStorageManager(env.client) ip_address_id_list = list(ip_address_id) # Convert actual IP Addresses to their SoftLayer ids if ip_address is not None: network_manager = SoftLayer.NetworkManager(env.client) for ip_address_value in ip_address: ip_address_object = network_manager.ip_lookup(ip_address_value) ip_address_id_list.append(ip_address_object['id']) block_manager.deauthorize_host_to_volume(volume_id, hardware_id, virtual_id, ip_address_id_list) # If no exception was raised, the command succeeded click.echo('Access to %s was revoked for the specified hosts' % volume_id)
[ "def", "cli", "(", "env", ",", "volume_id", ",", "hardware_id", ",", "virtual_id", ",", "ip_address_id", ",", "ip_address", ")", ":", "block_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "ip_address_id_list", "=", "list", "(", "ip_address_id", ")", "# Convert actual IP Addresses to their SoftLayer ids", "if", "ip_address", "is", "not", "None", ":", "network_manager", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "for", "ip_address_value", "in", "ip_address", ":", "ip_address_object", "=", "network_manager", ".", "ip_lookup", "(", "ip_address_value", ")", "ip_address_id_list", ".", "append", "(", "ip_address_object", "[", "'id'", "]", ")", "block_manager", ".", "deauthorize_host_to_volume", "(", "volume_id", ",", "hardware_id", ",", "virtual_id", ",", "ip_address_id_list", ")", "# If no exception was raised, the command succeeded", "click", ".", "echo", "(", "'Access to %s was revoked for the specified hosts'", "%", "volume_id", ")" ]
Revokes authorization for hosts accessing a given volume
[ "Revokes", "authorization", "for", "hosts", "accessing", "a", "given", "volume" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/access/revoke.py#L23-L41
1,364
softlayer/softlayer-python
SoftLayer/CLI/loadbal/group_add.py
cli
def cli(env, identifier, allocation, port, routing_type, routing_method): """Adds a new load_balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, loadbal_id = loadbal.parse_id(identifier) mgr.add_service_group(loadbal_id, allocation=allocation, port=port, routing_type=routing_type, routing_method=routing_method) env.fout('Load balancer service group is being added!')
python
def cli(env, identifier, allocation, port, routing_type, routing_method): """Adds a new load_balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, loadbal_id = loadbal.parse_id(identifier) mgr.add_service_group(loadbal_id, allocation=allocation, port=port, routing_type=routing_type, routing_method=routing_method) env.fout('Load balancer service group is being added!')
[ "def", "cli", "(", "env", ",", "identifier", ",", "allocation", ",", "port", ",", "routing_type", ",", "routing_method", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "_", ",", "loadbal_id", "=", "loadbal", ".", "parse_id", "(", "identifier", ")", "mgr", ".", "add_service_group", "(", "loadbal_id", ",", "allocation", "=", "allocation", ",", "port", "=", "port", ",", "routing_type", "=", "routing_type", ",", "routing_method", "=", "routing_method", ")", "env", ".", "fout", "(", "'Load balancer service group is being added!'", ")" ]
Adds a new load_balancer service.
[ "Adds", "a", "new", "load_balancer", "service", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/group_add.py#L28-L41
1,365
softlayer/softlayer-python
SoftLayer/CLI/dedicatedhost/cancel_guests.py
cli
def cli(env, identifier): """Cancel all virtual guests of the dedicated host immediately. Use the 'slcli vs cancel' command to cancel an specific guest """ dh_mgr = SoftLayer.DedicatedHostManager(env.client) host_id = helpers.resolve_id(dh_mgr.resolve_ids, identifier, 'dedicated host') if not (env.skip_confirmations or formatting.no_going_back(host_id)): raise exceptions.CLIAbort('Aborted') table = formatting.Table(['id', 'server name', 'status']) result = dh_mgr.cancel_guests(host_id) if result: for status in result: table.add_row([ status['id'], status['fqdn'], status['status'] ]) env.fout(table) else: click.secho('There is not any guest into the dedicated host %s' % host_id, fg='red')
python
def cli(env, identifier): """Cancel all virtual guests of the dedicated host immediately. Use the 'slcli vs cancel' command to cancel an specific guest """ dh_mgr = SoftLayer.DedicatedHostManager(env.client) host_id = helpers.resolve_id(dh_mgr.resolve_ids, identifier, 'dedicated host') if not (env.skip_confirmations or formatting.no_going_back(host_id)): raise exceptions.CLIAbort('Aborted') table = formatting.Table(['id', 'server name', 'status']) result = dh_mgr.cancel_guests(host_id) if result: for status in result: table.add_row([ status['id'], status['fqdn'], status['status'] ]) env.fout(table) else: click.secho('There is not any guest into the dedicated host %s' % host_id, fg='red')
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "dh_mgr", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "host_id", "=", "helpers", ".", "resolve_id", "(", "dh_mgr", ".", "resolve_ids", ",", "identifier", ",", "'dedicated host'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "host_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted'", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'server name'", ",", "'status'", "]", ")", "result", "=", "dh_mgr", ".", "cancel_guests", "(", "host_id", ")", "if", "result", ":", "for", "status", "in", "result", ":", "table", ".", "add_row", "(", "[", "status", "[", "'id'", "]", ",", "status", "[", "'fqdn'", "]", ",", "status", "[", "'status'", "]", "]", ")", "env", ".", "fout", "(", "table", ")", "else", ":", "click", ".", "secho", "(", "'There is not any guest into the dedicated host %s'", "%", "host_id", ",", "fg", "=", "'red'", ")" ]
Cancel all virtual guests of the dedicated host immediately. Use the 'slcli vs cancel' command to cancel an specific guest
[ "Cancel", "all", "virtual", "guests", "of", "the", "dedicated", "host", "immediately", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/cancel_guests.py#L16-L43
1,366
softlayer/softlayer-python
SoftLayer/CLI/file/list.py
cli
def cli(env, sortby, columns, datacenter, username, storage_type): """List file storage.""" file_manager = SoftLayer.FileStorageManager(env.client) file_volumes = file_manager.list_file_volumes(datacenter=datacenter, username=username, storage_type=storage_type, mask=columns.mask()) table = formatting.Table(columns.columns) table.sortby = sortby for file_volume in file_volumes: table.add_row([value or formatting.blank() for value in columns.row(file_volume)]) env.fout(table)
python
def cli(env, sortby, columns, datacenter, username, storage_type): """List file storage.""" file_manager = SoftLayer.FileStorageManager(env.client) file_volumes = file_manager.list_file_volumes(datacenter=datacenter, username=username, storage_type=storage_type, mask=columns.mask()) table = formatting.Table(columns.columns) table.sortby = sortby for file_volume in file_volumes: table.add_row([value or formatting.blank() for value in columns.row(file_volume)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "columns", ",", "datacenter", ",", "username", ",", "storage_type", ")", ":", "file_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "file_volumes", "=", "file_manager", ".", "list_file_volumes", "(", "datacenter", "=", "datacenter", ",", "username", "=", "username", ",", "storage_type", "=", "storage_type", ",", "mask", "=", "columns", ".", "mask", "(", ")", ")", "table", "=", "formatting", ".", "Table", "(", "columns", ".", "columns", ")", "table", ".", "sortby", "=", "sortby", "for", "file_volume", "in", "file_volumes", ":", "table", ".", "add_row", "(", "[", "value", "or", "formatting", ".", "blank", "(", ")", "for", "value", "in", "columns", ".", "row", "(", "file_volume", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List file storage.
[ "List", "file", "storage", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/list.py#L66-L81
1,367
softlayer/softlayer-python
SoftLayer/CLI/file/duplicate.py
cli
def cli(env, origin_volume_id, origin_snapshot_id, duplicate_size, duplicate_iops, duplicate_tier, duplicate_snapshot_size, billing): """Order a duplicate file storage volume.""" file_manager = SoftLayer.FileStorageManager(env.client) hourly_billing_flag = False if billing.lower() == "hourly": hourly_billing_flag = True if duplicate_tier is not None: duplicate_tier = float(duplicate_tier) try: order = file_manager.order_duplicate_volume( origin_volume_id, origin_snapshot_id=origin_snapshot_id, duplicate_size=duplicate_size, duplicate_iops=duplicate_iops, duplicate_tier_level=duplicate_tier, duplicate_snapshot_size=duplicate_snapshot_size, hourly_billing_flag=hourly_billing_flag ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order #{0} placed successfully!".format( order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) else: click.echo("Order could not be placed! Please verify your options " + "and try again.")
python
def cli(env, origin_volume_id, origin_snapshot_id, duplicate_size, duplicate_iops, duplicate_tier, duplicate_snapshot_size, billing): """Order a duplicate file storage volume.""" file_manager = SoftLayer.FileStorageManager(env.client) hourly_billing_flag = False if billing.lower() == "hourly": hourly_billing_flag = True if duplicate_tier is not None: duplicate_tier = float(duplicate_tier) try: order = file_manager.order_duplicate_volume( origin_volume_id, origin_snapshot_id=origin_snapshot_id, duplicate_size=duplicate_size, duplicate_iops=duplicate_iops, duplicate_tier_level=duplicate_tier, duplicate_snapshot_size=duplicate_snapshot_size, hourly_billing_flag=hourly_billing_flag ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order #{0} placed successfully!".format( order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) else: click.echo("Order could not be placed! Please verify your options " + "and try again.")
[ "def", "cli", "(", "env", ",", "origin_volume_id", ",", "origin_snapshot_id", ",", "duplicate_size", ",", "duplicate_iops", ",", "duplicate_tier", ",", "duplicate_snapshot_size", ",", "billing", ")", ":", "file_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "hourly_billing_flag", "=", "False", "if", "billing", ".", "lower", "(", ")", "==", "\"hourly\"", ":", "hourly_billing_flag", "=", "True", "if", "duplicate_tier", "is", "not", "None", ":", "duplicate_tier", "=", "float", "(", "duplicate_tier", ")", "try", ":", "order", "=", "file_manager", ".", "order_duplicate_volume", "(", "origin_volume_id", ",", "origin_snapshot_id", "=", "origin_snapshot_id", ",", "duplicate_size", "=", "duplicate_size", ",", "duplicate_iops", "=", "duplicate_iops", ",", "duplicate_tier_level", "=", "duplicate_tier", ",", "duplicate_snapshot_size", "=", "duplicate_snapshot_size", ",", "hourly_billing_flag", "=", "hourly_billing_flag", ")", "except", "ValueError", "as", "ex", ":", "raise", "exceptions", ".", "ArgumentError", "(", "str", "(", "ex", ")", ")", "if", "'placedOrder'", "in", "order", ".", "keys", "(", ")", ":", "click", ".", "echo", "(", "\"Order #{0} placed successfully!\"", ".", "format", "(", "order", "[", "'placedOrder'", "]", "[", "'id'", "]", ")", ")", "for", "item", "in", "order", "[", "'placedOrder'", "]", "[", "'items'", "]", ":", "click", ".", "echo", "(", "\" > %s\"", "%", "item", "[", "'description'", "]", ")", "else", ":", "click", ".", "echo", "(", "\"Order could not be placed! Please verify your options \"", "+", "\"and try again.\"", ")" ]
Order a duplicate file storage volume.
[ "Order", "a", "duplicate", "file", "storage", "volume", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/duplicate.py#L56-L88
1,368
softlayer/softlayer-python
SoftLayer/CLI/vpn/ipsec/subnet/remove.py
cli
def cli(env, context_id, subnet_id, subnet_type): """Remove a subnet from an IPSEC tunnel context. The subnet id to remove must be specified. Remote subnets are deleted upon removal from a tunnel context. A separate configuration request should be made to realize changes on network devices. """ manager = SoftLayer.IPSECManager(env.client) # ensure context can be retrieved by given id manager.get_tunnel_context(context_id) succeeded = False if subnet_type == 'internal': succeeded = manager.remove_internal_subnet(context_id, subnet_id) elif subnet_type == 'remote': succeeded = manager.remove_remote_subnet(context_id, subnet_id) elif subnet_type == 'service': succeeded = manager.remove_service_subnet(context_id, subnet_id) if succeeded: env.out('Removed {} subnet #{}'.format(subnet_type, subnet_id)) else: raise CLIHalt('Failed to remove {} subnet #{}' .format(subnet_type, subnet_id))
python
def cli(env, context_id, subnet_id, subnet_type): """Remove a subnet from an IPSEC tunnel context. The subnet id to remove must be specified. Remote subnets are deleted upon removal from a tunnel context. A separate configuration request should be made to realize changes on network devices. """ manager = SoftLayer.IPSECManager(env.client) # ensure context can be retrieved by given id manager.get_tunnel_context(context_id) succeeded = False if subnet_type == 'internal': succeeded = manager.remove_internal_subnet(context_id, subnet_id) elif subnet_type == 'remote': succeeded = manager.remove_remote_subnet(context_id, subnet_id) elif subnet_type == 'service': succeeded = manager.remove_service_subnet(context_id, subnet_id) if succeeded: env.out('Removed {} subnet #{}'.format(subnet_type, subnet_id)) else: raise CLIHalt('Failed to remove {} subnet #{}' .format(subnet_type, subnet_id))
[ "def", "cli", "(", "env", ",", "context_id", ",", "subnet_id", ",", "subnet_type", ")", ":", "manager", "=", "SoftLayer", ".", "IPSECManager", "(", "env", ".", "client", ")", "# ensure context can be retrieved by given id", "manager", ".", "get_tunnel_context", "(", "context_id", ")", "succeeded", "=", "False", "if", "subnet_type", "==", "'internal'", ":", "succeeded", "=", "manager", ".", "remove_internal_subnet", "(", "context_id", ",", "subnet_id", ")", "elif", "subnet_type", "==", "'remote'", ":", "succeeded", "=", "manager", ".", "remove_remote_subnet", "(", "context_id", ",", "subnet_id", ")", "elif", "subnet_type", "==", "'service'", ":", "succeeded", "=", "manager", ".", "remove_service_subnet", "(", "context_id", ",", "subnet_id", ")", "if", "succeeded", ":", "env", ".", "out", "(", "'Removed {} subnet #{}'", ".", "format", "(", "subnet_type", ",", "subnet_id", ")", ")", "else", ":", "raise", "CLIHalt", "(", "'Failed to remove {} subnet #{}'", ".", "format", "(", "subnet_type", ",", "subnet_id", ")", ")" ]
Remove a subnet from an IPSEC tunnel context. The subnet id to remove must be specified. Remote subnets are deleted upon removal from a tunnel context. A separate configuration request should be made to realize changes on network devices.
[ "Remove", "a", "subnet", "from", "an", "IPSEC", "tunnel", "context", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/subnet/remove.py#L25-L51
1,369
softlayer/softlayer-python
SoftLayer/CLI/ticket/list.py
cli
def cli(env, is_open): """List tickets.""" ticket_mgr = SoftLayer.TicketManager(env.client) table = formatting.Table([ 'id', 'assigned_user', 'title', 'last_edited', 'status', 'updates', 'priority' ]) tickets = ticket_mgr.list_tickets(open_status=is_open, closed_status=not is_open) for ticket in tickets: user = formatting.blank() if ticket.get('assignedUser'): user = "%s %s" % (ticket['assignedUser']['firstName'], ticket['assignedUser']['lastName']) table.add_row([ ticket['id'], user, click.wrap_text(ticket['title']), ticket['lastEditDate'], ticket['status']['name'], ticket.get('updateCount', 0), ticket.get('priority', 0) ]) env.fout(table)
python
def cli(env, is_open): """List tickets.""" ticket_mgr = SoftLayer.TicketManager(env.client) table = formatting.Table([ 'id', 'assigned_user', 'title', 'last_edited', 'status', 'updates', 'priority' ]) tickets = ticket_mgr.list_tickets(open_status=is_open, closed_status=not is_open) for ticket in tickets: user = formatting.blank() if ticket.get('assignedUser'): user = "%s %s" % (ticket['assignedUser']['firstName'], ticket['assignedUser']['lastName']) table.add_row([ ticket['id'], user, click.wrap_text(ticket['title']), ticket['lastEditDate'], ticket['status']['name'], ticket.get('updateCount', 0), ticket.get('priority', 0) ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "is_open", ")", ":", "ticket_mgr", "=", "SoftLayer", ".", "TicketManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'assigned_user'", ",", "'title'", ",", "'last_edited'", ",", "'status'", ",", "'updates'", ",", "'priority'", "]", ")", "tickets", "=", "ticket_mgr", ".", "list_tickets", "(", "open_status", "=", "is_open", ",", "closed_status", "=", "not", "is_open", ")", "for", "ticket", "in", "tickets", ":", "user", "=", "formatting", ".", "blank", "(", ")", "if", "ticket", ".", "get", "(", "'assignedUser'", ")", ":", "user", "=", "\"%s %s\"", "%", "(", "ticket", "[", "'assignedUser'", "]", "[", "'firstName'", "]", ",", "ticket", "[", "'assignedUser'", "]", "[", "'lastName'", "]", ")", "table", ".", "add_row", "(", "[", "ticket", "[", "'id'", "]", ",", "user", ",", "click", ".", "wrap_text", "(", "ticket", "[", "'title'", "]", ")", ",", "ticket", "[", "'lastEditDate'", "]", ",", "ticket", "[", "'status'", "]", "[", "'name'", "]", ",", "ticket", ".", "get", "(", "'updateCount'", ",", "0", ")", ",", "ticket", ".", "get", "(", "'priority'", ",", "0", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List tickets.
[ "List", "tickets", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/list.py#L15-L38
1,370
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/detail.py
cli
def cli(env, identifier): """Get details about a security group.""" mgr = SoftLayer.NetworkManager(env.client) secgroup = mgr.get_securitygroup(identifier) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', secgroup['id']]) table.add_row(['name', secgroup.get('name') or formatting.blank()]) table.add_row(['description', secgroup.get('description') or formatting.blank()]) rule_table = formatting.Table(['id', 'remoteIp', 'remoteGroupId', 'direction', 'ethertype', 'portRangeMin', 'portRangeMax', 'protocol']) for rule in secgroup.get('rules', []): rg_id = rule.get('remoteGroup', {}).get('id') or formatting.blank() port_min = rule.get('portRangeMin') port_max = rule.get('portRangeMax') if port_min is None: port_min = formatting.blank() if port_max is None: port_max = formatting.blank() rule_table.add_row([rule['id'], rule.get('remoteIp') or formatting.blank(), rule.get('remoteGroupId', rg_id), rule['direction'], rule.get('ethertype') or formatting.blank(), port_min, port_max, rule.get('protocol') or formatting.blank()]) table.add_row(['rules', rule_table]) vsi_table = formatting.Table(['id', 'hostname', 'interface', 'ipAddress']) for binding in secgroup.get('networkComponentBindings', []): try: vsi = binding['networkComponent']['guest'] vsi_id = vsi['id'] hostname = vsi['hostname'] interface = ('PRIVATE' if binding['networkComponent']['port'] == 0 else 'PUBLIC') ip_address = (vsi['primaryBackendIpAddress'] if binding['networkComponent']['port'] == 0 else vsi['primaryIpAddress']) except KeyError: vsi_id = "N/A" hostname = "Not enough permission to view" interface = "N/A" ip_address = "N/A" vsi_table.add_row([vsi_id, hostname, interface, ip_address]) table.add_row(['servers', vsi_table]) env.fout(table)
python
def cli(env, identifier): """Get details about a security group.""" mgr = SoftLayer.NetworkManager(env.client) secgroup = mgr.get_securitygroup(identifier) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', secgroup['id']]) table.add_row(['name', secgroup.get('name') or formatting.blank()]) table.add_row(['description', secgroup.get('description') or formatting.blank()]) rule_table = formatting.Table(['id', 'remoteIp', 'remoteGroupId', 'direction', 'ethertype', 'portRangeMin', 'portRangeMax', 'protocol']) for rule in secgroup.get('rules', []): rg_id = rule.get('remoteGroup', {}).get('id') or formatting.blank() port_min = rule.get('portRangeMin') port_max = rule.get('portRangeMax') if port_min is None: port_min = formatting.blank() if port_max is None: port_max = formatting.blank() rule_table.add_row([rule['id'], rule.get('remoteIp') or formatting.blank(), rule.get('remoteGroupId', rg_id), rule['direction'], rule.get('ethertype') or formatting.blank(), port_min, port_max, rule.get('protocol') or formatting.blank()]) table.add_row(['rules', rule_table]) vsi_table = formatting.Table(['id', 'hostname', 'interface', 'ipAddress']) for binding in secgroup.get('networkComponentBindings', []): try: vsi = binding['networkComponent']['guest'] vsi_id = vsi['id'] hostname = vsi['hostname'] interface = ('PRIVATE' if binding['networkComponent']['port'] == 0 else 'PUBLIC') ip_address = (vsi['primaryBackendIpAddress'] if binding['networkComponent']['port'] == 0 else vsi['primaryIpAddress']) except KeyError: vsi_id = "N/A" hostname = "Not enough permission to view" interface = "N/A" ip_address = "N/A" vsi_table.add_row([vsi_id, hostname, interface, ip_address]) table.add_row(['servers', vsi_table]) env.fout(table)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "secgroup", "=", "mgr", ".", "get_securitygroup", "(", "identifier", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "table", ".", "add_row", "(", "[", "'id'", ",", "secgroup", "[", "'id'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'name'", ",", "secgroup", ".", "get", "(", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", "]", ")", "table", ".", "add_row", "(", "[", "'description'", ",", "secgroup", ".", "get", "(", "'description'", ")", "or", "formatting", ".", "blank", "(", ")", "]", ")", "rule_table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'remoteIp'", ",", "'remoteGroupId'", ",", "'direction'", ",", "'ethertype'", ",", "'portRangeMin'", ",", "'portRangeMax'", ",", "'protocol'", "]", ")", "for", "rule", "in", "secgroup", ".", "get", "(", "'rules'", ",", "[", "]", ")", ":", "rg_id", "=", "rule", ".", "get", "(", "'remoteGroup'", ",", "{", "}", ")", ".", "get", "(", "'id'", ")", "or", "formatting", ".", "blank", "(", ")", "port_min", "=", "rule", ".", "get", "(", "'portRangeMin'", ")", "port_max", "=", "rule", ".", "get", "(", "'portRangeMax'", ")", "if", "port_min", "is", "None", ":", "port_min", "=", "formatting", ".", "blank", "(", ")", "if", "port_max", "is", "None", ":", "port_max", "=", "formatting", ".", "blank", "(", ")", "rule_table", ".", "add_row", "(", "[", "rule", "[", "'id'", "]", ",", "rule", ".", "get", "(", "'remoteIp'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "rule", ".", "get", "(", "'remoteGroupId'", ",", "rg_id", ")", ",", "rule", "[", "'direction'", "]", ",", "rule", ".", "get", "(", "'ethertype'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "port_min", ",", "port_max", ",", "rule", ".", "get", "(", "'protocol'", ")", "or", "formatting", ".", "blank", "(", ")", "]", ")", "table", ".", "add_row", "(", "[", "'rules'", ",", "rule_table", "]", ")", "vsi_table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'hostname'", ",", "'interface'", ",", "'ipAddress'", "]", ")", "for", "binding", "in", "secgroup", ".", "get", "(", "'networkComponentBindings'", ",", "[", "]", ")", ":", "try", ":", "vsi", "=", "binding", "[", "'networkComponent'", "]", "[", "'guest'", "]", "vsi_id", "=", "vsi", "[", "'id'", "]", "hostname", "=", "vsi", "[", "'hostname'", "]", "interface", "=", "(", "'PRIVATE'", "if", "binding", "[", "'networkComponent'", "]", "[", "'port'", "]", "==", "0", "else", "'PUBLIC'", ")", "ip_address", "=", "(", "vsi", "[", "'primaryBackendIpAddress'", "]", "if", "binding", "[", "'networkComponent'", "]", "[", "'port'", "]", "==", "0", "else", "vsi", "[", "'primaryIpAddress'", "]", ")", "except", "KeyError", ":", "vsi_id", "=", "\"N/A\"", "hostname", "=", "\"Not enough permission to view\"", "interface", "=", "\"N/A\"", "ip_address", "=", "\"N/A\"", "vsi_table", ".", "add_row", "(", "[", "vsi_id", ",", "hostname", ",", "interface", ",", "ip_address", "]", ")", "table", ".", "add_row", "(", "[", "'servers'", ",", "vsi_table", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Get details about a security group.
[ "Get", "details", "about", "a", "security", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/detail.py#L14-L73
1,371
softlayer/softlayer-python
SoftLayer/CLI/dns/record_add.py
cli
def cli(env, record, record_type, data, zone, ttl, priority, protocol, port, service, weight): """Add resource record. Each resource record contains a RECORD and DATA property, defining a resource's name and it's target data. Domains contain multiple types of resource records so it can take one of the following values: A, AAAA, CNAME, MX, SPF, SRV, and PTR. About reverse records (PTR), the RECORD value must to be the public Ip Address of device you would like to manage reverse DNS. slcli dns record-add 10.10.8.21 PTR myhost.com --ttl=900 Examples: slcli dns record-add myhost.com A 192.168.1.10 --zone=foobar.com --ttl=900 slcli dns record-add myhost.com AAAA 2001:DB8::1 --zone=foobar.com slcli dns record-add 192.168.1.2 MX 192.168.1.10 --zone=foobar.com --priority=11 --ttl=1800 slcli dns record-add myhost.com TXT "txt-verification=rXOxyZounZs87oacJSKvbUSIQ" --zone=2223334 slcli dns record-add myhost.com SPF "v=spf1 include:_spf.google.com ~all" --zone=2223334 slcli dns record-add myhost.com SRV 192.168.1.10 --zone=2223334 --service=foobar --port=80 --protocol=TCP """ manager = SoftLayer.DNSManager(env.client) record_type = record_type.upper() if zone and record_type != 'PTR': zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone') if record_type == 'MX': manager.create_record_mx(zone_id, record, data, ttl=ttl, priority=priority) elif record_type == 'SRV': manager.create_record_srv(zone_id, record, data, protocol, port, service, ttl=ttl, priority=priority, weight=weight) else: manager.create_record(zone_id, record, record_type, data, ttl=ttl) elif record_type == 'PTR': manager.create_record_ptr(record, data, ttl=ttl) else: raise exceptions.CLIAbort("%s isn't a valid record type or zone is missing" % record_type) click.secho("%s record added successfully" % record_type, fg='green')
python
def cli(env, record, record_type, data, zone, ttl, priority, protocol, port, service, weight): """Add resource record. Each resource record contains a RECORD and DATA property, defining a resource's name and it's target data. Domains contain multiple types of resource records so it can take one of the following values: A, AAAA, CNAME, MX, SPF, SRV, and PTR. About reverse records (PTR), the RECORD value must to be the public Ip Address of device you would like to manage reverse DNS. slcli dns record-add 10.10.8.21 PTR myhost.com --ttl=900 Examples: slcli dns record-add myhost.com A 192.168.1.10 --zone=foobar.com --ttl=900 slcli dns record-add myhost.com AAAA 2001:DB8::1 --zone=foobar.com slcli dns record-add 192.168.1.2 MX 192.168.1.10 --zone=foobar.com --priority=11 --ttl=1800 slcli dns record-add myhost.com TXT "txt-verification=rXOxyZounZs87oacJSKvbUSIQ" --zone=2223334 slcli dns record-add myhost.com SPF "v=spf1 include:_spf.google.com ~all" --zone=2223334 slcli dns record-add myhost.com SRV 192.168.1.10 --zone=2223334 --service=foobar --port=80 --protocol=TCP """ manager = SoftLayer.DNSManager(env.client) record_type = record_type.upper() if zone and record_type != 'PTR': zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone') if record_type == 'MX': manager.create_record_mx(zone_id, record, data, ttl=ttl, priority=priority) elif record_type == 'SRV': manager.create_record_srv(zone_id, record, data, protocol, port, service, ttl=ttl, priority=priority, weight=weight) else: manager.create_record(zone_id, record, record_type, data, ttl=ttl) elif record_type == 'PTR': manager.create_record_ptr(record, data, ttl=ttl) else: raise exceptions.CLIAbort("%s isn't a valid record type or zone is missing" % record_type) click.secho("%s record added successfully" % record_type, fg='green')
[ "def", "cli", "(", "env", ",", "record", ",", "record_type", ",", "data", ",", "zone", ",", "ttl", ",", "priority", ",", "protocol", ",", "port", ",", "service", ",", "weight", ")", ":", "manager", "=", "SoftLayer", ".", "DNSManager", "(", "env", ".", "client", ")", "record_type", "=", "record_type", ".", "upper", "(", ")", "if", "zone", "and", "record_type", "!=", "'PTR'", ":", "zone_id", "=", "helpers", ".", "resolve_id", "(", "manager", ".", "resolve_ids", ",", "zone", ",", "name", "=", "'zone'", ")", "if", "record_type", "==", "'MX'", ":", "manager", ".", "create_record_mx", "(", "zone_id", ",", "record", ",", "data", ",", "ttl", "=", "ttl", ",", "priority", "=", "priority", ")", "elif", "record_type", "==", "'SRV'", ":", "manager", ".", "create_record_srv", "(", "zone_id", ",", "record", ",", "data", ",", "protocol", ",", "port", ",", "service", ",", "ttl", "=", "ttl", ",", "priority", "=", "priority", ",", "weight", "=", "weight", ")", "else", ":", "manager", ".", "create_record", "(", "zone_id", ",", "record", ",", "record_type", ",", "data", ",", "ttl", "=", "ttl", ")", "elif", "record_type", "==", "'PTR'", ":", "manager", ".", "create_record_ptr", "(", "record", ",", "data", ",", "ttl", "=", "ttl", ")", "else", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"%s isn't a valid record type or zone is missing\"", "%", "record_type", ")", "click", ".", "secho", "(", "\"%s record added successfully\"", "%", "record_type", ",", "fg", "=", "'green'", ")" ]
Add resource record. Each resource record contains a RECORD and DATA property, defining a resource's name and it's target data. Domains contain multiple types of resource records so it can take one of the following values: A, AAAA, CNAME, MX, SPF, SRV, and PTR. About reverse records (PTR), the RECORD value must to be the public Ip Address of device you would like to manage reverse DNS. slcli dns record-add 10.10.8.21 PTR myhost.com --ttl=900 Examples: slcli dns record-add myhost.com A 192.168.1.10 --zone=foobar.com --ttl=900 slcli dns record-add myhost.com AAAA 2001:DB8::1 --zone=foobar.com slcli dns record-add 192.168.1.2 MX 192.168.1.10 --zone=foobar.com --priority=11 --ttl=1800 slcli dns record-add myhost.com TXT "txt-verification=rXOxyZounZs87oacJSKvbUSIQ" --zone=2223334 slcli dns record-add myhost.com SPF "v=spf1 include:_spf.google.com ~all" --zone=2223334 slcli dns record-add myhost.com SRV 192.168.1.10 --zone=2223334 --service=foobar --port=80 --protocol=TCP
[ "Add", "resource", "record", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/record_add.py#L43-L90
1,372
softlayer/softlayer-python
SoftLayer/CLI/loadbal/cancel.py
cli
def cli(env, identifier): """Cancel an existing load balancer.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, loadbal_id = loadbal.parse_id(identifier) if not (env.skip_confirmations or formatting.confirm("This action will cancel a load balancer. " "Continue?")): raise exceptions.CLIAbort('Aborted.') mgr.cancel_lb(loadbal_id) env.fout('Load Balancer with id %s is being cancelled!' % identifier)
python
def cli(env, identifier): """Cancel an existing load balancer.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, loadbal_id = loadbal.parse_id(identifier) if not (env.skip_confirmations or formatting.confirm("This action will cancel a load balancer. " "Continue?")): raise exceptions.CLIAbort('Aborted.') mgr.cancel_lb(loadbal_id) env.fout('Load Balancer with id %s is being cancelled!' % identifier)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "_", ",", "loadbal_id", "=", "loadbal", ".", "parse_id", "(", "identifier", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "confirm", "(", "\"This action will cancel a load balancer. \"", "\"Continue?\"", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted.'", ")", "mgr", ".", "cancel_lb", "(", "loadbal_id", ")", "env", ".", "fout", "(", "'Load Balancer with id %s is being cancelled!'", "%", "identifier", ")" ]
Cancel an existing load balancer.
[ "Cancel", "an", "existing", "load", "balancer", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/cancel.py#L16-L29
1,373
softlayer/softlayer-python
SoftLayer/CLI/order/preset_list.py
cli
def cli(env, package_keyname, keyword): """List package presets. .. Note:: Presets are set CPU / RAM / Disk allotments. You still need to specify required items. Some packages do not have presets. :: # List the presets for Bare Metal servers slcli order preset-list BARE_METAL_SERVER # List the Bare Metal server presets that include a GPU slcli order preset-list BARE_METAL_SERVER --keyword gpu """ table = formatting.Table(COLUMNS) manager = ordering.OrderingManager(env.client) _filter = {} if keyword: _filter = {'activePresets': {'name': {'operation': '*= %s' % keyword}}} presets = manager.list_presets(package_keyname, filter=_filter) for preset in presets: table.add_row([ preset['name'], preset['keyName'], preset['description'] ]) env.fout(table)
python
def cli(env, package_keyname, keyword): """List package presets. .. Note:: Presets are set CPU / RAM / Disk allotments. You still need to specify required items. Some packages do not have presets. :: # List the presets for Bare Metal servers slcli order preset-list BARE_METAL_SERVER # List the Bare Metal server presets that include a GPU slcli order preset-list BARE_METAL_SERVER --keyword gpu """ table = formatting.Table(COLUMNS) manager = ordering.OrderingManager(env.client) _filter = {} if keyword: _filter = {'activePresets': {'name': {'operation': '*= %s' % keyword}}} presets = manager.list_presets(package_keyname, filter=_filter) for preset in presets: table.add_row([ preset['name'], preset['keyName'], preset['description'] ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "package_keyname", ",", "keyword", ")", ":", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "_filter", "=", "{", "}", "if", "keyword", ":", "_filter", "=", "{", "'activePresets'", ":", "{", "'name'", ":", "{", "'operation'", ":", "'*= %s'", "%", "keyword", "}", "}", "}", "presets", "=", "manager", ".", "list_presets", "(", "package_keyname", ",", "filter", "=", "_filter", ")", "for", "preset", "in", "presets", ":", "table", ".", "add_row", "(", "[", "preset", "[", "'name'", "]", ",", "preset", "[", "'keyName'", "]", ",", "preset", "[", "'description'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List package presets. .. Note:: Presets are set CPU / RAM / Disk allotments. You still need to specify required items. Some packages do not have presets. :: # List the presets for Bare Metal servers slcli order preset-list BARE_METAL_SERVER # List the Bare Metal server presets that include a GPU slcli order preset-list BARE_METAL_SERVER --keyword gpu
[ "List", "package", "presets", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/preset_list.py#L20-L50
1,374
softlayer/softlayer-python
SoftLayer/CLI/user/permissions.py
permission_table
def permission_table(user_permissions, all_permissions): """Creates a table of available permissions""" table = formatting.Table(['Description', 'KeyName', 'Assigned']) table.align['KeyName'] = 'l' table.align['Description'] = 'l' table.align['Assigned'] = 'l' for perm in all_permissions: assigned = user_permissions.get(perm['keyName'], False) table.add_row([perm['name'], perm['keyName'], assigned]) return table
python
def permission_table(user_permissions, all_permissions): """Creates a table of available permissions""" table = formatting.Table(['Description', 'KeyName', 'Assigned']) table.align['KeyName'] = 'l' table.align['Description'] = 'l' table.align['Assigned'] = 'l' for perm in all_permissions: assigned = user_permissions.get(perm['keyName'], False) table.add_row([perm['name'], perm['keyName'], assigned]) return table
[ "def", "permission_table", "(", "user_permissions", ",", "all_permissions", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Description'", ",", "'KeyName'", ",", "'Assigned'", "]", ")", "table", ".", "align", "[", "'KeyName'", "]", "=", "'l'", "table", ".", "align", "[", "'Description'", "]", "=", "'l'", "table", ".", "align", "[", "'Assigned'", "]", "=", "'l'", "for", "perm", "in", "all_permissions", ":", "assigned", "=", "user_permissions", ".", "get", "(", "perm", "[", "'keyName'", "]", ",", "False", ")", "table", ".", "add_row", "(", "[", "perm", "[", "'name'", "]", ",", "perm", "[", "'keyName'", "]", ",", "assigned", "]", ")", "return", "table" ]
Creates a table of available permissions
[ "Creates", "a", "table", "of", "available", "permissions" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/permissions.py#L39-L49
1,375
softlayer/softlayer-python
SoftLayer/CLI/user/permissions.py
roles_table
def roles_table(user): """Creates a table for a users roles""" table = formatting.Table(['id', 'Role Name', 'Description']) for role in user['roles']: table.add_row([role['id'], role['name'], role['description']]) return table
python
def roles_table(user): """Creates a table for a users roles""" table = formatting.Table(['id', 'Role Name', 'Description']) for role in user['roles']: table.add_row([role['id'], role['name'], role['description']]) return table
[ "def", "roles_table", "(", "user", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'Role Name'", ",", "'Description'", "]", ")", "for", "role", "in", "user", "[", "'roles'", "]", ":", "table", ".", "add_row", "(", "[", "role", "[", "'id'", "]", ",", "role", "[", "'name'", "]", ",", "role", "[", "'description'", "]", "]", ")", "return", "table" ]
Creates a table for a users roles
[ "Creates", "a", "table", "for", "a", "users", "roles" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/permissions.py#L52-L57
1,376
softlayer/softlayer-python
SoftLayer/CLI/virt/create.py
_update_with_like_args
def _update_with_like_args(ctx, _, value): """Update arguments with options taken from a currently running VS.""" if value is None: return env = ctx.ensure_object(environment.Environment) vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, value, 'VS') like_details = vsi.get_instance(vs_id) like_args = { 'hostname': like_details['hostname'], 'domain': like_details['domain'], 'hourly': like_details['hourlyBillingFlag'], 'datacenter': like_details['datacenter']['name'], 'network': like_details['networkComponents'][0]['maxSpeed'], 'userdata': like_details['userData'] or None, 'postinstall': like_details.get('postInstallScriptUri'), 'dedicated': like_details['dedicatedAccountHostOnlyFlag'], 'private': like_details['privateNetworkOnlyFlag'], 'placement_id': like_details.get('placementGroupId', None), } like_args['flavor'] = utils.lookup(like_details, 'billingItem', 'orderItem', 'preset', 'keyName') if not like_args['flavor']: like_args['cpu'] = like_details['maxCpu'] like_args['memory'] = '%smb' % like_details['maxMemory'] tag_refs = like_details.get('tagReferences', None) if tag_refs is not None and len(tag_refs) > 0: like_args['tag'] = [t['tag']['name'] for t in tag_refs] # Handle mutually exclusive options like_image = utils.lookup(like_details, 'blockDeviceTemplateGroup', 'globalIdentifier') like_os = utils.lookup(like_details, 'operatingSystem', 'softwareLicense', 'softwareDescription', 'referenceCode') if like_image: like_args['image'] = like_image elif like_os: like_args['os'] = like_os if ctx.default_map is None: ctx.default_map = {} ctx.default_map.update(like_args)
python
def _update_with_like_args(ctx, _, value): """Update arguments with options taken from a currently running VS.""" if value is None: return env = ctx.ensure_object(environment.Environment) vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, value, 'VS') like_details = vsi.get_instance(vs_id) like_args = { 'hostname': like_details['hostname'], 'domain': like_details['domain'], 'hourly': like_details['hourlyBillingFlag'], 'datacenter': like_details['datacenter']['name'], 'network': like_details['networkComponents'][0]['maxSpeed'], 'userdata': like_details['userData'] or None, 'postinstall': like_details.get('postInstallScriptUri'), 'dedicated': like_details['dedicatedAccountHostOnlyFlag'], 'private': like_details['privateNetworkOnlyFlag'], 'placement_id': like_details.get('placementGroupId', None), } like_args['flavor'] = utils.lookup(like_details, 'billingItem', 'orderItem', 'preset', 'keyName') if not like_args['flavor']: like_args['cpu'] = like_details['maxCpu'] like_args['memory'] = '%smb' % like_details['maxMemory'] tag_refs = like_details.get('tagReferences', None) if tag_refs is not None and len(tag_refs) > 0: like_args['tag'] = [t['tag']['name'] for t in tag_refs] # Handle mutually exclusive options like_image = utils.lookup(like_details, 'blockDeviceTemplateGroup', 'globalIdentifier') like_os = utils.lookup(like_details, 'operatingSystem', 'softwareLicense', 'softwareDescription', 'referenceCode') if like_image: like_args['image'] = like_image elif like_os: like_args['os'] = like_os if ctx.default_map is None: ctx.default_map = {} ctx.default_map.update(like_args)
[ "def", "_update_with_like_args", "(", "ctx", ",", "_", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "env", "=", "ctx", ".", "ensure_object", "(", "environment", ".", "Environment", ")", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", "value", ",", "'VS'", ")", "like_details", "=", "vsi", ".", "get_instance", "(", "vs_id", ")", "like_args", "=", "{", "'hostname'", ":", "like_details", "[", "'hostname'", "]", ",", "'domain'", ":", "like_details", "[", "'domain'", "]", ",", "'hourly'", ":", "like_details", "[", "'hourlyBillingFlag'", "]", ",", "'datacenter'", ":", "like_details", "[", "'datacenter'", "]", "[", "'name'", "]", ",", "'network'", ":", "like_details", "[", "'networkComponents'", "]", "[", "0", "]", "[", "'maxSpeed'", "]", ",", "'userdata'", ":", "like_details", "[", "'userData'", "]", "or", "None", ",", "'postinstall'", ":", "like_details", ".", "get", "(", "'postInstallScriptUri'", ")", ",", "'dedicated'", ":", "like_details", "[", "'dedicatedAccountHostOnlyFlag'", "]", ",", "'private'", ":", "like_details", "[", "'privateNetworkOnlyFlag'", "]", ",", "'placement_id'", ":", "like_details", ".", "get", "(", "'placementGroupId'", ",", "None", ")", ",", "}", "like_args", "[", "'flavor'", "]", "=", "utils", ".", "lookup", "(", "like_details", ",", "'billingItem'", ",", "'orderItem'", ",", "'preset'", ",", "'keyName'", ")", "if", "not", "like_args", "[", "'flavor'", "]", ":", "like_args", "[", "'cpu'", "]", "=", "like_details", "[", "'maxCpu'", "]", "like_args", "[", "'memory'", "]", "=", "'%smb'", "%", "like_details", "[", "'maxMemory'", "]", "tag_refs", "=", "like_details", ".", "get", "(", "'tagReferences'", ",", "None", ")", "if", "tag_refs", "is", "not", "None", "and", "len", "(", "tag_refs", ")", ">", "0", ":", "like_args", "[", "'tag'", "]", "=", "[", "t", "[", "'tag'", "]", "[", "'name'", "]", "for", "t", "in", "tag_refs", "]", "# Handle mutually exclusive options", "like_image", "=", "utils", ".", "lookup", "(", "like_details", ",", "'blockDeviceTemplateGroup'", ",", "'globalIdentifier'", ")", "like_os", "=", "utils", ".", "lookup", "(", "like_details", ",", "'operatingSystem'", ",", "'softwareLicense'", ",", "'softwareDescription'", ",", "'referenceCode'", ")", "if", "like_image", ":", "like_args", "[", "'image'", "]", "=", "like_image", "elif", "like_os", ":", "like_args", "[", "'os'", "]", "=", "like_os", "if", "ctx", ".", "default_map", "is", "None", ":", "ctx", ".", "default_map", "=", "{", "}", "ctx", ".", "default_map", ".", "update", "(", "like_args", ")" ]
Update arguments with options taken from a currently running VS.
[ "Update", "arguments", "with", "options", "taken", "from", "a", "currently", "running", "VS", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/create.py#L16-L67
1,377
softlayer/softlayer-python
SoftLayer/CLI/virt/create.py
_build_receipt_table
def _build_receipt_table(result, billing="hourly", test=False): """Retrieve the total recurring fee of the items prices""" title = "OrderId: %s" % (result.get('orderId', 'No order placed')) table = formatting.Table(['Cost', 'Description'], title=title) table.align['Cost'] = 'r' table.align['Description'] = 'l' total = 0.000 if test: prices = result['prices'] else: prices = result['orderDetails']['prices'] for item in prices: rate = 0.000 if billing == "hourly": rate += float(item.get('hourlyRecurringFee', 0.000)) else: rate += float(item.get('recurringFee', 0.000)) total += rate table.add_row([rate, item['item']['description']]) table.add_row(["%.3f" % total, "Total %s cost" % billing]) return table
python
def _build_receipt_table(result, billing="hourly", test=False): """Retrieve the total recurring fee of the items prices""" title = "OrderId: %s" % (result.get('orderId', 'No order placed')) table = formatting.Table(['Cost', 'Description'], title=title) table.align['Cost'] = 'r' table.align['Description'] = 'l' total = 0.000 if test: prices = result['prices'] else: prices = result['orderDetails']['prices'] for item in prices: rate = 0.000 if billing == "hourly": rate += float(item.get('hourlyRecurringFee', 0.000)) else: rate += float(item.get('recurringFee', 0.000)) total += rate table.add_row([rate, item['item']['description']]) table.add_row(["%.3f" % total, "Total %s cost" % billing]) return table
[ "def", "_build_receipt_table", "(", "result", ",", "billing", "=", "\"hourly\"", ",", "test", "=", "False", ")", ":", "title", "=", "\"OrderId: %s\"", "%", "(", "result", ".", "get", "(", "'orderId'", ",", "'No order placed'", ")", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'Cost'", ",", "'Description'", "]", ",", "title", "=", "title", ")", "table", ".", "align", "[", "'Cost'", "]", "=", "'r'", "table", ".", "align", "[", "'Description'", "]", "=", "'l'", "total", "=", "0.000", "if", "test", ":", "prices", "=", "result", "[", "'prices'", "]", "else", ":", "prices", "=", "result", "[", "'orderDetails'", "]", "[", "'prices'", "]", "for", "item", "in", "prices", ":", "rate", "=", "0.000", "if", "billing", "==", "\"hourly\"", ":", "rate", "+=", "float", "(", "item", ".", "get", "(", "'hourlyRecurringFee'", ",", "0.000", ")", ")", "else", ":", "rate", "+=", "float", "(", "item", ".", "get", "(", "'recurringFee'", ",", "0.000", ")", ")", "total", "+=", "rate", "table", ".", "add_row", "(", "[", "rate", ",", "item", "[", "'item'", "]", "[", "'description'", "]", "]", ")", "table", ".", "add_row", "(", "[", "\"%.3f\"", "%", "total", ",", "\"Total %s cost\"", "%", "billing", "]", ")", "return", "table" ]
Retrieve the total recurring fee of the items prices
[ "Retrieve", "the", "total", "recurring", "fee", "of", "the", "items", "prices" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/create.py#L239-L260
1,378
softlayer/softlayer-python
SoftLayer/CLI/virt/create.py
_validate_args
def _validate_args(env, args): """Raises an ArgumentError if the given arguments are not valid.""" if all([args['cpu'], args['flavor']]): raise exceptions.ArgumentError( '[-c | --cpu] not allowed with [-f | --flavor]') if all([args['memory'], args['flavor']]): raise exceptions.ArgumentError( '[-m | --memory] not allowed with [-f | --flavor]') if all([args['dedicated'], args['flavor']]): raise exceptions.ArgumentError( '[-d | --dedicated] not allowed with [-f | --flavor]') if all([args['host_id'], args['flavor']]): raise exceptions.ArgumentError( '[-h | --host-id] not allowed with [-f | --flavor]') if all([args['userdata'], args['userfile']]): raise exceptions.ArgumentError( '[-u | --userdata] not allowed with [-F | --userfile]') image_args = [args['os'], args['image']] if all(image_args): raise exceptions.ArgumentError( '[-o | --os] not allowed with [--image]') while not any([args['os'], args['image']]): args['os'] = env.input("Operating System Code", default="", show_default=False) if not args['os']: args['image'] = env.input("Image", default="", show_default=False)
python
def _validate_args(env, args): """Raises an ArgumentError if the given arguments are not valid.""" if all([args['cpu'], args['flavor']]): raise exceptions.ArgumentError( '[-c | --cpu] not allowed with [-f | --flavor]') if all([args['memory'], args['flavor']]): raise exceptions.ArgumentError( '[-m | --memory] not allowed with [-f | --flavor]') if all([args['dedicated'], args['flavor']]): raise exceptions.ArgumentError( '[-d | --dedicated] not allowed with [-f | --flavor]') if all([args['host_id'], args['flavor']]): raise exceptions.ArgumentError( '[-h | --host-id] not allowed with [-f | --flavor]') if all([args['userdata'], args['userfile']]): raise exceptions.ArgumentError( '[-u | --userdata] not allowed with [-F | --userfile]') image_args = [args['os'], args['image']] if all(image_args): raise exceptions.ArgumentError( '[-o | --os] not allowed with [--image]') while not any([args['os'], args['image']]): args['os'] = env.input("Operating System Code", default="", show_default=False) if not args['os']: args['image'] = env.input("Image", default="", show_default=False)
[ "def", "_validate_args", "(", "env", ",", "args", ")", ":", "if", "all", "(", "[", "args", "[", "'cpu'", "]", ",", "args", "[", "'flavor'", "]", "]", ")", ":", "raise", "exceptions", ".", "ArgumentError", "(", "'[-c | --cpu] not allowed with [-f | --flavor]'", ")", "if", "all", "(", "[", "args", "[", "'memory'", "]", ",", "args", "[", "'flavor'", "]", "]", ")", ":", "raise", "exceptions", ".", "ArgumentError", "(", "'[-m | --memory] not allowed with [-f | --flavor]'", ")", "if", "all", "(", "[", "args", "[", "'dedicated'", "]", ",", "args", "[", "'flavor'", "]", "]", ")", ":", "raise", "exceptions", ".", "ArgumentError", "(", "'[-d | --dedicated] not allowed with [-f | --flavor]'", ")", "if", "all", "(", "[", "args", "[", "'host_id'", "]", ",", "args", "[", "'flavor'", "]", "]", ")", ":", "raise", "exceptions", ".", "ArgumentError", "(", "'[-h | --host-id] not allowed with [-f | --flavor]'", ")", "if", "all", "(", "[", "args", "[", "'userdata'", "]", ",", "args", "[", "'userfile'", "]", "]", ")", ":", "raise", "exceptions", ".", "ArgumentError", "(", "'[-u | --userdata] not allowed with [-F | --userfile]'", ")", "image_args", "=", "[", "args", "[", "'os'", "]", ",", "args", "[", "'image'", "]", "]", "if", "all", "(", "image_args", ")", ":", "raise", "exceptions", ".", "ArgumentError", "(", "'[-o | --os] not allowed with [--image]'", ")", "while", "not", "any", "(", "[", "args", "[", "'os'", "]", ",", "args", "[", "'image'", "]", "]", ")", ":", "args", "[", "'os'", "]", "=", "env", ".", "input", "(", "\"Operating System Code\"", ",", "default", "=", "\"\"", ",", "show_default", "=", "False", ")", "if", "not", "args", "[", "'os'", "]", ":", "args", "[", "'image'", "]", "=", "env", ".", "input", "(", "\"Image\"", ",", "default", "=", "\"\"", ",", "show_default", "=", "False", ")" ]
Raises an ArgumentError if the given arguments are not valid.
[ "Raises", "an", "ArgumentError", "if", "the", "given", "arguments", "are", "not", "valid", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/create.py#L273-L304
1,379
softlayer/softlayer-python
SoftLayer/CLI/virt/upgrade.py
cli
def cli(env, identifier, cpu, private, memory, network, flavor): """Upgrade a virtual server.""" vsi = SoftLayer.VSManager(env.client) if not any([cpu, memory, network, flavor]): raise exceptions.ArgumentError("Must provide [--cpu], [--memory], [--network], or [--flavor] to upgrade") if private and not cpu: raise exceptions.ArgumentError("Must specify [--cpu] when using [--private]") vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.confirm("This action will incur charges on your account. Continue?")): raise exceptions.CLIAbort('Aborted') if memory: memory = int(memory / 1024) if not vsi.upgrade(vs_id, cpus=cpu, memory=memory, nic_speed=network, public=not private, preset=flavor): raise exceptions.CLIAbort('VS Upgrade Failed')
python
def cli(env, identifier, cpu, private, memory, network, flavor): """Upgrade a virtual server.""" vsi = SoftLayer.VSManager(env.client) if not any([cpu, memory, network, flavor]): raise exceptions.ArgumentError("Must provide [--cpu], [--memory], [--network], or [--flavor] to upgrade") if private and not cpu: raise exceptions.ArgumentError("Must specify [--cpu] when using [--private]") vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.confirm("This action will incur charges on your account. Continue?")): raise exceptions.CLIAbort('Aborted') if memory: memory = int(memory / 1024) if not vsi.upgrade(vs_id, cpus=cpu, memory=memory, nic_speed=network, public=not private, preset=flavor): raise exceptions.CLIAbort('VS Upgrade Failed')
[ "def", "cli", "(", "env", ",", "identifier", ",", "cpu", ",", "private", ",", "memory", ",", "network", ",", "flavor", ")", ":", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "if", "not", "any", "(", "[", "cpu", ",", "memory", ",", "network", ",", "flavor", "]", ")", ":", "raise", "exceptions", ".", "ArgumentError", "(", "\"Must provide [--cpu], [--memory], [--network], or [--flavor] to upgrade\"", ")", "if", "private", "and", "not", "cpu", ":", "raise", "exceptions", ".", "ArgumentError", "(", "\"Must specify [--cpu] when using [--private]\"", ")", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", "identifier", ",", "'VS'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "confirm", "(", "\"This action will incur charges on your account. Continue?\"", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted'", ")", "if", "memory", ":", "memory", "=", "int", "(", "memory", "/", "1024", ")", "if", "not", "vsi", ".", "upgrade", "(", "vs_id", ",", "cpus", "=", "cpu", ",", "memory", "=", "memory", ",", "nic_speed", "=", "network", ",", "public", "=", "not", "private", ",", "preset", "=", "flavor", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'VS Upgrade Failed'", ")" ]
Upgrade a virtual server.
[ "Upgrade", "a", "virtual", "server", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/upgrade.py#L26-L45
1,380
softlayer/softlayer-python
SoftLayer/CLI/hardware/power.py
reboot
def reboot(env, identifier, hard): """Reboot an active server.""" hardware_server = env.client['Hardware_Server'] mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s. ' 'Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') if hard is True: hardware_server.rebootHard(id=hw_id) elif hard is False: hardware_server.rebootSoft(id=hw_id) else: hardware_server.rebootDefault(id=hw_id)
python
def reboot(env, identifier, hard): """Reboot an active server.""" hardware_server = env.client['Hardware_Server'] mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s. ' 'Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') if hard is True: hardware_server.rebootHard(id=hw_id) elif hard is False: hardware_server.rebootSoft(id=hw_id) else: hardware_server.rebootDefault(id=hw_id)
[ "def", "reboot", "(", "env", ",", "identifier", ",", "hard", ")", ":", "hardware_server", "=", "env", ".", "client", "[", "'Hardware_Server'", "]", "mgr", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "hw_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'hardware'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "confirm", "(", "'This will power off the server with id %s. '", "'Continue?'", "%", "hw_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted.'", ")", "if", "hard", "is", "True", ":", "hardware_server", ".", "rebootHard", "(", "id", "=", "hw_id", ")", "elif", "hard", "is", "False", ":", "hardware_server", ".", "rebootSoft", "(", "id", "=", "hw_id", ")", "else", ":", "hardware_server", ".", "rebootDefault", "(", "id", "=", "hw_id", ")" ]
Reboot an active server.
[ "Reboot", "an", "active", "server", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/power.py#L35-L51
1,381
softlayer/softlayer-python
SoftLayer/CLI/hardware/power.py
power_on
def power_on(env, identifier): """Power on a server.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') env.client['Hardware_Server'].powerOn(id=hw_id)
python
def power_on(env, identifier): """Power on a server.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') env.client['Hardware_Server'].powerOn(id=hw_id)
[ "def", "power_on", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "hw_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'hardware'", ")", "env", ".", "client", "[", "'Hardware_Server'", "]", ".", "powerOn", "(", "id", "=", "hw_id", ")" ]
Power on a server.
[ "Power", "on", "a", "server", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/power.py#L57-L62
1,382
softlayer/softlayer-python
SoftLayer/CLI/hardware/power.py
power_cycle
def power_cycle(env, identifier): """Power cycle a server.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s. ' 'Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') env.client['Hardware_Server'].powerCycle(id=hw_id)
python
def power_cycle(env, identifier): """Power cycle a server.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s. ' 'Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') env.client['Hardware_Server'].powerCycle(id=hw_id)
[ "def", "power_cycle", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "hw_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'hardware'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "confirm", "(", "'This will power off the server with id %s. '", "'Continue?'", "%", "hw_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted.'", ")", "env", ".", "client", "[", "'Hardware_Server'", "]", ".", "powerCycle", "(", "id", "=", "hw_id", ")" ]
Power cycle a server.
[ "Power", "cycle", "a", "server", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/power.py#L68-L79
1,383
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/edit.py
cli
def cli(env, group_id, name, description): """Edit details of a security group.""" mgr = SoftLayer.NetworkManager(env.client) data = {} if name: data['name'] = name if description: data['description'] = description if not mgr.edit_securitygroup(group_id, **data): raise exceptions.CLIAbort("Failed to edit security group")
python
def cli(env, group_id, name, description): """Edit details of a security group.""" mgr = SoftLayer.NetworkManager(env.client) data = {} if name: data['name'] = name if description: data['description'] = description if not mgr.edit_securitygroup(group_id, **data): raise exceptions.CLIAbort("Failed to edit security group")
[ "def", "cli", "(", "env", ",", "group_id", ",", "name", ",", "description", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "data", "=", "{", "}", "if", "name", ":", "data", "[", "'name'", "]", "=", "name", "if", "description", ":", "data", "[", "'description'", "]", "=", "description", "if", "not", "mgr", ".", "edit_securitygroup", "(", "group_id", ",", "*", "*", "data", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Failed to edit security group\"", ")" ]
Edit details of a security group.
[ "Edit", "details", "of", "a", "security", "group", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/edit.py#L18-L28
1,384
softlayer/softlayer-python
SoftLayer/CLI/event_log/get.py
cli
def cli(env, date_min, date_max, obj_event, obj_id, obj_type, utc_offset, metadata, limit): """Get Event Logs Example: slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10 """ columns = ['Event', 'Object', 'Type', 'Date', 'Username'] event_mgr = SoftLayer.EventLogManager(env.client) user_mgr = SoftLayer.UserManager(env.client) request_filter = event_mgr.build_filter(date_min, date_max, obj_event, obj_id, obj_type, utc_offset) logs = event_mgr.get_event_logs(request_filter) log_time = "%Y-%m-%dT%H:%M:%S.%f%z" user_data = {} if metadata: columns.append('Metadata') row_count = 0 click.secho(", ".join(columns)) for log in logs: if log is None: click.secho('No logs available for filter %s.' % request_filter, fg='red') return user = log['userType'] label = log.get('label', '') if user == "CUSTOMER": username = user_data.get(log['userId']) if username is None: username = user_mgr.get_user(log['userId'], "mask[username]")['username'] user_data[log['userId']] = username user = username if metadata: metadata_data = log['metaData'].strip("\n\t") click.secho("'{0}','{1}','{2}','{3}','{4}','{5}'".format( log['eventName'], label, log['objectName'], utils.clean_time(log['eventCreateDate'], in_format=log_time), user, metadata_data)) else: click.secho("'{0}','{1}','{2}','{3}','{4}'".format( log['eventName'], label, log['objectName'], utils.clean_time(log['eventCreateDate'], in_format=log_time), user)) row_count = row_count + 1 if row_count >= limit and limit != -1: return
python
def cli(env, date_min, date_max, obj_event, obj_id, obj_type, utc_offset, metadata, limit): """Get Event Logs Example: slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10 """ columns = ['Event', 'Object', 'Type', 'Date', 'Username'] event_mgr = SoftLayer.EventLogManager(env.client) user_mgr = SoftLayer.UserManager(env.client) request_filter = event_mgr.build_filter(date_min, date_max, obj_event, obj_id, obj_type, utc_offset) logs = event_mgr.get_event_logs(request_filter) log_time = "%Y-%m-%dT%H:%M:%S.%f%z" user_data = {} if metadata: columns.append('Metadata') row_count = 0 click.secho(", ".join(columns)) for log in logs: if log is None: click.secho('No logs available for filter %s.' % request_filter, fg='red') return user = log['userType'] label = log.get('label', '') if user == "CUSTOMER": username = user_data.get(log['userId']) if username is None: username = user_mgr.get_user(log['userId'], "mask[username]")['username'] user_data[log['userId']] = username user = username if metadata: metadata_data = log['metaData'].strip("\n\t") click.secho("'{0}','{1}','{2}','{3}','{4}','{5}'".format( log['eventName'], label, log['objectName'], utils.clean_time(log['eventCreateDate'], in_format=log_time), user, metadata_data)) else: click.secho("'{0}','{1}','{2}','{3}','{4}'".format( log['eventName'], label, log['objectName'], utils.clean_time(log['eventCreateDate'], in_format=log_time), user)) row_count = row_count + 1 if row_count >= limit and limit != -1: return
[ "def", "cli", "(", "env", ",", "date_min", ",", "date_max", ",", "obj_event", ",", "obj_id", ",", "obj_type", ",", "utc_offset", ",", "metadata", ",", "limit", ")", ":", "columns", "=", "[", "'Event'", ",", "'Object'", ",", "'Type'", ",", "'Date'", ",", "'Username'", "]", "event_mgr", "=", "SoftLayer", ".", "EventLogManager", "(", "env", ".", "client", ")", "user_mgr", "=", "SoftLayer", ".", "UserManager", "(", "env", ".", "client", ")", "request_filter", "=", "event_mgr", ".", "build_filter", "(", "date_min", ",", "date_max", ",", "obj_event", ",", "obj_id", ",", "obj_type", ",", "utc_offset", ")", "logs", "=", "event_mgr", ".", "get_event_logs", "(", "request_filter", ")", "log_time", "=", "\"%Y-%m-%dT%H:%M:%S.%f%z\"", "user_data", "=", "{", "}", "if", "metadata", ":", "columns", ".", "append", "(", "'Metadata'", ")", "row_count", "=", "0", "click", ".", "secho", "(", "\", \"", ".", "join", "(", "columns", ")", ")", "for", "log", "in", "logs", ":", "if", "log", "is", "None", ":", "click", ".", "secho", "(", "'No logs available for filter %s.'", "%", "request_filter", ",", "fg", "=", "'red'", ")", "return", "user", "=", "log", "[", "'userType'", "]", "label", "=", "log", ".", "get", "(", "'label'", ",", "''", ")", "if", "user", "==", "\"CUSTOMER\"", ":", "username", "=", "user_data", ".", "get", "(", "log", "[", "'userId'", "]", ")", "if", "username", "is", "None", ":", "username", "=", "user_mgr", ".", "get_user", "(", "log", "[", "'userId'", "]", ",", "\"mask[username]\"", ")", "[", "'username'", "]", "user_data", "[", "log", "[", "'userId'", "]", "]", "=", "username", "user", "=", "username", "if", "metadata", ":", "metadata_data", "=", "log", "[", "'metaData'", "]", ".", "strip", "(", "\"\\n\\t\"", ")", "click", ".", "secho", "(", "\"'{0}','{1}','{2}','{3}','{4}','{5}'\"", ".", "format", "(", "log", "[", "'eventName'", "]", ",", "label", ",", "log", "[", "'objectName'", "]", ",", "utils", ".", "clean_time", "(", "log", "[", "'eventCreateDate'", "]", ",", "in_format", "=", "log_time", ")", ",", "user", ",", "metadata_data", ")", ")", "else", ":", "click", ".", "secho", "(", "\"'{0}','{1}','{2}','{3}','{4}'\"", ".", "format", "(", "log", "[", "'eventName'", "]", ",", "label", ",", "log", "[", "'objectName'", "]", ",", "utils", ".", "clean_time", "(", "log", "[", "'eventCreateDate'", "]", ",", "in_format", "=", "log_time", ")", ",", "user", ")", ")", "row_count", "=", "row_count", "+", "1", "if", "row_count", ">=", "limit", "and", "limit", "!=", "-", "1", ":", "return" ]
Get Event Logs Example: slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10
[ "Get", "Event", "Logs" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/event_log/get.py#L29-L83
1,385
softlayer/softlayer-python
SoftLayer/CLI/file/modify.py
cli
def cli(env, volume_id, new_size, new_iops, new_tier): """Modify an existing file storage volume.""" file_manager = SoftLayer.FileStorageManager(env.client) if new_tier is not None: new_tier = float(new_tier) try: order = file_manager.order_modified_volume( volume_id, new_size=new_size, new_iops=new_iops, new_tier_level=new_tier, ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order #{0} placed successfully!".format(order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) else: click.echo("Order could not be placed! Please verify your options and try again.")
python
def cli(env, volume_id, new_size, new_iops, new_tier): """Modify an existing file storage volume.""" file_manager = SoftLayer.FileStorageManager(env.client) if new_tier is not None: new_tier = float(new_tier) try: order = file_manager.order_modified_volume( volume_id, new_size=new_size, new_iops=new_iops, new_tier_level=new_tier, ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order #{0} placed successfully!".format(order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) else: click.echo("Order could not be placed! Please verify your options and try again.")
[ "def", "cli", "(", "env", ",", "volume_id", ",", "new_size", ",", "new_iops", ",", "new_tier", ")", ":", "file_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "if", "new_tier", "is", "not", "None", ":", "new_tier", "=", "float", "(", "new_tier", ")", "try", ":", "order", "=", "file_manager", ".", "order_modified_volume", "(", "volume_id", ",", "new_size", "=", "new_size", ",", "new_iops", "=", "new_iops", ",", "new_tier_level", "=", "new_tier", ",", ")", "except", "ValueError", "as", "ex", ":", "raise", "exceptions", ".", "ArgumentError", "(", "str", "(", "ex", ")", ")", "if", "'placedOrder'", "in", "order", ".", "keys", "(", ")", ":", "click", ".", "echo", "(", "\"Order #{0} placed successfully!\"", ".", "format", "(", "order", "[", "'placedOrder'", "]", "[", "'id'", "]", ")", ")", "for", "item", "in", "order", "[", "'placedOrder'", "]", "[", "'items'", "]", ":", "click", ".", "echo", "(", "\" > %s\"", "%", "item", "[", "'description'", "]", ")", "else", ":", "click", ".", "echo", "(", "\"Order could not be placed! Please verify your options and try again.\"", ")" ]
Modify an existing file storage volume.
[ "Modify", "an", "existing", "file", "storage", "volume", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/modify.py#L35-L57
1,386
softlayer/softlayer-python
SoftLayer/managers/user.py
UserManager.add_permissions
def add_permissions(self, user_id, permissions): """Enables a list of permissions for a user :param int id: user id to set :param list permissions: List of permissions keynames to enable :returns: True on success, Exception otherwise Example:: add_permissions(123, ['BANDWIDTH_MANAGE']) """ pretty_permissions = self.format_permission_object(permissions) LOGGER.warning("Adding the following permissions to %s: %s", user_id, pretty_permissions) return self.user_service.addBulkPortalPermission(pretty_permissions, id=user_id)
python
def add_permissions(self, user_id, permissions): """Enables a list of permissions for a user :param int id: user id to set :param list permissions: List of permissions keynames to enable :returns: True on success, Exception otherwise Example:: add_permissions(123, ['BANDWIDTH_MANAGE']) """ pretty_permissions = self.format_permission_object(permissions) LOGGER.warning("Adding the following permissions to %s: %s", user_id, pretty_permissions) return self.user_service.addBulkPortalPermission(pretty_permissions, id=user_id)
[ "def", "add_permissions", "(", "self", ",", "user_id", ",", "permissions", ")", ":", "pretty_permissions", "=", "self", ".", "format_permission_object", "(", "permissions", ")", "LOGGER", ".", "warning", "(", "\"Adding the following permissions to %s: %s\"", ",", "user_id", ",", "pretty_permissions", ")", "return", "self", ".", "user_service", ".", "addBulkPortalPermission", "(", "pretty_permissions", ",", "id", "=", "user_id", ")" ]
Enables a list of permissions for a user :param int id: user id to set :param list permissions: List of permissions keynames to enable :returns: True on success, Exception otherwise Example:: add_permissions(123, ['BANDWIDTH_MANAGE'])
[ "Enables", "a", "list", "of", "permissions", "for", "a", "user" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L87-L99
1,387
softlayer/softlayer-python
SoftLayer/managers/user.py
UserManager.remove_permissions
def remove_permissions(self, user_id, permissions): """Disables a list of permissions for a user :param int id: user id to set :param list permissions: List of permissions keynames to disable :returns: True on success, Exception otherwise Example:: remove_permissions(123, ['BANDWIDTH_MANAGE']) """ pretty_permissions = self.format_permission_object(permissions) LOGGER.warning("Removing the following permissions to %s: %s", user_id, pretty_permissions) return self.user_service.removeBulkPortalPermission(pretty_permissions, id=user_id)
python
def remove_permissions(self, user_id, permissions): """Disables a list of permissions for a user :param int id: user id to set :param list permissions: List of permissions keynames to disable :returns: True on success, Exception otherwise Example:: remove_permissions(123, ['BANDWIDTH_MANAGE']) """ pretty_permissions = self.format_permission_object(permissions) LOGGER.warning("Removing the following permissions to %s: %s", user_id, pretty_permissions) return self.user_service.removeBulkPortalPermission(pretty_permissions, id=user_id)
[ "def", "remove_permissions", "(", "self", ",", "user_id", ",", "permissions", ")", ":", "pretty_permissions", "=", "self", ".", "format_permission_object", "(", "permissions", ")", "LOGGER", ".", "warning", "(", "\"Removing the following permissions to %s: %s\"", ",", "user_id", ",", "pretty_permissions", ")", "return", "self", ".", "user_service", ".", "removeBulkPortalPermission", "(", "pretty_permissions", ",", "id", "=", "user_id", ")" ]
Disables a list of permissions for a user :param int id: user id to set :param list permissions: List of permissions keynames to disable :returns: True on success, Exception otherwise Example:: remove_permissions(123, ['BANDWIDTH_MANAGE'])
[ "Disables", "a", "list", "of", "permissions", "for", "a", "user" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L101-L113
1,388
softlayer/softlayer-python
SoftLayer/managers/user.py
UserManager.permissions_from_user
def permissions_from_user(self, user_id, from_user_id): """Sets user_id's permission to be the same as from_user_id's Any permissions from_user_id has will be added to user_id. Any permissions from_user_id doesn't have will be removed from user_id. :param int user_id: The user to change permissions. :param int from_user_id: The use to base permissions from. :returns: True on success, Exception otherwise. """ from_permissions = self.get_user_permissions(from_user_id) self.add_permissions(user_id, from_permissions) all_permissions = self.get_all_permissions() remove_permissions = [] for permission in all_permissions: # If permission does not exist for from_user_id add it to the list to be removed if _keyname_search(from_permissions, permission['keyName']): continue else: remove_permissions.append({'keyName': permission['keyName']}) self.remove_permissions(user_id, remove_permissions) return True
python
def permissions_from_user(self, user_id, from_user_id): """Sets user_id's permission to be the same as from_user_id's Any permissions from_user_id has will be added to user_id. Any permissions from_user_id doesn't have will be removed from user_id. :param int user_id: The user to change permissions. :param int from_user_id: The use to base permissions from. :returns: True on success, Exception otherwise. """ from_permissions = self.get_user_permissions(from_user_id) self.add_permissions(user_id, from_permissions) all_permissions = self.get_all_permissions() remove_permissions = [] for permission in all_permissions: # If permission does not exist for from_user_id add it to the list to be removed if _keyname_search(from_permissions, permission['keyName']): continue else: remove_permissions.append({'keyName': permission['keyName']}) self.remove_permissions(user_id, remove_permissions) return True
[ "def", "permissions_from_user", "(", "self", ",", "user_id", ",", "from_user_id", ")", ":", "from_permissions", "=", "self", ".", "get_user_permissions", "(", "from_user_id", ")", "self", ".", "add_permissions", "(", "user_id", ",", "from_permissions", ")", "all_permissions", "=", "self", ".", "get_all_permissions", "(", ")", "remove_permissions", "=", "[", "]", "for", "permission", "in", "all_permissions", ":", "# If permission does not exist for from_user_id add it to the list to be removed", "if", "_keyname_search", "(", "from_permissions", ",", "permission", "[", "'keyName'", "]", ")", ":", "continue", "else", ":", "remove_permissions", ".", "append", "(", "{", "'keyName'", ":", "permission", "[", "'keyName'", "]", "}", ")", "self", ".", "remove_permissions", "(", "user_id", ",", "remove_permissions", ")", "return", "True" ]
Sets user_id's permission to be the same as from_user_id's Any permissions from_user_id has will be added to user_id. Any permissions from_user_id doesn't have will be removed from user_id. :param int user_id: The user to change permissions. :param int from_user_id: The use to base permissions from. :returns: True on success, Exception otherwise.
[ "Sets", "user_id", "s", "permission", "to", "be", "the", "same", "as", "from_user_id", "s" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L115-L139
1,389
softlayer/softlayer-python
SoftLayer/managers/user.py
UserManager.get_user_permissions
def get_user_permissions(self, user_id): """Returns a sorted list of a users permissions""" permissions = self.user_service.getPermissions(id=user_id) return sorted(permissions, key=itemgetter('keyName'))
python
def get_user_permissions(self, user_id): """Returns a sorted list of a users permissions""" permissions = self.user_service.getPermissions(id=user_id) return sorted(permissions, key=itemgetter('keyName'))
[ "def", "get_user_permissions", "(", "self", ",", "user_id", ")", ":", "permissions", "=", "self", ".", "user_service", ".", "getPermissions", "(", "id", "=", "user_id", ")", "return", "sorted", "(", "permissions", ",", "key", "=", "itemgetter", "(", "'keyName'", ")", ")" ]
Returns a sorted list of a users permissions
[ "Returns", "a", "sorted", "list", "of", "a", "users", "permissions" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L141-L144
1,390
softlayer/softlayer-python
SoftLayer/managers/user.py
UserManager.get_logins
def get_logins(self, user_id, start_date=None): """Gets the login history for a user, default start_date is 30 days ago :param int id: User id to get :param string start_date: "%m/%d/%Y %H:%M:%s" formatted string. :returns: list https://softlayer.github.io/reference/datatypes/SoftLayer_User_Customer_Access_Authentication/ Example:: get_logins(123, '04/08/2018 0:0:0') """ if start_date is None: date_object = datetime.datetime.today() - datetime.timedelta(days=30) start_date = date_object.strftime("%m/%d/%Y 0:0:0") date_filter = { 'loginAttempts': { 'createDate': { 'operation': 'greaterThanDate', 'options': [{'name': 'date', 'value': [start_date]}] } } } login_log = self.user_service.getLoginAttempts(id=user_id, filter=date_filter) return login_log
python
def get_logins(self, user_id, start_date=None): """Gets the login history for a user, default start_date is 30 days ago :param int id: User id to get :param string start_date: "%m/%d/%Y %H:%M:%s" formatted string. :returns: list https://softlayer.github.io/reference/datatypes/SoftLayer_User_Customer_Access_Authentication/ Example:: get_logins(123, '04/08/2018 0:0:0') """ if start_date is None: date_object = datetime.datetime.today() - datetime.timedelta(days=30) start_date = date_object.strftime("%m/%d/%Y 0:0:0") date_filter = { 'loginAttempts': { 'createDate': { 'operation': 'greaterThanDate', 'options': [{'name': 'date', 'value': [start_date]}] } } } login_log = self.user_service.getLoginAttempts(id=user_id, filter=date_filter) return login_log
[ "def", "get_logins", "(", "self", ",", "user_id", ",", "start_date", "=", "None", ")", ":", "if", "start_date", "is", "None", ":", "date_object", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "30", ")", "start_date", "=", "date_object", ".", "strftime", "(", "\"%m/%d/%Y 0:0:0\"", ")", "date_filter", "=", "{", "'loginAttempts'", ":", "{", "'createDate'", ":", "{", "'operation'", ":", "'greaterThanDate'", ",", "'options'", ":", "[", "{", "'name'", ":", "'date'", ",", "'value'", ":", "[", "start_date", "]", "}", "]", "}", "}", "}", "login_log", "=", "self", ".", "user_service", ".", "getLoginAttempts", "(", "id", "=", "user_id", ",", "filter", "=", "date_filter", ")", "return", "login_log" ]
Gets the login history for a user, default start_date is 30 days ago :param int id: User id to get :param string start_date: "%m/%d/%Y %H:%M:%s" formatted string. :returns: list https://softlayer.github.io/reference/datatypes/SoftLayer_User_Customer_Access_Authentication/ Example:: get_logins(123, '04/08/2018 0:0:0')
[ "Gets", "the", "login", "history", "for", "a", "user", "default", "start_date", "is", "30", "days", "ago" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L146-L169
1,391
softlayer/softlayer-python
SoftLayer/managers/user.py
UserManager.get_events
def get_events(self, user_id, start_date=None): """Gets the event log for a specific user, default start_date is 30 days ago :param int id: User id to view :param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string. The Timezone part has to be HH:MM, notice the : there. :returns: https://softlayer.github.io/reference/datatypes/SoftLayer_Event_Log/ """ if start_date is None: date_object = datetime.datetime.today() - datetime.timedelta(days=30) start_date = date_object.strftime("%Y-%m-%dT00:00:00") object_filter = { 'userId': { 'operation': user_id }, 'eventCreateDate': { 'operation': 'greaterThanDate', 'options': [{'name': 'date', 'value': [start_date]}] } } events = self.client.call('Event_Log', 'getAllObjects', filter=object_filter) if events is None: events = [{'eventName': 'No Events Found'}] return events
python
def get_events(self, user_id, start_date=None): """Gets the event log for a specific user, default start_date is 30 days ago :param int id: User id to view :param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string. The Timezone part has to be HH:MM, notice the : there. :returns: https://softlayer.github.io/reference/datatypes/SoftLayer_Event_Log/ """ if start_date is None: date_object = datetime.datetime.today() - datetime.timedelta(days=30) start_date = date_object.strftime("%Y-%m-%dT00:00:00") object_filter = { 'userId': { 'operation': user_id }, 'eventCreateDate': { 'operation': 'greaterThanDate', 'options': [{'name': 'date', 'value': [start_date]}] } } events = self.client.call('Event_Log', 'getAllObjects', filter=object_filter) if events is None: events = [{'eventName': 'No Events Found'}] return events
[ "def", "get_events", "(", "self", ",", "user_id", ",", "start_date", "=", "None", ")", ":", "if", "start_date", "is", "None", ":", "date_object", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "30", ")", "start_date", "=", "date_object", ".", "strftime", "(", "\"%Y-%m-%dT00:00:00\"", ")", "object_filter", "=", "{", "'userId'", ":", "{", "'operation'", ":", "user_id", "}", ",", "'eventCreateDate'", ":", "{", "'operation'", ":", "'greaterThanDate'", ",", "'options'", ":", "[", "{", "'name'", ":", "'date'", ",", "'value'", ":", "[", "start_date", "]", "}", "]", "}", "}", "events", "=", "self", ".", "client", ".", "call", "(", "'Event_Log'", ",", "'getAllObjects'", ",", "filter", "=", "object_filter", ")", "if", "events", "is", "None", ":", "events", "=", "[", "{", "'eventName'", ":", "'No Events Found'", "}", "]", "return", "events" ]
Gets the event log for a specific user, default start_date is 30 days ago :param int id: User id to view :param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string. The Timezone part has to be HH:MM, notice the : there. :returns: https://softlayer.github.io/reference/datatypes/SoftLayer_Event_Log/
[ "Gets", "the", "event", "log", "for", "a", "specific", "user", "default", "start_date", "is", "30", "days", "ago" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L171-L197
1,392
softlayer/softlayer-python
SoftLayer/managers/user.py
UserManager._get_id_from_username
def _get_id_from_username(self, username): """Looks up a username's id :param string username: Username to lookup :returns: The id that matches username. """ _mask = "mask[id, username]" _filter = {'users': {'username': utils.query_filter(username)}} user = self.list_users(_mask, _filter) if len(user) == 1: return [user[0]['id']] elif len(user) > 1: raise exceptions.SoftLayerError("Multiple users found with the name: %s" % username) else: raise exceptions.SoftLayerError("Unable to find user id for %s" % username)
python
def _get_id_from_username(self, username): """Looks up a username's id :param string username: Username to lookup :returns: The id that matches username. """ _mask = "mask[id, username]" _filter = {'users': {'username': utils.query_filter(username)}} user = self.list_users(_mask, _filter) if len(user) == 1: return [user[0]['id']] elif len(user) > 1: raise exceptions.SoftLayerError("Multiple users found with the name: %s" % username) else: raise exceptions.SoftLayerError("Unable to find user id for %s" % username)
[ "def", "_get_id_from_username", "(", "self", ",", "username", ")", ":", "_mask", "=", "\"mask[id, username]\"", "_filter", "=", "{", "'users'", ":", "{", "'username'", ":", "utils", ".", "query_filter", "(", "username", ")", "}", "}", "user", "=", "self", ".", "list_users", "(", "_mask", ",", "_filter", ")", "if", "len", "(", "user", ")", "==", "1", ":", "return", "[", "user", "[", "0", "]", "[", "'id'", "]", "]", "elif", "len", "(", "user", ")", ">", "1", ":", "raise", "exceptions", ".", "SoftLayerError", "(", "\"Multiple users found with the name: %s\"", "%", "username", ")", "else", ":", "raise", "exceptions", ".", "SoftLayerError", "(", "\"Unable to find user id for %s\"", "%", "username", ")" ]
Looks up a username's id :param string username: Username to lookup :returns: The id that matches username.
[ "Looks", "up", "a", "username", "s", "id" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L199-L213
1,393
softlayer/softlayer-python
SoftLayer/managers/user.py
UserManager.format_permission_object
def format_permission_object(self, permissions): """Formats a list of permission key names into something the SLAPI will respect. :param list permissions: A list of SLAPI permissions keyNames. keyName of ALL will return all permissions. :returns: list of dictionaries that can be sent to the api to add or remove permissions :throws SoftLayerError: If any permission is invalid this exception will be thrown. """ pretty_permissions = [] available_permissions = self.get_all_permissions() # pp(available_permissions) for permission in permissions: # Handle data retrieved directly from the API if isinstance(permission, dict): permission = permission['keyName'] permission = permission.upper() if permission == 'ALL': return available_permissions # Search through available_permissions to make sure what the user entered was valid if _keyname_search(available_permissions, permission): pretty_permissions.append({'keyName': permission}) else: raise exceptions.SoftLayerError("'%s' is not a valid permission" % permission) return pretty_permissions
python
def format_permission_object(self, permissions): """Formats a list of permission key names into something the SLAPI will respect. :param list permissions: A list of SLAPI permissions keyNames. keyName of ALL will return all permissions. :returns: list of dictionaries that can be sent to the api to add or remove permissions :throws SoftLayerError: If any permission is invalid this exception will be thrown. """ pretty_permissions = [] available_permissions = self.get_all_permissions() # pp(available_permissions) for permission in permissions: # Handle data retrieved directly from the API if isinstance(permission, dict): permission = permission['keyName'] permission = permission.upper() if permission == 'ALL': return available_permissions # Search through available_permissions to make sure what the user entered was valid if _keyname_search(available_permissions, permission): pretty_permissions.append({'keyName': permission}) else: raise exceptions.SoftLayerError("'%s' is not a valid permission" % permission) return pretty_permissions
[ "def", "format_permission_object", "(", "self", ",", "permissions", ")", ":", "pretty_permissions", "=", "[", "]", "available_permissions", "=", "self", ".", "get_all_permissions", "(", ")", "# pp(available_permissions)", "for", "permission", "in", "permissions", ":", "# Handle data retrieved directly from the API", "if", "isinstance", "(", "permission", ",", "dict", ")", ":", "permission", "=", "permission", "[", "'keyName'", "]", "permission", "=", "permission", ".", "upper", "(", ")", "if", "permission", "==", "'ALL'", ":", "return", "available_permissions", "# Search through available_permissions to make sure what the user entered was valid", "if", "_keyname_search", "(", "available_permissions", ",", "permission", ")", ":", "pretty_permissions", ".", "append", "(", "{", "'keyName'", ":", "permission", "}", ")", "else", ":", "raise", "exceptions", ".", "SoftLayerError", "(", "\"'%s' is not a valid permission\"", "%", "permission", ")", "return", "pretty_permissions" ]
Formats a list of permission key names into something the SLAPI will respect. :param list permissions: A list of SLAPI permissions keyNames. keyName of ALL will return all permissions. :returns: list of dictionaries that can be sent to the api to add or remove permissions :throws SoftLayerError: If any permission is invalid this exception will be thrown.
[ "Formats", "a", "list", "of", "permission", "key", "names", "into", "something", "the", "SLAPI", "will", "respect", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/user.py#L215-L238
1,394
softlayer/softlayer-python
SoftLayer/CLI/globalip/unassign.py
cli
def cli(env, identifier): """Unassigns a global IP from a target.""" mgr = SoftLayer.NetworkManager(env.client) global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier, name='global ip') mgr.unassign_global_ip(global_ip_id)
python
def cli(env, identifier): """Unassigns a global IP from a target.""" mgr = SoftLayer.NetworkManager(env.client) global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier, name='global ip') mgr.unassign_global_ip(global_ip_id)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "global_ip_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_global_ip_ids", ",", "identifier", ",", "name", "=", "'global ip'", ")", "mgr", ".", "unassign_global_ip", "(", "global_ip_id", ")" ]
Unassigns a global IP from a target.
[ "Unassigns", "a", "global", "IP", "from", "a", "target", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/globalip/unassign.py#L14-L20
1,395
softlayer/softlayer-python
SoftLayer/CLI/vpn/ipsec/configure.py
cli
def cli(env, context_id): """Request configuration of a tunnel context. This action will update the advancedConfigurationFlag on the context instance and further modifications against the context will be prevented until all changes can be propgated to network devices. """ manager = SoftLayer.IPSECManager(env.client) # ensure context can be retrieved by given id manager.get_tunnel_context(context_id) succeeded = manager.apply_configuration(context_id) if succeeded: env.out('Configuration request received for context #{}' .format(context_id)) else: raise CLIHalt('Failed to enqueue configuration request for context #{}' .format(context_id))
python
def cli(env, context_id): """Request configuration of a tunnel context. This action will update the advancedConfigurationFlag on the context instance and further modifications against the context will be prevented until all changes can be propgated to network devices. """ manager = SoftLayer.IPSECManager(env.client) # ensure context can be retrieved by given id manager.get_tunnel_context(context_id) succeeded = manager.apply_configuration(context_id) if succeeded: env.out('Configuration request received for context #{}' .format(context_id)) else: raise CLIHalt('Failed to enqueue configuration request for context #{}' .format(context_id))
[ "def", "cli", "(", "env", ",", "context_id", ")", ":", "manager", "=", "SoftLayer", ".", "IPSECManager", "(", "env", ".", "client", ")", "# ensure context can be retrieved by given id", "manager", ".", "get_tunnel_context", "(", "context_id", ")", "succeeded", "=", "manager", ".", "apply_configuration", "(", "context_id", ")", "if", "succeeded", ":", "env", ".", "out", "(", "'Configuration request received for context #{}'", ".", "format", "(", "context_id", ")", ")", "else", ":", "raise", "CLIHalt", "(", "'Failed to enqueue configuration request for context #{}'", ".", "format", "(", "context_id", ")", ")" ]
Request configuration of a tunnel context. This action will update the advancedConfigurationFlag on the context instance and further modifications against the context will be prevented until all changes can be propgated to network devices.
[ "Request", "configuration", "of", "a", "tunnel", "context", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/configure.py#L14-L31
1,396
softlayer/softlayer-python
SoftLayer/managers/dns.py
DNSManager._get_zone_id_from_name
def _get_zone_id_from_name(self, name): """Return zone ID based on a zone.""" results = self.client['Account'].getDomains( filter={"domains": {"name": utils.query_filter(name)}}) return [x['id'] for x in results]
python
def _get_zone_id_from_name(self, name): """Return zone ID based on a zone.""" results = self.client['Account'].getDomains( filter={"domains": {"name": utils.query_filter(name)}}) return [x['id'] for x in results]
[ "def", "_get_zone_id_from_name", "(", "self", ",", "name", ")", ":", "results", "=", "self", ".", "client", "[", "'Account'", "]", ".", "getDomains", "(", "filter", "=", "{", "\"domains\"", ":", "{", "\"name\"", ":", "utils", ".", "query_filter", "(", "name", ")", "}", "}", ")", "return", "[", "x", "[", "'id'", "]", "for", "x", "in", "results", "]" ]
Return zone ID based on a zone.
[ "Return", "zone", "ID", "based", "on", "a", "zone", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L28-L32
1,397
softlayer/softlayer-python
SoftLayer/managers/dns.py
DNSManager.get_zone
def get_zone(self, zone_id, records=True): """Get a zone and its records. :param zone: the zone name :returns: A dictionary containing a large amount of information about the specified zone. """ mask = None if records: mask = 'resourceRecords' return self.service.getObject(id=zone_id, mask=mask)
python
def get_zone(self, zone_id, records=True): """Get a zone and its records. :param zone: the zone name :returns: A dictionary containing a large amount of information about the specified zone. """ mask = None if records: mask = 'resourceRecords' return self.service.getObject(id=zone_id, mask=mask)
[ "def", "get_zone", "(", "self", ",", "zone_id", ",", "records", "=", "True", ")", ":", "mask", "=", "None", "if", "records", ":", "mask", "=", "'resourceRecords'", "return", "self", ".", "service", ".", "getObject", "(", "id", "=", "zone_id", ",", "mask", "=", "mask", ")" ]
Get a zone and its records. :param zone: the zone name :returns: A dictionary containing a large amount of information about the specified zone.
[ "Get", "a", "zone", "and", "its", "records", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L43-L54
1,398
softlayer/softlayer-python
SoftLayer/managers/dns.py
DNSManager.create_zone
def create_zone(self, zone, serial=None): """Create a zone for the specified zone. :param zone: the zone name to create :param serial: serial value on the zone (default: strftime(%Y%m%d01)) """ return self.service.createObject({ 'name': zone, 'serial': serial or time.strftime('%Y%m%d01'), "resourceRecords": {}})
python
def create_zone(self, zone, serial=None): """Create a zone for the specified zone. :param zone: the zone name to create :param serial: serial value on the zone (default: strftime(%Y%m%d01)) """ return self.service.createObject({ 'name': zone, 'serial': serial or time.strftime('%Y%m%d01'), "resourceRecords": {}})
[ "def", "create_zone", "(", "self", ",", "zone", ",", "serial", "=", "None", ")", ":", "return", "self", ".", "service", ".", "createObject", "(", "{", "'name'", ":", "zone", ",", "'serial'", ":", "serial", "or", "time", ".", "strftime", "(", "'%Y%m%d01'", ")", ",", "\"resourceRecords\"", ":", "{", "}", "}", ")" ]
Create a zone for the specified zone. :param zone: the zone name to create :param serial: serial value on the zone (default: strftime(%Y%m%d01))
[ "Create", "a", "zone", "for", "the", "specified", "zone", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L56-L66
1,399
softlayer/softlayer-python
SoftLayer/managers/dns.py
DNSManager.create_record_mx
def create_record_mx(self, zone_id, record, data, ttl=60, priority=10): """Create a mx resource record on a domain. :param integer id: the zone's ID :param record: the name of the record to add :param data: the record's value :param integer ttl: the TTL or time-to-live value (default: 60) :param integer priority: the priority of the target host """ resource_record = self._generate_create_dict(record, 'MX', data, ttl, domainId=zone_id, mxPriority=priority) return self.record.createObject(resource_record)
python
def create_record_mx(self, zone_id, record, data, ttl=60, priority=10): """Create a mx resource record on a domain. :param integer id: the zone's ID :param record: the name of the record to add :param data: the record's value :param integer ttl: the TTL or time-to-live value (default: 60) :param integer priority: the priority of the target host """ resource_record = self._generate_create_dict(record, 'MX', data, ttl, domainId=zone_id, mxPriority=priority) return self.record.createObject(resource_record)
[ "def", "create_record_mx", "(", "self", ",", "zone_id", ",", "record", ",", "data", ",", "ttl", "=", "60", ",", "priority", "=", "10", ")", ":", "resource_record", "=", "self", ".", "_generate_create_dict", "(", "record", ",", "'MX'", ",", "data", ",", "ttl", ",", "domainId", "=", "zone_id", ",", "mxPriority", "=", "priority", ")", "return", "self", ".", "record", ".", "createObject", "(", "resource_record", ")" ]
Create a mx resource record on a domain. :param integer id: the zone's ID :param record: the name of the record to add :param data: the record's value :param integer ttl: the TTL or time-to-live value (default: 60) :param integer priority: the priority of the target host
[ "Create", "a", "mx", "resource", "record", "on", "a", "domain", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dns.py#L101-L113